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

/* file js/item.js */

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

(function ($) {
/**
  * getDatabaseConnectionUrl(): returns database connection url get from inputs in specified container
  *
  * @param Node parent: the parent of the inputs (lightbox object for example)
  *
  * @returns String: Database connection url (Usable for Adodb, easily parsable)
 */
function getDatabaseConnectionUrl(parent) {
  driver = $('select.database-connection-driver', parent).val();
  username = $('input.database-connection-username', parent).val();
  password = $('input.database-connection-password', parent).val();
  server = $('input.database-connection-server', parent).val();
  database = $('input.database-connection-database', parent).val();
  out = driver;
  out+= '://'+username;
  if(password.length > 0)
    out+= ':'+password;
  out+= '@'+server;
  out+= '/'+database;
  return out;
}

/**
  * getConnectionUrl(): get access url for non-db server
  *
  * @param Node parent: the parent of the inputs (lightbox object for example)
  *
  * @returns String: Access url
 */
function getConnectionUrl(parent) {
  driver = $('select.connection-driver', parent).val();
  username = $('input.connection-username', parent).val();
  password = $('input.connection-password', parent).val();
  server = $('input.connection-server', parent).val();
  path = $('input.connection-path', parent).val();
  out = driver;
  out+= '://'+username;
  if(password.length > 0)
    out+= ':'+password;
  out+= '@'+server;
  out+= ':'+path;
  return out;
}

/**
  * system.item(): javascript implementation of form_item class
  *
  * @param String key_: name of the form item
  * @param String value: the value of the form item
  * @param String type: type of the form item
  *
  * @returns Object: Javascript formitem object
 */
system.item = function (key_, value, type) {
  this.variables = [];
  this.init = function (key_, value, type) {
    if(type == 'print'){
      this.setVar('id', '');
    }
    if(type == 'multiple') {
      this.setVar('type', 'dropdown');
      this.setVar('size', 4);
      this.setVar('multiple', 'multiple');
    }
    if(type == 'number') {
      this.setVar('type', 'text');
      cl = this.getVar('class', '');
      if(cl.indexOf('input-check-number') == -1) {
        this.setVar('class', cl+(cl.length > 0 ? ' ' : '')+'input-check-number');
      }
    }
    if(type == 'boolean') {
      this.setVar('type', 'checkbox');
      val = this.getVar('value', '0');
      if (val == true) {
        this.setVar('checked', 'checked');
      }
      if(val.length == 0)
        this.setVar('value', '1');
    }
    if($.inArray(type, system.item.inputTypes) != -1) {
      this.setVar('is_input', true);
      if(type == 'file') {
        if(value != null) {
          this.setVar('value', null);
        }
      }
    }
    if(type == 'weight') {
      this.setVar('type', 'dropdown');
      this.setVar('options', [
        -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
      ]);
    }
  }

  /**
    * setVar(): set instance variable of form item
    *
    * @param String variable: the variable name to set
    * @param mixed value: the variable value
    *
    * @returns Javascript formitem object
   */
  this.setVar = function (variable, value) {
    if(typeof variable == 'string' && variable.length > 0)
      this.variables[variable] = value;
      if(variable == 'require_javascript') {
        for(i in value) {
          system.loadJavascript(value[i])
        }
      }
    return this;
  }

  /**
    * getVar(): returns instance variable value
    *
    * @param String variable: the required variable name
    * @optional mixed tdefault: default value for the variable
    *
    * @returns mixed: Instance variable value
   */
  this.getVar = function (variable, tdefault) {
    if(typeof this.variables[variable] != 'undefined')
      return this.variables[variable]
    if(typeof tdefault == 'undefined')
      tdefault = null;
    return tdefault;
  }

  /**
    * getLabelFor(): returns HTML label for current form item
    *
    * @returns HTML/String: label of item
   */
  this.getLabelFor = function () {
    id = this.getVar('id', '');
    title = this.getVar('title', this.getVar('name', ''));
    if(id.length > 0) {
      return '<label for="'+id+'">'+t(title)+'</label>';
    }
    return title;
  }

  /** is this type supported **/
  if($.inArray(type, system.item.itemTypes) == -1 && typeof type != "function") {
    if(typeof console != "undefined") {
      console.warn('Used undefined type "'+type+'" for system.item, printing stacktrace');
      //console.warn(system.stackTrace());
    }
    alert ('Used undefined type ("'+type+'") for system.item');
  }
  /** empty name variable **/
  if(key_ == null) {
    key_ = '';
  }
  this.setVar('key',  key_);
  if(key_.length > 0)
    this.setVar('name', key_);
  key_fixed = key_.replace(/[^a-zA-Z0-9\_\-\.]+/, '_');
  if(key_fixed.length > 0)
    this.setVar('id',   key_fixed);
  this.setVar('type', type);
  try {
    this.setVar('value',value);
  } catch (ex) {
  }

  /** setup the item **/
  this.init(key_fixed, value, type);

  /**
    * getHtml(): return the item HTML implementation
    *
    * @returns HTML/String: the item HTML implementation
   */
  this.getHtml = function () {
    if(typeof this.getVar('output_html') == 'undefined' || this.getVar('output_html') == null) {
      if (typeof this.getVar('is_input') != 'undefined' && this.getVar('is_input') == true) {
        cl = this.getVar('class', '');
        cl+= (cl.length > 0 ? ' ' : '') + 'input-'+this.getVar('type');
        this.setVar('class', cl);
        str = '<input type="'+this.getVar('type')+'"'+this.printArgs('type')+' />';
      } else if (this.getVar('type') == 'dropdown'){
        str = '<select'+this.printArgs(data, 'value')+'>'+this.printOptions()+'</select>';
      } else if (this.getVar('type') == 'image'){
        str = '<input type="hidden" '+this.printArgs('type')+' />';
      } else if (this.getVar('type') == 'textarea' || this.getVar('type') == 'wysiwyg'){
        str = '';
        if(this.getVar('type') == 'wysiwyg') {
          if(typeof this.getVar('id') == "undefined" || this.getVar('id').length == 0) {
            this.getVar('id') = 'wysiwyg';
          }
          init_options = this.getVar('init_options');
          obj_str = '';
          for(key in init_options) {
            val = init_options[key];
            obj_str += (obj_str.length > 0 ? ",\n" : '')+key+': '+(typeof val == 'bool' ? (val ? 'true' : 'false') : (typeof val == 'string' ? '"'+val.replace('"', '\\"')+'"' : (typeof val == 'number' ? (isNaN(parseInt(val)) ? 0 : parseInt(val)) : '"error"')));
          }
str = "\n"+
  '          <script type="text/javascript"><!--'+"\n"+
  '            tinyMCE.init({'+"\n"+obj_str+','+
  '              elements : "'+this.getVar('id')+'",'+"\n"+
  '            });'+"\n"+
  '--></script>';
        }
        str += '<textarea'+this.printArgs('value', 'rows=5,cols=23')+'>'+(typeof this.getVar('value') != "undefined" ? this.getVar('value') : '')+'</textarea>';
      } else {
        str = this.getVar('type');
      }
    } else {
      str = this.getVar('output_html');
    }
    return str;
  }

  /**
    * printOptions(): prints select item options list
    *
    * @returns HTML: The options HTML implementation
   */
  this.printOptions = function() {
    str = '';
    options = this.getVar('options', []);
    selected = new Array();
    if(typeof this.getVar('value') != "undefined") {
      val = this.getVar('value');
      if (val.length > 0 || val == 0) {
        if(typeof val != "object")
          selected = val.split(',');
        else
          selected = val;
      }
    }
    ititle = (this.getVar('title').length != 0 ? this.getVar('title') : this.getVar('name'));
    if (ereg = /(.*)-[0-9]+$/.exec(ititle))
      ititle = ereg[1];
    if (typeof options == "object") {
      for (key_ in options) {
        valu = options[key_];
        val = (typeof valu == 'object' && valu['valu'].length > 0 ? valu['valu'] : valu);
        title_t = (typeof valu == 'object' && typeof valu['title'] != "undefined" ? valu['title'] : '');
        n = this.getVar('key');
        if (ereg = /(.*)-[0-9]+$/.exec(n))
          n = ereg[1];
        sel = false;
        for(i in selected)
          if(selected[i] == val)
            sel = true;
        str += '  <option value="'+val+'"'+(sel ? ' selected="selected"' : '')+'>'+(title_t.length > 0 ? title_t : (ititle.length > 0 ? ititle + ' - ' : '') +  val)+'</option>'+"\n";
      }
    }
    return str;
  }

  /**
    * printArgs(): prints element arguments
    *
    * @param Array invalid: array of allready printed arguments
    * @param Array required: array of required arguments, that has to be printed
   */
  this.printArgs = function (invalid, required) {
    allowed = ['id', 'name', 'value', 'style', 'class', 'onchange', 'onclick', 'onmousedown', 'onmouseup', 'onfocus', 'onblur', 'onkeyup', 'onkeydown','checked'];
    shown = [];
    str = '';
    if(typeof invalid != "object" || invalid == null)
      invalid = [];
    for(i in this.variables) {
      valid = false;
      for(j in allowed) {
        val = allowed[j];
        if(i == val) {
          valid = true;
        }
      }
      if(this.getVar('is_input') != 1 && i == 'value')
        valid = false;
      if(valid) {
        for(j in invalid) {
          val = invalid[j];
          if(i == val) {
            valid = false;
          }
        }
      }
      if(valid) {
        shown[shown.length] = i;
        str += ' '+i+'="'+this.variables[i]+'"';
      }
    }
    if(required != null) {
    }
    return str;
  }
}

/** init persistent variables **/
system.item.ajax_result = []
system.item.type_searches = [];
system.item.last_type_search = [];
system.item = system.item;
system.item.lastItemChanged = null;
system.item.lastItemChangedUpdated = null;
system.item.inputTypes = ['hidden', 'text', 'password', 'number', 'email', 'phone', 'date', 'time', 'checkbox', 'radio', 'button', 'submit', 'file'];
system.item.itemTypes = ['hidden', 'text', 'password', 'number', 'email', 'phone', 'date', 'time', 'checkbox', 'radio', 'button', 'submit', 'dropdown', 'multiple', 'weight', 'textarea', 'wysiwyg', 'file', 'image'];
system.item.formChangeListeners = [];

/**
  * formChange(): adds function to formChangeListeners array
  *
  * @param function fb_nc: the callback function
  *
  * @returns function: the added function
**/
system.item.formChange = function (fb_nc) {
  //system.stackTrace();
  system.item.formChangeListeners[system.item.formChangeListeners.length] = fb_nc;
  return fb_nc;
}

/**
  * modifyForm(): callback of ajax changeform due to item type change
  *
  * @param Array dt: the json result
  * @param String name_prefix: current prefix of the item type
 */
system.item.modifyForm = function (dt, name_prefix) {
  lastobj = null;
  dt = system.sortArray(dt, 'weight');
  for (i in dt) {
    data = dt[i];
    if(typeof data != 'object' || data.length == 0)
      continue;
    reg = /(.*)-([0-9]+)-$/;
    system.item.name_prefix
    if(out = reg.exec(name_prefix))
      name_prefix = out[1]+'-'+data['system.item_id'];
    $(system.item.lastItemChanged).attr('id', $(system.item.lastItemChanged).attr('id').replace('/'+system.item.name_prefix+'/', name_prefix));
    it = new system.item ((typeof data['name'] != "undefined" ? data['name'] : '__eee__'), typeof data['value'] != 'undefined' ? data['value'] : null, typeof data['type'] != 'undefined' ? data['type'] : null);
    it.setVar('require_javascript', data.require_javascript);
    it.setVar('output_html', data['output_html']);
    it.setVar('init_options', data['init_options']);
    cl = (typeof data['class'] != "undefined" ? data['class']+' ' : '')+'generated-system.item';
    it.setVar('class', cl);
    str = '';
    str = it.getHtml();
    short_name = '';
    if(ereg = /(.*)-([0-9]+)-(.*)/.exec(data['name'])) {
      short_name = ereg[1]+'-'+ereg[2]+' ';
    }
    text_str = str;
    nm = t(""+data['title']);
    obj = $('<tr class="'+short_name+data['name']+'"><th>'+ nm + '</th><td>'+text_str+'</td></tr>');
    if(lastobj == null && (typeof system.item.lastItemChangedUpdated == "undefined" || system.item.lastItemChangedUpdated == null)) {
      $(obj).addClass($(system.item.lastItemChanged).parent('TR').hasClass('row-odd') ? 'row-even' : 'row-odd');
      $(obj).insertAfter($(system.item.lastItemChanged).parents('TR'));
    } else if (typeof system.item.lastItemChangedUpdated != "undefined" && system.item.lastItemChangedUpdated != null) {
      //$(obj).addClass(system.item.lastItemChangedUpdated.hasClass('row-odd') ? 'row-even' : 'row-odd');
      $(obj).insertAfter(system.item.lastItemChangedUpdated);
    } else {
      $(obj).addClass(lastobj.hasClass('row-odd') ? 'row-even' : 'row-odd');
      $(obj).insertAfter(lastobj);
    }
    lastobj = obj;
  }
  $('tr.'+system.item.old_name_prefix).each(function() {
    while ($(this).get(0).className.indexOf(system.item.old_name_prefix) != -1) {
      $(this).get(0).className = $(this).get(0).className.replace(system.item.old_name_prefix, name_prefix);
      $('input, textarea, select', $(this)).each(function () {
        while (this.className.indexOf(system.item.old_name_prefix) != -1)
          this.className = this.className.replace(system.item.old_name_prefix, name_prefix);
        while (this.name.indexOf(system.item.old_name_prefix) != -1)
          this.name = this.name.replace(system.item.old_name_prefix, name_prefix);
        while (this.id.indexOf(system.item.old_name_prefix) != -1)
          this.id = this.id.replace(system.item.old_name_prefix, name_prefix);
      });
    }
  });
  $('tr.'+system.item.name_prefix).each(function() {
    $(this).removeClass('row-even').removeClass('row-odd').addClass($(this).prev().hasClass('row-odd') ? 'row-even' : 'row-odd');
  });
  o = {};
  /* new way of triggering the change */
  $(document).trigger('documentChanged');
  /*
  for(i = 0; i < system.item.formChangeListeners.length; i++) {
    ;
    if(typeof system.item.formChangeListeners[i] == 'function' && system.item.formChangeListeners[i] != null) {
      system.item.formChangeListeners[i]();
    }
  }
  */
}

/**
  * removeMyItemsFromForm(): removes all items with specified prefix
  *
  * @param String prefix: the prefix to be removed
 */
system.item.removeMyItemsFromForm = function (prefix) {
  $('tr.generated-system.item').each(function (){
    if(system.item.lastItemChangedUpdated == null)
      $(this).prev();
    if(mat = /^([^\-]+)-([^\-]+)-([^\-]+)$/.exec(this.id)) {
      if(mat[1]+"-"+mat[2] == prefix) {

        $(this).parents().each(function() {
          reg = /(.*)-([0-9]+)-(.*)$/;
          if(this.tagName == 'TR' && reg.test(this.className)) {
            $(this).remove();
          }
        });
      }
    }
  });
}

/**
  * loadResultPreview(): print type-to-search result box
  *
  * @param Node row: the row container
  * @param String module: the module which is beeing used
  * @param String fn: the function name to call in php
 */
system.item.loadResultPreview = function (row, module, fn) {
  valu = $('input.type-result', row).val();
  $.ajaxSetup({async: false});
  module = module || $('input.type-search').attr('ajax_module');
  fn = fn || $('input.type-search').attr('ajax_function');
  $.post(system.getLink('/'+module+'/'+fn+'?type=ajax'), {item_id: valu}, function (tjson) {
    system.jsonMessage(tjson);
    system.item.ajax_result[module] = system.item.ajax_result[module] || [];
    field_id = 'field_id';
    if(typeof tjson.fields != 'undefined') {
      if(typeof tjson.fields.field_id != 'undefined')
        field_id = tjson.fields.field_id;
    }
    for(i in tjson.items) {
      dom = tjson.items[i];
      system.item.ajax_result[module][dom[field_id]] = dom;
      if(typeof tjson.fields != 'undefined' && tjson.fields != null)
        system.item.ajax_result[module][dom[field_id]]['fields'] = tjson.fields;

    }
  }, 'json');
  $.ajaxSetup({async: true});
  itemIds = (valu || '').split(',');
  container_t = $('input.result-preview', row);
  container_t.children().each(function () {
    $(this).remove();
  })
  j = 0;
  for(i in itemIds) {
    if(typeof system.item.ajax_result[module] != 'undefined' && typeof system.item.ajax_result[module][itemIds[i]] != "undefined") {
      out = system.item.getDomainElement(itemIds[i], module)
      out.appendTo(container_t.get(0));
      j++;
    }
  }
}

/**
  * getDomainElement(): creates container for type-to-search
  *
  * @param int item_id: the id of the item
  * @param String module: the module name
  *
  * @returns Node: container for results
 */
system.item.getDomainElement = function (item_id, module) {
  item =system.item.ajax_result[module][item_id];
  field_id = 'item_id';
  field_title = 'title';
  if(typeof item.fields != 'undefined') {
    if(typeof item.fields.field_id != 'undefined') { field_id = item.fields.field_id; }
    if(typeof item.fields.field_title != 'undefined') { field_title = item.fields.field_title; }
  }
  nam = $('<span class="preview-name"></span>');
  nam.attr('innerHTML', system.item.ajax_result[module][item_id][field_title]);
  remove = $('<a class="preview-remove"></a>');
  remove.html('x');
  container = $('<div class="preview-container"></div>');
  nam.appendTo(container);
  remove.appendTo(container);
  container.get(0).item_id = item_id;

  return container;
}

/**
  * write_searches(): write the results we have got from the system
  *
  * @param Node parent_object: the object to write to
  * @param Array tjson: the json object got from system
 */
system.item.write_searches = function (parent_object, tjson) {
  if($('div.type-search-result', $(parent_object).parents('TR')).length == 0) {
    $('<div class="type-search-result"></div>').insertAfter($(parent_object));
  }
  cont = $('div.type-search-result', $(parent_object).parents('TR'));
  cont.children().each(function () {
    $(this).remove();
  })
  field_id = 'item_id';
  field_title = 'title';
  if(typeof tjson.fields != 'undefined') {
    if(typeof tjson.fields.field_id != 'undefined') { field_id = tjson.fields.field_id; }
    if(typeof tjson.fields.field_title != 'undefined') { field_title = tjson.fields.field_title; }
  }
  if(typeof tjson.items != "undefined")
    for(write_searches_i in tjson.items) {
      if(typeof write_searches_i != 'number' && parseInt(write_searches_i) != write_searches_i ) {
        return;
      }
      it = new system.item('item_'+tjson.items[write_searches_i][field_id], tjson.items[write_searches_i][field_id], 'checkbox');
      it.setVar('class', 'check-changed');
      if($.inArray(tjson.items[write_searches_i][field_id], $('input.type-result', $(parent_object).parents('TR')).val().split(',')) != -1) {
        it.setVar('checked', 'checked');
      }
      fival = it.getHtml();
      $('<div class="type-search-result-item">'+fival+tjson.items[write_searches_i][field_title]+'</div>').appendTo(cont);
    }
}

/** some extensions for jquery **/
$.extend($.fn, {
  getCursorsWordPosition: function () {
    if (document.selection) { // IE support
      $(this).focus();
      sel = document.selection.createRange();
      sel_length = document.selection.createRange().text.length;
      sel.moveStart('character', -el.value.length);
      pos = sel.text.length - sel_length;
    } else if ($(this).attr('selectionStart') || $(this).attr('selectionStart') == '0') // Firefox support
      pos = $(this).attr('selectionStart');
    pos_space = $(this).val().substring(0, pos).lastIndexOf(' ');
    word_start = 0;
    if(pos_space != -1)
      word_start = pos_space + 1;
    pos_bracket = $(this).val().substring(0, pos).lastIndexOf('{');
    if(word_start <= pos_bracket) {
      if(pos_bracket != -1)
        word_start = pos_bracket + 1;
      else if(pos_bracket == -1)
        word_start = -1;
    }
    word_end = 0;
    pos_space = $(this).val().substring(pos-1).indexOf(' ');
    if(pos_space != -1)
      word_end = pos_space;
    pos_bracket = $(this).val().substring(pos-1).indexOf('}');
    if(word_end > pos_bracket || word_end == 0) {
      if(pos_bracket != -1)
        word_end = parseInt(pos_bracket) - 1;
      else if (pos_bracket == -1)
        word_end = -1;
    }
    word_end = pos+(word_end != -1 ? word_end : $(this).val().length);
    return {start: word_start, end: word_end}
  },
  /**
    * displayWhisperer(): display the popup whisperer Node
    *
    * @param String word: the word to display results form_item
    * @param String position: the position of work that cursor lies on
    * @param Array tjson: data got from the system
   */
  displayWhisperer: function (word, position, tjson) {
    container = $('div.whisperer-result', $(this).parent());
    if(container.length == 0) {
      $('div.whisperer-result:not(.keep-shown)').fadeOut('show', function () { $(this).remove(); });
      container = $('<div class="whisperer-result"></div>').appendTo($(this).parent()).data('output_format', unescape(tjson.output_format));
      pos = $(this).offset();
      pos.top += $(this).height()+$(this).css('paddingTop')+$(this).css('paddingBottom');
      container.css('minWidth', $(this).outerWidth()-parseInt(container.css('paddingLeft'))-parseInt(container.css('paddingRight')));
      container.css(pos);
    } else {
      container.children().remove();
    }
    $(this).blur(function () {
      $('div.whisperer-result:not(.keep-shown)', $(this).parent()).fadeOut('show', function () { $(this).remove(); });
    });
    $('<div class="result-title">'+system.translation.getString('Results')+'</div>').appendTo(container);
    container.data('start', position.start).data('end', position.end);
    shown = 0;
    for(i=0;i<tjson.length;i++) {
      if(tjson[i].indexOf(word) != -1) {
        $('<div class="result-item clickable">'+tjson[i]+'</div>').appendTo(container).click(function () {
          st = $(this).parent().data('start');
          en = $(this).parent().data('end');
          v = $(this).parent().prev().prev().val();
          start = v.substr(0, st);
          center = $.fn.sprintf($(this).parent().data('output_format'), $(this).html());
          end = v.substr(en);
          if(start.substr(start.length - 1) == '{') {
            start = start.substr(0, start.length - 1);
          }
          if(end.substr(0, 1) == '}') {
            end = end.substr(1);
          }
          $(this).parent().prev().prev().val(start+center+end);
          $(this).parent().prev().prev().focus();
          $(this).parent().remove();
        });
        if(shown > 10)
          break;
        shown++;
      }
    }
    if(shown == 0) {
      $('<div class="result-empty">'+system.translation.getString('Sorry, no results')+'</div>').appendTo(container);
    }
  }
});

$(document).bind('documentChanged', function () {
  $('input.input-date').datepicker({changeMonth: true, changeYear: true});
  $('input.type-result').each(function () {
    val = $(this).val();
    if($(this).parents('TR').find('input.result-preview').length == 0) {
      $('<div class="result-preview"></div>').insertBefore($(this).parent().children()[0]);
    }
    system.item.loadResultPreview($(this).parents('TR'), $(this).attr('ajax_module'), $(this).attr('ajax_module'));
  });
  /** keyup event for type-to-search form item **/
  $('input.type-whisperer').die('keyup');
  $('input.type-whisperer').live('keyup', function () {
    pos = $(this).getCursorsWordPosition();
    word = $(this).val().substring(pos.start, pos.end);
    tjson = eval($(this).next().val().replace(/\n/g, ''));
    tjson.output_format = $(this).next().attr('title');
    $(this).displayWhisperer(word, pos, tjson);
  });
  /** register form item change function **/
  system.item.formChange(function  () {
    $('input.type-search').unbind('keyup');
    $('input.type-search').keyup(function () {
      if($(this).parents('TR').find('input.type-result').hasClass('allow-plain-search')) {
        $(this).parents('TR').find('input.type-result').val($(this).val());
      }
      if(typeof system.item.last_type_search[$(aThis).attr('module')] != 'undefined' && system.item.last_type_search[$(aThis).attr('module')] != null)
        system.item.last_type_search[$(aThis).attr('module')].abort();
      if($(this).val().length < 2)
        return;
      if(typeof system.item.type_searches[$(aThis).attr('module')] != 'undefined' && typeof system.item.type_searches[$(aThis).attr('module')][$(aThis).val()] != 'undefined') {
        system.item.write_searches(this, system.item.type_searches[$(aThis).attr('module')][$(aThis).val()]);
      }
      var aThis = this;
      url = '/'+$(this).attr('ajax_module')+'/'+$(this).attr('ajax_function');
      if(/^\/([A-Za-z]+)\/([A-Za-z]+)$/.test(url)) {
        if(typeof system.item.last_type_search[$(aThis).attr('module')] == 'undefined') system.item.last_type_search[$(aThis).attr('module')] = [];
        system.item.last_type_search[$(aThis).attr('module')] = $.post(system.getLink(url+'?type=ajax'), {search_string: $(this).val()}, function (tjson) {
          system.jsonMessage(tjson);
          if(typeof system.item.type_searches[$(aThis).attr('module')] == 'undefined') system.item.type_searches[$(aThis).attr('module')] = [];
          system.item.type_searches[$(aThis).attr('module')][$(aThis).val()] = tjson;
          system.item.write_searches(aThis, tjson);
        }, 'json');
      }
    });
    /** inputs help text replace clear on focus **/
    $('input.type-search').focus(function () {
      if($(this).val() == $(this).attr('info_value')) {
        $(this).val('');
      }
    });
    /** inputs help text replace fill on blur **/
    $('input.type-search').live('blur', function () {
      if($(this).val() == '') {
        $(this).val($(this).attr('info_value'));
      }
    });
  })();
  /** form item image remove function **/
  $('a.preview-remove').die('click')
  $('a.preview-remove').live('click', function () {
    dom_id = $(this).parents('.preview-container').get(0).item_id;
    v = $('input.type-result', $(this).parents('TR')).val();
    v = (','+v+',').replace(','+dom_id+',', ',');
    v = v.replace(/,+/, ',');
    if(out = /([0-9]+)\,+$/.exec(v)) {
      v = out[1];
    }
    if(out = /^\,+([0-9]+)/.exec(v)) {
      v = out[1];
    }
    $('input.type-result', $(this).parents('TR')).val(v);
    data = $('input.type-search', $(this).parents('TR'));
    system.item.loadResultPreview($(this).parents('TR'), data.attr('ajax_module'), data.attr('ajax_function'));
  });

  $('input.check-changed').die('click');
  $('input.check-changed').live('click', function () {
    val_obj = $(this).parents('TR').find('input.type-result');
    values = val_obj.val().split(',');
    v = val_obj.val();
    is_onlyone = val_obj.hasClass('allow-one');
    if(is_onlyone) {
      aThis = this;
      $(this).parents('TR').find('input.check-changed').each(function () {
        if($(this).get(0) != $(aThis).get(0)){
          $(this).attr('checked', '');
        }
      })
      v = $(this).val();
    } else {
      if($(this).attr('checked') == false) {
        v = (','+v+',').replace(','+$(this).val()+',', ',');
      } else if ((','+v+',').indexOf(','+$(this).val()+',') == -1) {
        v = v+','+$(this).val();
      }
    }
    v = v.replace(/,+/g, ',');
    if(out = /([0-9]+)([^,])\,+$/.exec(v)) {
      v = out[1]+out[2];
    }
    if(out = /^\,+([^,])(.*)/.exec(v)) {
      v = out[1]+out[2];
    }
    val_obj.val(v);
    data = $('input.type-search', $(this).parents('TR'));
    system.item.loadResultPreview($(this).parents('TR'), data.attr('ajax_module'), data.attr('ajax_function'));
  });
  /** the item type list change function (load description for diferent item and clear the previous) **/
  if($('select.item-form-item').die('change').length > 0) {
    system.loadJavascript('/js/translation.js');
  }
  $('select.item-form-item').live('change', function(){
    if(typeof this.name != "undefined") {
      nm = this.name.substring(0, this.name.lastIndexOf('-'));
      if(nm.length > 0) {
        system.item.old_name_prefix = nm;
        system.item.removeMyItemsFromForm(nm);
      }
      nm = nm.substring(0, nm.lastIndexOf('-')+1)+this.value;
      system.item.name_prefix = nm;
    }
    system.item.lastItemChanged = this;
    reg = /(.*)-([0-9]+)-(.*)$/;
    if(out = reg.exec($(this).attr('name')))
      $(this).attr('name', out[1]+'-'+this.value+'-'+out[3]);
    if(out = reg.exec($(this).attr('id')))
      $(this).attr('id', out[1]+'-'+this.value+'-'+out[3]);
    if(out = reg.exec($(this).parent().parent().get(0).className))
      $(this).parent().parent().get(0).className = out[1]+'-'+this.value+'-'+out[3];
    $.get(system.getLink('/Item/getItemData?type=ajax&item_id='+this.value+'&prefix='+system.item.name_prefix), {}, function (tjson) {
      system.jsonMessage(tjson);
      system.item.modifyForm(tjson, tjson.prefix);
    }, 'json');
  });
  /** check if the user input is a number **/
  $('input.input-check-number').die('keyup');
  $('input.input-check-number').live('keyup', function () {
    if(!/^-?[0-9]+$/.test($(this).val())) {
      if(!$(this).hasClass('check-fail'))
        $(this).addClass('check-fail');
    } else if ($(this).hasClass('check-fail')) {
      $(this).removeClass('check-fail');
    }
  });
  /** check if the user input id a price **/
  $('input.input-check-price').die('keyup');
  $('input.input-check-price').live('keyup', function () {
    if(!/^[0-9]+([.,]?)([0-9]*)$/.test($(this).val().replace(/ /g, ''))) {
      if(!$(this).hasClass('check-fail'))
        $(this).addClass('check-fail');
    } else if ($(this).hasClass('check-fail')) {
      $(this).removeClass('check-fail');
    }
  });
  /** show up the database connection form **/
  $('input.add-database-connection-helper').unbind('focus');
  $('input.add-database-connection-helper').focus( function () {
    data = {};
    if(preg = /([^:]+):\/\/([^:\/]+):?([^:@]+)@([^@\/]+)\/([^\/]+)/.exec($(this).val())) {
      data.driver = preg[1];
      data.username = preg[2];
      data.password = preg[3];
      data.server   = preg[4];
      data.database = preg[5];
    }
    $('#database_connection_container').remove();
    container = $('<table class="database-connection-container" />');
    container.append($('<tr><th>Database driver</th><td><select name="database_driver" class="database-connection-driver"><option value="mysql"'+(typeof data.driver != 'undefined' && data.driver == 'mysql' ? ' selected="selected"' : '')+'>mysql</option><option value="mysqli"'+(typeof data.driver != 'undefined' && data.driver == 'mysqli' ? ' selected="selected"' : '')+'>mysqli</option></select></td></tr>'));
    container.append($('<tr><th>Username</th><td><input type="text" name="username" class="database-connection-username"'+(typeof data.username != 'undefined' && data.username.length > 0 ? ' value="'+data.username+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Password</th><td><input type="password" name="password" class="database-connection-password"'+(typeof data.password != 'undefined' && data.password.length > 0 ? ' value="'+data.password+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Database server</th><td><input type="text" name="server" class="database-connection-server"'+(typeof data.server != 'undefined' && data.server.length > 0 ? ' value="'+data.server+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Database name</th><td><input type="text" name="server" class="database-connection-database"'+(typeof data.database != 'undefined' && data.database.length > 0 ? ' value="'+data.database+'"' : '')+' /></td></tr>'));
    container.append($('<tr><td colspan="2" class="database-connection-result"></td></tr>'));
    container.append($('<tr><td colspan="2" class="database-connection-test"><input type="button" value="'+'Test connection'+'"></td></tr>'));
    aThis = this;
    $(container).appendTo($('<div id="database_connection_container"></div>').appendTo('BODY').hide());
    out = getDatabaseConnectionUrl(container);
    $('td.database-connection-result', container).html(out);
    $('<a href="#database_connection_container"></a>').fancybox({hideOnContentClick: false, callbackOnClose: function () {
      $(aThis).val(getDatabaseConnectionUrl());
    }}).click();
    $('#database_connection_container').remove();
    $('td.database-connection-test input').click( function () {
      $.post(system.getLink('/FormItem/testDatabaseConnection'), {link: getDatabaseConnectionUrl(), type: 'ajax'}, function (tjson) {
        system.jsonMessage(tjson);
        $('td.database-connection-test input').val(tjson.connection_succeded == true ? 'Connection succeded' : 'Connection failed');
      }, 'json');
    });
    $('select.database-connection-driver, input.database-connection-username, input.database-connection-password, input.database-connection-server, input.database-connection-database').live('keyup', function () {
      out = getDatabaseConnectionUrl($(this).parents('table:eq(0)'));
      $('td.database-connection-result').html(out);
      $('td.database-connection-test input').val('Test connection');
    });
  });
  /** show up the access connection helper **/
  $('input.add-connection-helper').unbind('focus');
  $('input.add-connection-helper').focus( function () {
    data = {};
    if(preg = /([^:]+):\/\/([^:\/]+):?([^:@]+)@([^@\/]+):([^\/]+)/.exec($(this).val())) {
      data.driver   = preg[1];
      data.username = preg[2];
      data.password = preg[3];
      data.server   = preg[4];
      data.path     = preg[5];
    }
    $('#connection_container').remove();
    container = $('<table class="connection-container" />');
    container.append($('<tr><th>Database driver</th><td><select name="driver" class="connection-driver"><option value="ftp"'+(typeof data.driver != 'undefined' && data.driver == 'ftp' ? ' selected="selected"' : '')+'>ftp</option></select></td></tr>'));
    container.append($('<tr><th>Username</th><td><input type="text" name="username" class="connection-username"'+(typeof data.username != 'undefined' && data.username.length > 0 ? ' value="'+data.username+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Password</th><td><input type="password" name="password" class="connection-password"'+(typeof data.password != 'undefined' && data.password.length > 0 ? ' value="'+data.password+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Server</th><td><input type="text" name="server" class="connection-server"'+(typeof data.server != 'undefined' && data.server.length > 0 ? ' value="'+data.server+'"' : '')+' /></td></tr>'));
    container.append($('<tr><th>Path</th><td><input type="text" name="server" class="connection-path"'+(typeof data.path != 'undefined' && data.path.length > 0 ? ' value="'+data.path+'"' : '')+' /></td></tr>'));
    container.append($('<tr><td colspan="2" class="connection-result"></td></tr>'));
    container.append($('<tr><td colspan="2" class="connection-test"><input type="button" value="'+'Test connection'+'"></td></tr>'));
    aThis = this;
    $(container).appendTo($('<div id="database_connection_container"></div>').appendTo('BODY').hide());
    out = getConnectionUrl(container);
    $('td.connection-result', container).html(out);
    $('<a href="#database_connection_container"></a>').fancybox({hideOnContentClick: false, callbackOnClose: function () {
      $(aThis).val(getConnectionUrl());
    }}).click();
    $('#connection_container').remove();
    $('select.connection-driver, input.connection-username, input.connection-password, input.connection-server, input.connection-path').live('keyup', function () {
      out = getConnectionUrl($(this).parents('table:eq(0)'));
      $('td.connection-result').html(out);
      $('td.connection-test input').val('Test connection');
    });
  });
  (system.item.formChange(function() {
    $('.allow-multiple-values:not(.multiple-allready-processed)').each(function () {
      if($(this).attr('tagName').toLowerCase() == 'input') {
        oldtype = $(this).attr('type');
        $(this).hide();
        val = $(this).val();
        separator_int = -1;
        if(preg = /values-separated-by-([0-9]+)/.exec($(this).attr('className'))) {
          vals = val.split(String.fromCharCode(preg[1]));
          separator_int = parseInt(preg[1]);
        }
        class_type = '';
        if(preg = / input-(^[ -]+) /.exec($(this).attr('className'))) {
          class_type = preg[1];
        }
        fch_i=-1;
        last_obj = $(this);
        has_empty = false;
        while (fch_i <= vals.length) {
          v = vals.length > fch_i && typeof vals[fch_i] != "undefined" ? vals[fch_i] : "";
          if(v.length == 0) {
            if(has_empty) {
              fch_i++;
              continue;
            }
            has_empty = true;
          }
          obj = $('<input type="'+oldtype+'" />');
          obj.change(function () {
            vals = [];
            empty_exists = false;
            $(this).parent().children('input.generated-multiple').each(function () {
              if($(this).val().length > 0)
                vals[vals.length] = $(this).val();
              else
                empty_exists = true;
            });
            if(!empty_exists) {
              obj = $('<input type="'+oldtype+'" />');
              obj.addClass('generated-multiple');
              obj.data('separator_int', $(this).data('separator_int'));
              obj.val('');
              obj.insertAfter($(this).parent().children('input.generated-multiple:last'));
              obj.change(arguments.callee);
            }
            vs = vals.join(String.fromCharCode($(this).data('separator_int')));
            $(this).siblings('input.multiple-allready-processed:eq(0)').val(vs);
          });
          obj.data('separator_int', separator_int);
          obj.val(v);
          obj.insertAfter(last_obj);
            obj.addClass('generated-multiple');
          obj.addClass('input-'+class_type);
          last_obj = obj;
          fch_i++;
        }
        $(this).addClass('multiple-allready-processed');
      }
    })
  }))()
  $('.form-item-getspecial-split-item').each(function () {
    $(this).find('.item-getitemnomodifyformitem').change(function () {
      $.get(system.getLink('/Item/getItemFields/'+$(this).val()), {type: 'ajax'}, function (tjson) {
        drop = $('.form-item-getspecial-split-item').find('select.item-getitemitemsformitem').get(0);
        drop.options.length=0;
        for(i in tjson) {
          if(typeof i == 'number' || typeof i == 'string' && (i === '0' || parseInt(i) > 0)) {
            drop.options[drop.options.length] = new Option(tjson[i].int_name, tjson[i].int_name);
          }
        }
      }, 'json');
    });
  })
});
})(jQuery);
