if(typeof loaded_javascripts == "undefined") var loaded_javascripts = [];

/* file js/system.js */

loaded_javascripts[loaded_javascripts.length] = 'js/system.js';
/**
* letynsoft@letynsoft.com @ 2010-12-25
* this script is part of LetynSOFT's CMS system
* this script is part of system module
*/

DB = function () { };
DB.escape = function escape(string) {
  return (typeof string == "string" ? string : '').replace(/\\?'/, '\\\'');
}


/** the system object **/
if(typeof system == "undefined") var system = {};
/** create url_prefix variable if still does not exists **/
(function ($) {
/**
  * stackTrace(): return the function stack trace
  *
  * @returns Array: all lines in the call stack
 */
system.stackTrace = function () {
  f = arguments.callee;
  out = {};
  i = 0;
  while (f) {
    out[i++] = [f, f.caller,typeof f.name != 'undefined' ? f.name : 'no name'];
    f = f.caller;
  }
  return out;
}

system.calcPrefix = function () {
  if(window.opener) {
    w = window.opener;
    do {
      if(typeof w.system != 'undefined' && typeof w.system.url_prefix != 'undefined') {
        break;
      }
      w = window.opener;
    } while (typeof w != 'undefined' && w);
    return typeof w.system.url_prefix != 'undefined' ? w.system.url_prefix : '';
  }
  return '';
}

// if the url prefix is still not known, try getting it from parent window
if(typeof system.url_prefix == "undefined") system.url_prefix = system.calcPrefix();

/**
* getLink(): returns corect url for prefixed system paths
*
* @param URI url: the system url
*
* @returns URI: the prefixed system url
*/
system.getLink = function getLink(url) {
  p = system.url_prefix;
  if(p == null) {
    system.url_prefix = p = system.calcPrefix();
  }
  out = p.substr(-1) == '/' ? (url.substr(0, 1) == '/' ? p.substr(0, p.length-1) + url : p + url) : (url.substr(0, 1) == '/' ? p + url : p + '/' + url);
  if(url.substr(0, 1) != '/') {
    out = out.substring(1, out.length);
  }
  return out;
}

/**
  * jsonMessage(): check if the json system responce contain a message
  *
  * @param Array tjson: the system responce object
 */
system.jsonMessage = function jsonMessage(tjson) {
  if ( typeof tjson.messages != 'undefined' ) {
    for (i=0;i<tjson.messages.length;i++) {
      msg = tjson.messages[i];
      system.info(typeof msg == 'object' ? msg.message : msg, typeof msg == 'object' ? msg.type : 'info', 15);
    }
  }
}
var db;

system.tryOpenDb = function tryOpenDb() {
  if(typeof window.openDatabase == 'undefined')
    return false;
  db_name = (window.location.host+'_'+system.getLink('')).replace(/([^a-zA-Z0-9]+)/g, '-');
  db = window.openDatabase(db_name, "", 'Database for '+window.location.host+system.getLink('')+' CMS, can be removed', 1024*1024);
  return db;
}
system.checkTables = function checkTables(tables) {
  if(typeof db == 'undefined' || !db)
    return false;
  for(t in tables) {
    table_found = false;
    db.transaction(function(tx) {
      sql = 'SELECT name FROM sqlite_master WHERE name = \''+DB.escape(t)+'\' ORDER BY name;';
      tx.executeSql(sql, [], function updateString(tx, rs){
        for(j = 0;j<rs.rows.length;j++) {
          row = rs.rows.item(j);
          table_found = true;
          system.checkTable(tables[t], row['name'], false);
        }
        if(!table_found) {
          system.checkTable(tables[t], t, true);
        }
      });
    });
  }
}
system.checkTable = function checkTable(table, tablename, force_create) {
  if(typeof table != 'undefined') {
    if(force_create) {
      sql = system.sqlite.getTableCreate(tablename, table);
      system.sqlite.executeStatements(sql);
    } else {
      system.sqlite.getTableAlter(tablename, table);
    }
  }
}
system.sqlite = {};
system.sqlite.getTableCreate = function getTableCreate(tablename, table) {
  sql = "CREATE TABLE '"+tablename+"' (";
  is_first = true;
  for(i in table) {
    column = table[i];
    sql += (!is_first ? ',' : '' ) + "\n  " +
    column.key + " " + column.type +
    (typeof column.size != 'undefined' && column.size > 0 ? "(" + column.size.length + ")" : '') +
    (typeof column.additional != 'undefined' && column.additional.length > 0 ? " "+column.additional : '');
    is_first = false;
  }
  sql += "\n);";
  return sql;
}
system.sqlite.getTableAlter = function getTableAlter(tablename, table) {
  if(typeof db == 'undefined' || !db)
    return false;
  // copy the data to temporary table
  newColumns = {};
  for(i in table) {
    $k = table[i].key;
    newColumns[$k] = table[i];
  }
  sql = "select sql from sqlite_master WHERE name = '"+tablename+"'";
  currentColumns = [];
  return db.transaction(function(tx) {
    tx.executeSql(sql, [], function updateString(tx, rs) {
      if(rs.rows.length > 0) {
        //parse the sql;
        create_table = rs.rows.item(0)['sql'];
        if(typeof create_table != "undefined") {
          create_table = create_table.replace(/\n/g, "");
          if(preg = /^create table [^\(]*\((.*)\)$/i.exec(create_table)) {
            spl = preg[1].split(',');
            different = false;
            for(i in spl) {
              if(preg2 = /^ *([^ ]+) +(.+)$/.exec(spl[i])) {
                currentColumns[currentColumns.length] = preg2[1];
                if(typeof newColumns[preg2[1]] != 'undefined') {
                  column = newColumns[preg2[1]];
                  if(preg[2]!=column.type +
                  (typeof column.size != 'undefined' && column.size > 0 ? "(" + column.size.length + ")" : '') +
                  (typeof column.additional != 'undefined' && column.additional.length > 0 ? " "+column.additional : '')) {
                  } else {
                    different = true;
                  }
                } else {
                  different = true;
                }
              }
            }
            if(typeof currentColumns == 'undefined' || currentColumns.length == 0) {
              throw "FailedToFetchColumns";
            }
            if(different) {
              sql = "CREATE TABLE copy_table AS SELECT * FROM "+tablename+";"+"\n";
              sql+= "DROP TABLE "+tablename+";"+"\n";
              sql+= system.sqlite.getTableCreate(tablename, table)+"\n";
              sql+= "INSERT INTO "+tablename+" ("+currentColumns.join(',')+") SELECT "+currentColumns.join(',')+" FROM copy_table"+"\n";
              sql+= "DROP TABLE copy_table;"+"\n";
              return system.sqlite.executeStatements(sql);
            }
          }
        }
      }
    })
  });
}
system.sqlite.executeStatements = function(statements) {
  if(typeof db == 'undefined' || !db)
    return false;
  db.transaction(function(tx) {
    statements = (typeof statements == 'array' ? statements : typeof statements != 'undefined' ? statements.split(';') : ''.split(';'));
    for(i=0;i<statements.length;i++) {
      if(statements[i].replace(/^[ \n]*$/, '').length != 0) {
        tx.executeSql(statements[i], [], function updateString(tx, rs) {
        });
      }
    }
  });
}
/**
  * info(): the info notification object
  *
  * @param String message: the message to be displayed
  * @param String type: type of the message (debug, info, warning, error)
  * @param int display_time[=120]: time to display the message in seconds
 */
system.info = function (message, type, display_time) {
  system.loadJavascript('/js/jquery.timers.js');
  if ( typeof system.info.container == "undefined") {
    system.info.container = $('<div class="info-box-container"></div>').appendTo('BODY:eq(0)').css({top: $(window).scrollTop()});
  }
  if(typeof display_time == 'string') {
    if (display_time == 'long') display_time = 60;
    if (display_time == 'short') display_time = 30;
  }
  if (typeof display_time == 'undefined' || !parseInt(display_time) || display_time > 120)
    display_time = 120;
  for(j=0;j<system.info.container.children().length;j++) {
    i=system.info.container.children()[j];
    if(typeof $(i).attr('tagName') != "undefined") {
      if($(i).data('msg') == message && $(i).data('type') == type) {
        if($(i).find('.message-repeat').length == 0) {
          $('<div class="message-repeat">1</div>').insertBefore($('.message-time-line', i));
        }
        if(display_time>0)
          $(i).find('.message-time-line').stop(true).css('width', system.info.container.width()).animate({width:'0%'}, (display_time)*1000, 'linear', function () {
            $(this).parent().slideUp('slow', function () {
              $(this).remove();
            });
          });
        $(i).find('.message-repeat').attr('innerHTML', parseInt($(i).find('.message-repeat').attr('innerHTML'))+1);
        return;
      }
    }
  }
  $('<div class="message message-'+(typeof type != "undefined" ? type : 'info') +'">'+message+'</div>').slideUp(0).hide().appendTo(system.info.container).append(display_time>0?$('<div class="message-time-line"></div>').css({width: '100%', height: 1}).animate({width:'0%'}, (1+display_time)*1000, 'linear', function () {
    $(this).parent().slideUp('slow', function () {
      $(this).remove();
    });
  }):$('<div class="message-time-line"></div>').css({width: '100%', height: 1})).slideDown('slow').data('msg', message).data('type', type);
}

/**
  * info.clean(): clean all messages in info container
 */
system.info.clean = function () {
  $('.info-box-container').children().slideUp('slow', function () { $(this).remove(); });
}


system.jsBookmarks = function () {
  system.loadJavascript('/js/jquery.timers.js');
  this.addItem = function addItem(t, cn, obj) {
    this.items[this.items.length] = {
      title: t,
      cn: cn,
      object: obj
    };
  }
  this.buildDOM = function buildDOM(container, params) {
    if(typeof params == 'undefined') params = {};
    params = system.jsBookmarks.defaultParams + params;
    menu = $('<ul class="bookmarks-menu"></ul>');
    content = $('<div class="bookmarks-contents"></div>');
    for(i=0;i<this.items.length;i++) {
      menu.append((this.items[i].menu = $('<li>'+this.items[i].title+'</li>').addClass('bookmarks-label').click(function () {
        params = $(this).data('params');
        if(typeof params != 'object') params = {};
        if(typeof params.animation == 'undefined') params.animation = '';
        item_i = -1;
        children = $(this).parent().children();
        $(children).removeClass('current');
        for(i=0;i<children.length;i++) {
          if($(children[i]).get(0) == $(this).get(0)) {
            $(children[i]).addClass('current');
            item_i = i;
            break;
          }
        }
        current = $(this).parent().parent().find('>.bookmarks-contents-container>.bookmarks-contents>.bookmarks-content.shown');
        new_item = $(this).parent().parent().find('>.bookmarks-contents-container>.bookmarks-contents>.bookmarks-content:eq('+item_i+')');
        if($(current).get(0) != $(new_item).get(0)) {
          if(params.animation == 'fade') {
            current.removeClass('shown').fadeOut('slow');
            new_item.stop(true, true).fadeIn('slow').addClass('shown');
          } else if (params.animation.length == 0 || params.animation == 'scroll') {
            anim = new_item.position();
            anim.top = -anim.top;
            anim.left= -anim.left;
            new_item.parent().parent().css({position: 'relative'}).animate({height: new_item.height()});
            new_item.parent().css({position: 'absolute', height: new_item.height()}).animate(anim);
            if(new_item.height() > 0)
              new_item.css({height: new_item.height()});
          }
        }
      }).addClass('bookmark-'+(this.items[i].cn)).data('item', this.items[i]).data('params', params)));
      this.items[i].object.addClass('bookmarks-content').addClass('bookmark-'+(this.items[i].cn));
      if(params.animation == 'fade')
        this.items[i].object.hide();
      content.append(this.items[i].object);
    }
    if(typeof this.items[0] != 'undefined') {
      $(document).oneTime(100, 'bookmarks-timeout', function () {
        $('.bookmarks-menu').each(function () {
          $(this).find('>.bookmarks-label:eq(0)').click().parent().addClass('allready-initialized');
        })
      });
    }
    if(params.animation == 'fade')
      this.items[0].object.show().addClass('shown');
    $(container).append(menu);
    $(container).append($('<div class="bookmarks-contents-container"></div>').append(content));
  }
  this.getContainer = function getContainer(container) {
    if(typeof container == 'undefined') container = $('<div id="lightbox_container"></div>');
    this.buildDOM(container);
    return container;
  }
  this.showAsLightbox = function showAsLightbox(params) {
    $('#lightbox_container').remove();
    container = $('<div id="lightbox_container"></div>');
    this.buildDOM(container);
    if(typeof params == 'undefined') params = {};
    params.hideOnContentClick = false;
    $('<a href="#lightbox_container"></a>').hide().append(container).appendTo('body').fancybox(params).click();
  }
  this.items = [];
  return this;
}
system.jsBookmarks.defaultParams = {
  animation: 'fade'
}

/**
  * sortArray(): sorts the array by specified key
  *
  * @param Array array: the array to be sorted
  * @param String field: the field to be sorted by
  * @param String sorting: the result order (asc or desc)
 */
system.sortArray = function sortArray (array, field, sorting) {
  if(typeof sorting == 'undefined' || sorting == null || $.inArray(sorting, ['asc', 'desc']))
    sorting = 'asc';
  do {
    sorted = true;
    for(i = 0; i < array.length -1; i++) {
      if(typeof array[i] != "undefined" && array[i] != null && typeof array[i + 1] != "undefined" && array[i + 1] != null) {
        i1 = array[i];
        i2 = array[i+1];
        if(typeof i1[field] == 'undefined' || i1[field] == null) i1[field] = 0;
        if(typeof i2[field] == 'undefined' || i2[field] == null) i2[field] = 0;
        if(i1[field] > i2[field] && sorting != 'desc' || i1[field] < i2[field] && sorting == 'desc') {
          array[i]   = i2;
          array[i+1] = i1;
          sorted = false;
        }
      }
    }
  } while (!sorted);
  return array;
}

/**
  * parseClassToAssoc(): parse className to object
  *
  * @param String prefix: the className item prefix to parse
  *
  * @returns Array: the associative array of className items
 */
$.extend($.fn, {
  parseClassToAssoc: function (prefix) {
    out = [];
    cl = $(this).attr('className');
    classes = cl.split(' ');
    reg=/^_(.*)\-\-(.*)$/;
    for(i=0;i<classes.length;i++) {
      cl = classes[i];
      if(cl.indexOf(prefix) == 0){
        cl = cl.substr(prefix.length);
        if((preg = reg.exec(cl)) && preg[1].length > 0) {
          if(typeof out[preg[1]] == 'undefined') out[preg[1]] = new Array();
          out[preg[1]].push(preg[2]);
        }
      }
    }
    return out;
  },
  indexOf: function (item) {
    out = -1;
    $.each(this, function(i, it) {
      if(item == it) {
        out = i;
      }
    });
    return out;
  }
});
/** create loaded_javascripts array, if still not present **/
system.loaded_javascripts = typeof loaded_javascripts != 'undefined' && loaded_javascripts != null ? loaded_javascripts : [];

/**
  * loadJavascript(): load javascript file
  *
  * @params URI path: the script url to load
 */
system.loadJavascript = function (path) {
  patht = path;
  while(patht.substring(0, 1) == '/')
    patht = patht.substring(1);
  if($.inArray(patht, system.loaded_javascripts) == -1) {
    $.ajaxSetup({ async: false });
    p = system.getLink(patht);
    out = $.getScript(window.location.protocol+'//'+window.location.host+'/'+(p.substring(0, 1) == '/' ? p.substring(1) : p), function () {
      system.loaded_javascripts[patht] = true;
    });
    $.ajaxSetup({ async: true });
  }
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

$.extend($.fn, {
  sprintf: function () {
    var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
    while (f) {
      if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
      else if (m = /^\x25{2}/.exec(f)) o.push('%');
      else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
        if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
        if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
          throw("Expecting number but found " + typeof(a));
        switch (m[7]) {
          case 'b': a = a.toString(2); break;
          case 'c': a = String.fromCharCode(a); break;
          case 'd': a = parseInt(a); break;
          case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
          case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
          case 'o': a = a.toString(8); break;
          case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
          case 'u': a = Math.abs(a); break;
          case 'x': a = a.toString(16); break;
          case 'X': a = a.toString(16).toUpperCase(); break;
        }
        a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
        c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
        x = m[5] - String(a).length;
        p = m[5] ? $.fn.str_repeat(c, x) : '';
        o.push(m[4] ? a + p : p + a);
      }
      else throw ("Huh ?!");
      f = f.substring(m[0].length);
    }
    return o.join('');
  },
  str_repeat: function (i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }
});
$(document).ready(function () {
  $(document).trigger('documentChanged');
})
$(document).bind('documentChanged', function () {
  /** do we debug?, add same string to links **/
  preg = /debug=([,a-z_-]+)[&]?/;
  if(ret = preg.exec(window.location)) {
    $('a, form').each(function () {
      if($(this).get(0).tagName == 'A') {
        attribute = 'href';
      } else if ($(this).get(0).tagName == 'FORM') {
        attribute = 'action';
      }
      link = $(this).attr(attribute);
      if(typeof link == 'string')
        if(link.indexOf('debug') == -1) {
          link += (link.indexOf('?') == -1 ? '?' : '&') + 'debug='+ret[1];
          $(this).attr(attribute, link);
        }
    })
  }
  $('.node-function.node-link-delete').die('click')
  if($('.node-function.node-link-delete').length > 0) {
    system.loadJavascript('/js/translation.js');
  }
  $('.node-function.node-link-delete').live('click', function () {
    if(confirm(t('Are you sure you want to delete this node?'))) {
      url = $(this).attr('href');
      window.location.assign(url+(url.indexOf('?') == -1 ? '?' : '&')+'confirm=1');
    }
    return false;
  })
  /** load translation class if it will be used **/
  if($('a.function-delete').length > 0)
    system.loadJavascript('/js/translation.js');
  /** delete item click event **/
  $('a.function-delete').die('click', system.functionDelete);
  $('a.function-delete').live('click', system.functionDelete);
  /** scroll info object container when scrolling **/
  $(window).unbind('scroll', system.window_scroll);
  $(window).scroll(system.window_scroll);
  /* do we have address plugin loaded? */
  while(typeof $.address != 'undefined') {
    // can we trust md5?
    if(typeof md5sum == "undefined" || !md5sum.vm_test()) {
      break;
    }
    if($('div#page_loader').length == 0) {
      $('<div id="page_loader">').appendTo('body:eq(0)').data('loaders', 0).click(function () {
        $(this).loader({action: 'remove'});
      });
    }
    preg = /debug=([,a-z_-]+)[&]?/;
    if(ret = preg.exec(window.location)) {
      break;
    }
    running_first = true;
    $.address.init(function(event) {
      // Initializes plugin support for links
    }).change(function (e) {
      current_link = e.value.length > 0 ? (running_first ? system.last_link : e.value) : window.location.pathname+window.location.search;
      running_first = false;
      if(system.last_link != current_link) {
        $('div#page_loader').loader({action: 'add'});
        url = system.getLink('/Node/ajaxContents');
        params = e.parameters;
        params.type = 'ajax';
        params.load_url = current_link;
        $.get(url, params, system.replaceContents, 'json');
      }
      system.last_link = current_link;
      return e.path;
    });
    $('a:not([href^=http])').address();
    $('form:not([method=post])').address();
    $('form[method=post]').submit(function () {
      preg = /debug=([,a-z_-]+)[&]?/;
      if(ret = preg.exec(window.location)) {
      } else {
        // now we need to post the post forms
        data = {};
        $(':text, :password, :hidden, :selected, :checked, :submit, textarea', this).each(function () {
          data[$(this).attr('name')] = $(this).val();
        });
        url = system.getLink('/Node/ajaxContents');
        data.load_url = $(this).attr('action');
        $.address.value(data.load_url);
        $.post(url+((url.indexOf('?') == -1) ? '?' : '&')+'type=ajax', data, system.replaceContents);
        return false;
      }
    });

/*    $('a').address(function () {
      $('div#page_loader').loader({action: 'add'});
      $.get(system.getLink('/Node/ajaxContents'), {type: 'ajax', load_url: $(this).attr('href')}, system.replaceContents, 'json');
      return $(this).attr('href');
    });
    */
    break;
  }
  system.loadJavascript('/js/jquery.timers.js');
});
$.extend($.fn, {
  loader: function loader(params) {
    params = $.extend({}, params);
    loaders = $(this).data('loaders');
    if(params.action == 'remove') {
      $(this).data('loaders', loaders - 1);
      if(loaders == 1) {
        // hide the loader
        $(this).stop(true);
        $(this).fadeTo('slow', 0, function() {
          $(this).slideUp('slow', function() {
            $(this).css('display', 'none');
          })
          $('html').css({overflow: ''});
        });
      }
    } else {
      $(this).data('loaders', 1);
      if(loaders == 0) {
        // show the loader
        $('html').css({overflow: 'hidden'});
        $(this).css({display: 'block', width: '100%', height: '100%', background: 'grey', position: 'absolute', top: $(document).scrollTop(), left: $(document).scrollLeft()});
        $(this).stop(true).slideDown(0).fadeOut(0).fadeTo('slow', 0.5, function() { });
      }
    }
  },
  lightboxTree: function lightboxTree(o,v) {
    o = $(this).data('o', o);
    if($(this).length == 0)
      return ;
    me = $.fn.lightboxTree;
    if(typeof me.defaultOptions == 'undefined') {
      // first init, setup statics
      me.defaultOptions = {
        data_url: '',
        return_key: 'id',
        parent_key: 'parent_id',
        name_key: 'name',
        open_event: 'focus',
        tree: null,
        open_event_target: false,
        value: null,
        multiple: false,
        item_template: null,
        tree_action: 'get_tree',
        selectCallback: null,
        closeCallback: null,
        open: false,
        as_window: false
      };
      me.functions = [];
      me.printData= function (tjson, options) {
        to_print = '';
        system.jsonMessage(tjson);
        if(typeof tjson.items != 'undefined') {
          container = $('<ul></ul>');
          items = [];
          for(i in tjson.items) {
            it = tjson.items[i];
            if (options.multiple) {
              i_ = new system.item('lightboxTree-item', it[options.return_key], 'checkbox');
            } else {
              i_ = new system.item('lightboxTree-item', it[typeof options.child_id_key != 'undefined' ? options.child_id_key : options.return_key], 'radio');
            }
            i_.setVar('title', it[options.name_key]);
            if (typeof options.value == 'string' && $.inArray(it[options.return_key], (options.value).split(',')) != -1) {
              i_.setVar('checked', 'checked');
            }
            li = $('<li>'+i_.getHtml()+'</li>');
            if(options.item_template === null) {
              li.append('<span class="title clickable">'+it[options.name_key]+'</span>');
            } else {
              t = options.item_template;
              if (typeof t == 'function') {
                li.append(t(it, i_));
              } else if (typeof t == 'string') {
                if(t.substring(0, 1) == '#') {
                } else {
                  $.template( 'lightboxTree-ItemTemplate', t );
                  $.tmpl( 'lightboxTree-ItemTemplate', it ).appendTo(li);
                }
              }
            }
            rk = it[typeof options.child_id_key != 'undefined' ? options.child_id_key : options.return_key]
            li.data('return_key', rk);
            li.data('lightboxTree_options', options);
            li.data('item', it);
            if(typeof options.selectCallback == 'function') {
              li.find('input').bind('change', options.selectCallback);
            }
            $('#fancy_content li span.title, #general_panel li span.title').die('click');
            $('#fancy_content li span.title, #general_panel li span.title').live('click', function () {
              me = $.fn.lightboxTree;
              options = $(this).parents('li:eq(0)').data('lightboxTree_options');
              rk = $(this).parents('li:eq(0)').data('return_key');
              me.loadData(this, options, rk, true);
            })
            tit = li.find('span.title');
            if(tit.length > 0) {
              tit.data('return_key', rk);
              tit.data('lightboxTree_options', options);
            }
            if(typeof to_print == 'string') {
              to_print = $(li);
            } else {
              to_print = $(to_print).add(li);
            }
          }
        }
        return to_print;
      }
      me.loadData= function loadData(aThis, options, item_id, async) {
        $(aThis).addClass('lightboxTree-loading-data');
        opts = {type: 'ajax'}
        opts[options.parent_key] = item_id;
        par = $('#fancy_content, #general_panel').find('input[name=lightboxTree-item][value='+item_id+']').parent();
        if(par.length > 0 && (ul = par.find('ul.lightboxTree:eq(0)')).length > 0) {
          //is it open?
          if(ul.css('display') == 'none') {
            // we want to open siblings of the item, that is beeing opened
            arr = $(par).siblings();
            //arr.splice(arr.indexOf(par), 1);
            arr.slideUp('slow');
          } else {
            arr = $(par).siblings();
            //arr.splice(arr.indexOf(par), 1);
            arr.slideDown('slow');
            ul.find('ul.lightboxTree').slideUp('slow');
            ul.find('input[name=lightboxTree-item]').parent().slideDown('slow');
          }
          ul.slideToggle('slow');
        } else {
          arr = $(par).siblings();
          //arr.splice(arr.indexOf(par), 1);
          arr.slideUp('slow');
          $(aThis).slideDown('slow');
          $(par).addClass('loading');
          if(typeof async == 'undefined' || async !== true) {
            $.ajaxSetup({async: false});
          }
          $.get(system.getLink(options.data_url), opts, function (tjson) {
            $('.lightboxTree-loading-data').removeClass('lightboxTree-loading-data');
            me = $.fn.lightboxTree;
            f = $('#fancy_content');
            if(f.length == 0) {
              f = $('#general_panel');
            }
            data = me.printData(tjson, options);
            if($('ul.lightboxTree', f).length == 0) {
              $('#fancybox_temp').remove();
              $('<div id="fancybox_temp"></div>').appendTo('body').css('display', 'none').append($('<ul class="lightboxTree">').append(data));
              opts = {hideOnContentClick: false, allowRemove: true, autoDimensions: true, callbackOnClose: function () {
                out = [];
                checkboxes = $(':checked' ,$('#fancy_content'));
                if(checkboxes.length > 0)
                checkboxes.each(function () {
                  out.push($(this).val());
                });
                lio = $('.lightbox-is-open');
                if(lio.length > 0) {
                  options = lio.data('lightboxTree_options');
                  options.value = out.join(',');
                }
                if(typeof options.closeCallback == 'function' && options.closeCallback != null) {
                  options.closeCallback(out, options);
                } else {
                  lio.val(out.join(','));
                  lio.change();
                }
                lio.removeClass('lightbox-is-open');
                $('lightboxTree-opener').removeClass('lightboxTree-opener');
                $('#fancy_content').html('');
              }, onComplete: function () {
                $('#fancybox_temp').remove();
              }};
              if(typeof options.fancy_width != 'undefined') opts.frameWidth = options.fancy_width;
              if(typeof options.fancy_height != 'undefined') opts.frameHeight = options.fancy_height;
              if(typeof options.open_in != 'undefined') {
                $(options.open_in).append($('#fancybox_temp').children());
              } else {
                $('<a href="#fancybox_temp"></a>').fancybox(opts).click();
              }
            } else {
              par = f.find('input[name=lightboxTree-item][value='+item_id+']').parent();
              arr = $(par).siblings();
              arr.splice(arr.indexOf(par), 1);
              arr.slideUp('slow');
              par.removeClass('loading');
              par.find('ul').remove();
              par.append($('<ul class="lightboxTree">').append(data)).find('ul').slideUp(0).slideDown('slow');
            }
          }, 'json');
          if(typeof async == 'undefined' || async !== true) {
            $.ajaxSetup({async: true});
          }
        }
      }
    }
    system.loadJavascript('js/item.js');
    $(this).each(function () {
      o = $(this).data('o');
      if (typeof o == 'object') {
        options = {};
        options = $.extend(options, me.defaultOptions, o, {originator: this});
        if(typeof options.value == 'undefined' || options.value == null)
          options.value = $(this).val();
        $(this).data('lightboxTree_options', options);
        action='options';
      } else if (typeof o == 'string' && $.inArray(o, me.functions) > -1) {
        action='function';
      } else if (typeof o == 'string' && typeof me.defaultOptions[o] != 'undefined') {
        options = $(this).data('lightboxTree_options');
        if(typeof options != 'undefined') {
          options = $.extend({}, options, {o: v});
        } else {
          options = {o: v};
        }
        $(this).data('lightboxTree_options', options);
        action='option';
      } else {
        system.info(t('Failed to determine action %s', o), 'warning');
      }
      if(action == 'options') {
        // we need to initialize the lightboxTree
        $(this).addClass('lightboxTree-opener');
        target = this;
        if(typeof options.open_event_target == 'object') {
          target = options.open_event_target;
        } else if (typeof options.open_event_target == 'string') {
          target = $(target).parent().find(options.open_event_target);
        }
        $(target).unbind(options.open_event);
        $(target).bind(options.open_event, function () {
          i_ = $($(this).data('lightboxTree-input')).addClass('loading');
          if(!i_.hasClass('lightbox-is-open')) {
            i_.addClass('lightbox-is-open');
            i_.trigger('lightboxTree-open');
          }
          return false;
        }).data('lightboxTree-input', this);
        $(this).unbind('lightboxTree-open');
        $(this).data('lightboxTree_options', options).bind('lightboxTree-open', function (e) {
          me = $.fn.lightboxTree;
          options = $(this).data('lightboxTree_options');
          // we need to load the tree for all selected items
          load_tree = [];
          me.loadData(this, options, 0, ((""+options.value).length > 0) ? false : true);
          opts = {action: options.tree_action, type: 'ajax'};
          opts[options.return_key] = options.value;
          $.get(system.getLink(options.data_url), opts, function (tjson) {
            load_tree = [];
            for(i=tjson.items.length-1;i>=0;i--) {
              load_tree[load_tree.length] = tjson.items[i];
            }

            for(load_i=0;load_i<load_tree.length;load_i++) {
              if(typeof load_tree[load_i] != 'undefined' && (""+load_tree[load_i]).length > 0 && load_tree[load_i] != null) {
                par = $('#fancy_content').find('input[name=lightboxTree-item][value='+load_tree[load_i]+']').parent();
                me.loadData(par, options, load_tree[load_i], false);
              }
            }
          }, 'json');
        });
        if(options.open) {
          $(target).trigger(options.open_event);
        }
      } else if (action == 'option') {
        options[o] = v;
        $(this).data('lightboxTree_options', options);
      }
    });
  }
});
system.last_link = window.location.pathname+window.location.search;
system.window_scroll = function window_scroll() {
  if(typeof system.info.container != 'undefined' && system.info.container.length > 0) {
    system.info.container.css({top: (typeof window.scrollY != "undefined" ? window.scrollY : (typeof window.offsetTop != "undefined" ? window.offsetTop : 0))+"px"});
  }
}
system.functionDelete = function functionDelete() {
  if(confirm(system.translation.getString('Are you sure you want to remove this item?'))) {
    url = $(this).attr('href');
    if(preg = /(.*)sbmt=([^&]*)&?(.*)/.exec(url)) {
      url = preg[1]+'sbmt='+system.translation.getString('Yes')+'&'+preg[3];
    } else {
      url += (url.indexOf('?') != -1 ? '&' : '?') + 'sbmt='+system.translation.getString('Yes')
    }
    window.location.assign(url);
    return false;
  } else {
    return false;
  }
}
system.concatContent = function concatContent(contents) {
  contents = system.sortContent(contents);
  positions = {};
  for(position in contents ) {
    items = contents[position];
    for(content_k in items) {
      if(typeof positions[position] == 'undefined') positions[position] = '';
      content = items[content_k];
      positions[position] = positions[position]+content['content'];
    }
  }
  return positions;
}
system.sortContent = function sortContent(contents, params) {
  if(typeof params == 'undefined') { params = {}; }
  if(typeof params.sorting == 'undefined' || $.inArray(params.sorting, ['asc', 'desc']) == -1) { params.sorting = 'asc'; }
  for(j in contents){
    item = contents[j];
    system.sortArray(item, 'weight', params['sorting']);
  }
  return contents;
}
system.replacingContents = [];
system.replaceContents = function (tjson) {
  system.jsonMessage(tjson);
  positions = system.concatContent(tjson.contents);
  /* load the required javascripts */
  for(i in tjson.page_headers) {
    h = tjson.page_headers[i];
    if(h.header_type == 'text/javascript') {
      if(h.params.type == 'file') {
        system.loadJavascript(h['content'])
      } else if (h.params.type == 'inline') {
        eval(h['content']);
      }
    }
    if(h.header_type == 'http-equiv') {
      if(h.content.toLowerCase() == 'refresh') {
        if(preg=/; *url=(.*)$/i.exec(h.params.content)) {
          system.info('Redirecting you to '+preg[1], 10);
          window.redirect_to = preg[1];
          $(document).oneTime(2000, function () {
            window.location.assign(window.redirect_to);
            window.redirect_to = null;
          })
        }
      }
    }
  }

  ///* now lets compare the html
  found_columns = [];
  system.replacingContents = [];
  for(i in positions) {
    $('#'+i).each(function () {
      found_columns[found_columns.length] = i;
      if($(this).html() != positions[i]) {
        $('body').addClass('with-'+(i.replace(/_/g, '-')));
        system.replacingContents[i] = 1;
        $(this).stop(true).fadeTo('slow', 0, function () {
          str = $(this).data('new_html');
          $(this).children().remove();
          obj = $(this).append($(str));
          system.replacingContents[$(this).data('position')] = 0;
          trigger = true;
          for(i in system.replacingContents) {
            if(system.replacingContents[i] == 1) {
              trigger = false;
            }
          }
          obj.fadeTo('slow', 1, function () { });
          if(trigger) {
            $('div#page_loader').loader({action: 'remove'});
            $(document).trigger('documentChanged');
          }
        }).data('new_html', positions[i]).data('position', i);
      }
    })
  }
  for(i in tjson.positions) {
    if(typeof tjson.positions[i] == 'string' && $.inArray(tjson.positions[i], found_columns) == -1) {
      $('body').removeClass('with-'+(tjson.positions[i].replace(/_/g, '-')));
      $('#'+tjson.positions[i]).fadeTo('slow', 0, function () {
        $(this).html('');
      });
    }
  }
}
system.messageLogShowSec = 5;
system.messageLog = function messageLog(type, message, time) {
  time = typeof time != "undefined" && time != 0 ? time : system.messageLogShowSec;
  container = $('ul.messageLogContainer');
  if(container.length == 0)
    container = $('<ul class="messageLogContainer"></div>').appendTo('Body:eq(0)');
  container.append($('<li class="message-'+type+'">'+message+'</li>').oneTime(time, function () { $(this).remove(); }));
}
})(jQuery);

/** set console to dummy object **/
if(typeof console == 'undefined') {
  console = function () {};
}

/** set console.log to alert **/
if(typeof console.log == 'undefined') {
  console.log = function (str) {
    alert(str);
  }
}

/**
  * window.var_dump(): output all arguments to console.log
 */
function var_dump() {
  //console.log(system.stackTrace());
  for(_i_=0;_i_<arguments.length;_i_++) {
    console.log(arguments[_i_]);
  }
}

