/* Constants */
var req_timeout = 30;
//var redirect_after_logout = site_root_url + 'account/login.php';
var redirect_after_logout = site_root_url;
var operation_actions_url = site_root_url + 'myfinances/actions.php';
var settings_actions_url = site_root_url + 'settings/actions.php';
var get_suppliers_by_name_url = site_root_url + 'myfinances/getsuppliersbyname.php';

var defaultSearchText = _('Rechercher');
//var button_class = web_site == 1 ? 'blackbutton' : 'blackbutton3';
var button_class ='button';

var select_other_id = 1000000000;

var is_ie = !!(window.attachEvent && !window.opera);
var className = (!is_ie) ? 'class' : 'className';
var isIE6 = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
var isIE = $.browser.msie;

var fcf_prefix = "";
/* End Constants */

/* Internationalization */
function _(s) {
  if (typeof(i18n)!='undefined' && i18n[s]) {
    return i18n[s];
  }
  return s;
}
/* End Internationalization */


/* Window / body events */
function get_key_code(e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  return keycode;
}

function disableEnterKey(e) {
  return (get_key_code(e) != 13);
}

function disableEventPropagation(event) {
  if (event.stopPropagation) {
    // this code is for Mozilla and Opera
    event.stopPropagation();
  }
  else if (window.event) {
    // this code is for IE
    window.event.cancelBubble = true;
  }
}
/* End Window / body events */

/* Ajax requests */
function showLoader () {
	$('#load').show();
}

function hideLoader () {
	$('#load').hide();
}

function validateForm(formId, f, options) {
  if (!options) {
    options = new Array();
  }
  var theform = $('#' + formId);
  
  if (options.displayErrorsInsideForm == undefined || options.displayErrorsInsideForm == true) {
    clearFormErrors(formId);
  }
  if (options.displayErrorMessage == undefined || options.displayErrorMessage == true) {
    if ($('#error_message').length > 0) {
      $('#error_message').remove();
    }
  }
  
  $('#' + formId + ' li.buttons button').each(function (index, domElt) {
    $(this).attr("disabled", true);
  });

  $.ajax({
        url: theform.attr("action"),
        type: theform.attr("method"),
        data: theform.serialize(),
        success: function(result) {
            var errors = result.errors;
            if (errors && getArrayKeys(errors).length > 0) {
            
              if (options.displayErrorMessage == undefined || options.displayErrorMessage == true) {
               theform.prepend('<p id="error_message" class="errormsg">' + _('The form contains errors.') + '</p>');
              }
              
              var msg = '';
              $.each(errors, function(key, error) { 
                success = false;
                if (error == _('Connection timeout')) {
                  window.location=redirect_after_logout;
                }
                if (options.displayErrorsInsideForm == undefined || options.displayErrorsInsideForm == true) {
                  $('#' + key).parent().append('<span class="error">' + error + '</span>');
                } else {
                  msg += '<span class="error">' + error + "</span><br/><br/>";               
                }
              });
              
              if (options.displayErrorsInsideForm != undefined && options.displayErrorsInsideForm == false) {
                showAlert(window.event, {'title': options.errorTitle || _('Error'), 'body': msg });
              }
                      
              $('#' + formId + ' li.buttons button').each(function (index, domElt) {
                $(this).removeAttr("disabled");
              });
            } else {
              if (!f) {
                theform[0].submit();
              } else {
                f(result);        
              }
            }
        },
        error: function(request, error) {
        },
        dataType: "json"
    });
}

function validateFormWithErrorPopup(formId, errorTitle) {
  return validateForm(formId, undefined, {
    displayErrorMessage: false,
    displayErrorsInsideForm: false,
    errorTitle: errorTitle
  });
}

function clearFormErrors(formId) {
  $('#' + formId + ' span.error').each(function(index, domElt) { 
		$(this).remove();
	});
}

function appendFormError(key, error) {
  $('#' + key).parent().append('<span class="error">' + error + '</span>');
}

function validateResponse(json) {
  var success = true;
  if (json && json.errors) {
    var errors = json.errors;
    $.each(errors, function(key, error) { 
      success = false;
      if (error == _('Connection timeout')) {
        window.location=redirect_after_logout;
      }
      $('#' + key).parent().append('<span class="error">' + error + '</span>');
    });
  }
  return success;
}

function processErrors(json) {
  var connected = true;
  var success = true;
  if (json && json.errors) {
    var errors = json.errors;
    var msg = '';
    $.each(errors, function(key, error) { 
      success = false;
      if (error == _('Connection timeout')) {
        window.location=redirect_after_logout;
        connected = false;
      }
      msg += error + "<br/>";
    });
    
    if (!success && connected) {
      showAlert(window.event, {'title': _('Error'), 'body': '<p class="error">' + msg + '</p>'});        
    }
  }
  return success;
}
/* End Ajax requests */

/* Dialog / Alert */
function getOrCreatePopupBackground() {
  var popupBackground;
  if (!$('#popupBackground').length) {
    var arrayPageSize = getTotalPageSize();
    var width = arrayPageSize[0] + 'px';
    var height = arrayPageSize[1] + 'px';
    popupBackground = $('<div id="popupBackground" style="display:none;width:' + width + ';height:' + height + ';"></div>');
    $(document.body).append(popupBackground);
  } else {
    popupBackground = $('#popupBackground');
  }
  return popupBackground;
}

function showDialog(e, options) {
  if (!e) e = window.event||window.Event;

  var popupBackground = getOrCreatePopupBackground();
  
  var dialog;
  if (!$('#popup').length) {
    dialog = $('<div id="popup" style="display:none;" class="popup"></div>');
    $(document.body).append(dialog);
    
    $(document).keyup(function(e) {
      if (e.keyCode == 27)
        hideDialog();
    });
    dialog.draggable({zIndex:999999});
  } else {
    dialog = $('#popup');
  }
  
  var okLabel = options['okLabel'] ? options['okLabel'] : _('Ok');
  var cancelLabel = options['cancelLabel'] ? options['cancelLabel'] : _('Cancel');

  var okButtonClass = (options['buttonClass'] ? options['buttonClass'] + " " : button_class);
  var cancelButtonClass = (options['buttonClass'] ? options['buttonClass'] + " " : "");
  
  var buttonsStyle = (options['buttonsStyle'] == 'formButtons' ? "style='padding-left: " + options['buttonsPadding'] + "px;'" : "style='text-align:center;'");

  var content = "<div class='popupInner'>"
    + "<div id='popupTop' class='popupTop'>"
    + "<span id='popupTitle'>" + (options['title'] ? options['title'] : "") + "</span>"
    + "<a id='dialog_close_icon' href='#'><img class='pngfix' src='/images/icons/supprimer-blanc2.png' alt='" + _('Close')+ "' title='" + _('Close') + "'/></a>"
    + "</div>"
    + "<div class='popupContent'>"
    + "<div class='popupBody'>" + (options['body'] ? options['body'] : "") + "</div>"
    + "<div class='popupButtons' id='dialog_buttons' " + buttonsStyle + ">"
    + "<button id='dialog_btn_ok' name='dialog_btn_ok' type='submit' class='" + okButtonClass + "'><span>" + okLabel + "</span></button>"
    + "<a id='dialog_btn_cancel' href='#' class='cancel'>" + cancelLabel + "</a>"
    + "</div>"
    + "</div>"
    //+ "<div id='popupBottom' class='popupBottom'>&nbsp;</div>"
    + "</div>";

  dialog.html(content);

  var width = options['width'] ? options['width'] : 360;
  dialog.width(width + 'px');
  $('#popupTop').width((width - 15) + 'px');
  $('#popupTitle').width((width - 35) + 'px');
  //$('#popupBottom').css('backgroundPosition', (width - 292) + 'px' + ' 100%');
  
  var dialog_btn_ok = $('#dialog_btn_ok');
  dialog_btn_ok.unbind('click').click(function() {
    if (options['ok']) {
      res = options['ok']();
    } else {
      res = false;
    }
    if (!options['OkDoNotClose']) {
      hideDialog();
      return false;
    }
    return res;
  });
  
  $('#dialog_btn_cancel').unbind('click').click(function() {
    hideDialog();
    return false;
  });
  
  $('#dialog_close_icon').unbind('click').click(function() {
    hideDialog();
    return false;
  });
  
  popupBackground.show();
  dialog.show();
  dialog.css('position', 'absolute');

  if (options['top'] && options['left']) {
    dialog.css({left: options['left'] + 'px', top: options['top'] + 'px'});
  } else if (options['position'] && options['position'] == 'mouse') {
    dialog.css({left: mousePosX(e) - 52 + 'px', top: mousePosY(e) - 16 + 'px'});
  } else {
    centerPopup(dialog[0]);
  }

  if (isIE6) {
    popupBackground.bgiframe();
    dialog.bgiframe();
  }

  addPopupTooltips();
  dialog_btn_ok.focus();
  if (options['postDisplay']) {
      options['postDisplay']();
  }
  return false;
}

function showPopup(e, options) {
  if (!e) e = window.event||window.Event;
  var id = options.id;
  if ($('#' + id).length) {
    $('#' + id).remove();
    //return false;
  }
  var dialog = $('<div id="' + id + '" style="display:none;" class="popup"></div>');
  $(document.body).append(dialog);
  $(document).keyup(function(e) {
    if (e.keyCode == 27)
      closePopup(id);
  });
  dialog.draggable({zIndex:999999});
  
  var okLabel = options['okLabel'] ? options['okLabel'] : _('Ok');
  var okButtonClass = (options['buttonClass'] ? options['buttonClass'] + " " : button_class);
  var buttonsStyle = (options['buttonsStyle'] == 'formButtons' ? "style='padding-left: " + options['buttonsPadding'] + "px;'" : "style='text-align:center;'");
  
  var content = "<div class='popupInner'>"
    + "<div id='popupTop_" + id + "' class='popupTop'>"
    + "<span id='popupTitle_" + id + "'>" + (options['title'] ? options['title'] : "") + "</span>"
    + "<a id='dialog_close_icon_" + id + "' href='#'><img class='pngfix' src='/images/icons/supprimer-blanc2.png' alt='" + _('Close')+ "' title='" + _('Close') + "'/></a>"
    + "</div>"
    + "<div class='popupContent' style='padding-top:10px;'>"
    + "<div class='popupBody'>" + (options['body'] ? options['body'] : "") + "</div>"
    + (!options.noButton ? "<div class='popupButtons' style='text-align:center;'>"
    + "<button id='dialog_btn_ok_" + id + "' type='submit' class='" + okButtonClass + "'><span>" + okLabel + "</span></button>"
    + "</div>" : "")
    + "</div>"
    + "</div>";
  dialog.html(content);
    
  var width = options['width'] ? options['width'] : 360;
  dialog.width(width + 'px');
  $('#popupTop_' + id).width((width - 15) + 'px');
  $('#popupTitle_' + id).width((width - 35) + 'px');
  //$('#popupBottom_' + id).css('backgroundPosition', (width - 292) + 'px' + ' 100%');
  
  var dialog_btn_ok = $('#dialog_btn_ok_' + id);
  dialog_btn_ok.click(function() {
    closePopup(id);
    return false;
  });
  $('#dialog_close_icon_' + id).click(function() {
    closePopup(id);
    return false;
  });
  
  dialog.show();
  dialog.css('position', 'absolute');

  if (options['top'] && options['left']) {
    dialog.css({left: options['left'] + 'px', top: options['top'] + 'px'});
  } else if (options['position'] && options['position'] == 'mouse') {
    dialog.css({left: mousePosX(e) - 52 + 'px', top: mousePosY(e) - 16 + 'px'});
  } else {
    centerPopup(dialog[0]);
  }

  if (isIE6) {
    dialog.bgiframe();
  }

  dialog_btn_ok.focus();
  if (options['postDisplay']) {
      options['postDisplay']();
  }
  return false;
}

function closePopup(id) {
  $('#' + id).fadeOut(200, function() {
    $('#' + id).remove();
  });
}

function hideDialog() {
  $('#popup').fadeOut(200, function() {
    if (isIE) {
      $('#popupBackground').hide();
    } else {
      $('#popupBackground').fadeOut(100);
    }
  });
}

function addPopupTooltips() {
	$('#popup input, #popup select').each(function(index, domElt) { 
		addPopupHint($(this));
	});
}

function addPopupHint(inputField) {
  inputField.parent().find('span').each(function(index, domElt) {
    var span = $(this);
    if (span.attr('class').indexOf("help")>-1) {
      inputField.focus(function() {
        $(this).parent().find('span').each(function(index, domElt) {
          var span2 = $(this);
          if (span2.attr('class').indexOf("help")>-1) {
            span2.addClass('highlighted');
          }
        });
      });
      inputField.blur(function() {
        $(this).parent().find('span').each(function(index, domElt) {
          var span2 = $(this);
          if (span2.attr('class').indexOf("help")>-1) {
            span2.removeClass('highlighted');
          }
        });
      });
    }
  });
}

function showAlert(e, options) {
  if (!e) e = window.event||window.Event;

  var popupBackground = getOrCreatePopupBackground();

  var dialog;
  if (!$('#popup').length) {
    dialog = $('<div id="popup" style="display:none;" class="popup"></div>');
    $(document.body).append(dialog);
    
    $(document).keyup(function(e) {
      if (e.keyCode == 27)
        hideDialog();
    });
    //new Draggable('dialog', { zindex:4001 });
    dialog.draggable({zIndex:999999});
  } else {
    dialog = $('#popup');
  }

  var okLabel = options['okLabel'] ? options['okLabel'] : _('Ok');
  var okButtonClass = (options['buttonClass'] ? options['buttonClass'] + " " : button_class);

  var content = "<div class='popupInner'>"
    + "<div id='popupTop' class='popupTop'>"
    + "<span id='popupTitle'>" + (options['title'] ? options['title'] : "") + "</span>"
    + "<a id='dialog_close_icon' href='#'><img class='pngfix' src='/images/icons/supprimer-blanc2.png' alt='" + _('Close')+ "' title='" + _('Close') + "'/></a>"
    + "</div>"
    + "<div class='popupContent'>"
    + "<div class='popupBody'>" + (options['body'] ? options['body'] : "") + "</div>"
    + "<div class='popupButtons' id='dialog_buttons' style='text-align:center;'>"
    + "<button id='dialog_btn_ok' name='dialog_btn_ok' type='submit' class='" + okButtonClass + "'><span>" + okLabel + "</span></button>"
    + "</div>"
    + "</div>"
    + "</div>";

  dialog.html(content);

  var width = options['width'] ? options['width'] : 360;
  dialog.width(width + 'px');
  $('#popupTop').width((width - 15) + 'px');
  $('#popupTitle').width((width - 35) + 'px');
  //$('#popupBottom').css('backgroundPosition', (width - 292) + 'px' + ' 100%');
  
  var dialog_btn_ok = $('#dialog_btn_ok');
  dialog_btn_ok.unbind('click').click(function() {
    hideDialog();
    return false;
  });
  
  $('#dialog_close_icon').unbind('click').click(function() {
    hideDialog();
    return false;
  });
  
  popupBackground.show();
  dialog.show();
  dialog.css('position', 'absolute');

  if (options['top'] && options['left']) {
    dialog.css({left: options['left'] + 'px', top: options['top'] + 'px'});
  } else if (options['position'] && options['position'] == 'mouse') {
    dialog.css({left: mousePosX(e) - 52 + 'px', top: mousePosY(e) - 16 + 'px'});
  } else {
    centerPopup(dialog[0]);
  }
  if (isIE6) {
    popupBackground.bgiframe();
    dialog.bgiframe();
  }

  dialog_btn_ok.focus();
  if (options['postDisplay']) {
      options['postDisplay']();
  }
  return false;
}

function getScrollTop() {
  return (window.pageYOffset)?window.pageYOffset:(document.documentElement && document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop;
}

function centerPopup(element) {
    //var arrayPageScroll = document.viewport.getScrollOffsets();
    //var x = arrayPageScroll[1] + document.viewport.getHeight()/2 - element.offsetHeight/2;
    //var y = arrayPageScroll[0] + document.viewport.getWidth()/2 - element.offsetWidth/2;
    var x = $(window).scrollTop() + $(window).height()/2 - element.offsetHeight/2;
    var y = $(window).scrollLeft() + $(window).width()/2 - element.offsetWidth/2;
    
    if (isIE6) {
      element.style.top = x;
      element.style.left = y;
    } else {
      element.style.top = x + 'px';
      element.style.left = y + 'px';
    }
}

function mousePosX(e) {
  if (!e) e = window.event||window.Event;
  return e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
}

function mousePosY(e) {
  if (!e) e = window.event||window.Event;
  return e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
}

function getTotalPageSize() {      
  var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

function openPopup(url, title, width, height, x, y) {
  mywindow = window.open(url,title,'width=' + width + ',height=' + height + ',scrollbars=yes,menubar=no,status=no,toolbar=no,location=no');
  if (mywindow)
    mywindow.moveTo(x,y);
}

jQuery.fn.extend({
   findPos : function() {
       obj = jQuery(this).get(0);
       var curleft = obj.offsetLeft || 0;
       var curtop = obj.offsetTop || 0;
       while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
       }
       return {x:curleft,y:curtop};
   }
});
/* End Dialog / Alert */

/* DOM utils */
function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

function discardElement(element) {
  var garbageBin = document.getElementById('IELeakGarbageBin');
  if (!garbageBin) {
    garbageBin = document.createElement('DIV');
    garbageBin.id = 'IELeakGarbageBin';
    garbageBin.style.display = 'none';
    document.body.appendChild(garbageBin);
  }
  // move the element to the garbage bin
  garbageBin.appendChild(element);
  garbageBin.innerHTML = '';
}

function fadeOutElement(elt, f) {
  elt.fadeOut(300, function() {
    discardElement(elt[0]);
    if (f) {
      f();
    }
  });
}

/* End DOM utils */

/* Array utils */
function sortKeys(h, sortBy) {
  var keys = getArrayKeys(h);
  var sortedKeys;
  if (sortBy == 'keys') {
    sortedKeys = keys.sort(function sortByNumericKeys(a, b){
      return a - b;
      });
  } else if (sortBy == 'values') {
    sortedKeys = keys.sort(function sortByValues(a, b){
      var A = h[a].toLowerCase();
      var B = h[b].toLowerCase();
      //if (h[b] == _('Other')) return -1;
      //if (h[a] == _('Other')) return 1;
      if (b == select_other_id) return -1;
      if (a == select_other_id) return 1;
      
      if (A < B) return -1;
      if (A > B) return 1;
      return 0;    
      });
  } else {
    sortedKeys = keys;
  }
  return sortedKeys;
}

if(!Array.indexOf){
	Array.prototype.indexOf = function(obj) {
		for (var i in this) {
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	};
}

Array.prototype.toUrl = function (name) 
{
  var url = '';
   for (var i = 0; i < this.length; i++) 
   {
      if (url != '')
        url += '&';
      url += name + '[]=' + this[i];
  }
  return url;
};

Array.prototype.removeValue = function (value) {
	var r = new Array();
	for (var i in this)
	{
		if(!(this[i]==value))
		{
			r[i] = this[i];
		}
	}
	return r;
};

Array.prototype.removeIndex = function (index) {
	var r = new Array();
	for (var i in this)
	{
		if(!(i==index))
		{
			r[i] = this[i];
		}
	}
	return r;
};

function getArrayKeys(myArray) {
  var keys = Array();
  $.each(myArray, function(key, value) {
    keys.push(key);
  });
  return keys;
};
/* End Array utils */


/* Fields */
function getSelectHtml(myList, listId, selectValue, className, emptyValue, listName, twoLevels, sortBy, noEmptyValue) {

  var html = [];
  var idx = 0;
  
  if (className == undefined) {
    className = 'select_medium';
  }
  
  if (emptyValue == undefined) {
    emptyValue = '--- ' + _('Select in the list') + ' ---';
  }
  if (listName == undefined) {
    listName = listId;
  }
  
  html[idx++] = '<select id="' + listId + '" name="' + listName + '" class="' + className + '">';
  if (!noEmptyValue)
    html[idx++] = '<option value="">' + emptyValue + '</option>';
  
  if (!twoLevels) {
    var sortedKeys = sortKeys(myList, sortBy);
  
    for (var i = 0; i < sortedKeys.length; i++) {
       if (sortedKeys[i] == selectValue) {
        html[idx++] = '<option value="' + sortedKeys[i] + '" selected>' + myList[sortedKeys[i]] + '</option>';
      } else {
        html[idx++] = '<option value="' + sortedKeys[i] + '">' + myList[sortedKeys[i]] + '</option>';
      }
    }
  
  } else {
  
    $.each(myList, function(groupKey, subList) {
      html[idx++] = '<optgroup label="' + myaddslashes(groupKey) + '" class="optgroup">';
      var sortedKeys = sortKeys(subList, sortBy);
  
      for (var i = 0; i < sortedKeys.length; i++) {
        if (sortedKeys[i] == selectValue) {
          html[idx++] = '<option value="' + sortedKeys[i] + '" selected>' + subList[sortedKeys[i]] + '</option>';
        } else {
          html[idx++] = '<option value="' + sortedKeys[i] + '">' + subList[sortedKeys[i]] + '</option>';
        }
      }
      
      html[idx++] = '</optgroup>';
    });

  }
  
  html[idx++] = '</select>';
  
  return html.join("");
}

function getYearList(id, name, defaultValue, className, emptyLabel, minYear, maxYear, reverseYears) {
  if (className == undefined) {
    className = 'select_medium';
  }
  if (emptyLabel == undefined) {
    emptyLabel = "--- " + _('Select in the list') + " ---";
  }
  var d = new Date();
  var curr_year = d.getFullYear();
  if (minYear == undefined) {
    minYear = curr_year - 120;
  }
  if (maxYear == undefined) {
    maxYear = curr_year;
  }
  if (reverseYears == undefined) {
    reverseYears = true;
  }
      
  var html = [];
  var idx = 0;
  
  html[idx++] = "<select id='" + id + "' name='" + name + "' class='" + className + "'><option value=''>" + emptyLabel + "</option><option value=''></option>";

  if (reverseYears) {
    for(var i = maxYear ; i >= minYear; i--)
    {
      if (i == defaultValue) {
        html[idx++] = "<option value='" + i + "' selected>" + i + "</option>";
      } else {
        html[idx++] = "<option value='" + i + "'>" + i + "</option>";
      }
    }
  } else {
    for(var i = minYear ; i <= maxYear; i++)
    {
      if (i == defaultValue) {
        html[idx++] = "<option value='" + i + "' selected>" + i + "</option>";
      } else {
        html[idx++] = "<option value='" + i + "'>" + i + "</option>";
      }
    }
  }

  html[idx++] = "</select>";
  
  return html.join("");
}

function getMonthList(id, name, defaultValue, className, emptyLabel) {
  var myList = {
  1 : _('January'),
  2 : _('February'),
  3 : _('March'),
  4 : _('April'),
  5 : _('May'),
  6 : _('June'),
  7 : _('July'),
  8 : _('August'),
  9 : _('September'),
  10 : _('October'),
  11 : _('November'),
  12 : _('December')
  };
  return getSelectHtml(myList, id, defaultValue, className, emptyLabel, name);
}

function getDayList(id, name, defaultValue, className, emptyLabel) {
  if (className == undefined) {
    className = 'select_medium';
  }
  if (emptyLabel == undefined) {
    emptyLabel = "--- " + _('Select in the list') + " ---";
  }
      
  var html = [];
  var idx = 0;
  
  html[idx++] = "<select id='" + id + "' name='" + name + "' class='" + className + "'><option value=''>" + emptyLabel + "</option><option value=''></option>";

  for(var i = 1 ; i <= 31; i++)
  {
    if (i == defaultValue) {
      html[idx++] = "<option value='" + i + "' selected>" + i + "</option>";
    } else {
      html[idx++] = "<option value='" + i + "'>" + i + "</option>";
    }
  }

  html[idx++] = "</select>";
  
  return html.join("");

}

function getMultiSelectHtml(myList, listId, selectValues) {

  var html = [];
  var idx = 0;
  
  html[idx++] = "<div class='multicheckbox'>";
  
  $.each(myList, function(key, value) {
    html[idx++] = "<div class='multicheckbox_row'>";
    if (selectValues != null && selectValues.contains(key)) {
      html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + key + "' " + "name='" + listId + "[]' value='" + key + "' checked /> " + value + " ";
    } else {
      html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + key + "' " + "name='" + listId + "[]' value='" + key + "' /> " + value + " ";
    }
    html[idx++] = "</div>";
  
  });
  html[idx++] = "</div>";
  
  return html.join("");
}

function getMultiSelectHtmlValue(listId) {

  var val = '';

  $('input[name=\"' + listId + '[]\"]').each(function(index, domElt) {
    if ($(this).is(':checked')) {
      if (val != '') {
        val += ',';
      }
      val+=$(this).val();
    }
  });

  return val;
}

function getMultiSelectHtmlNumericValue(listId) {

  var val = 0;

  $('input[name=\"' + listId + '[]\"]').each(function(index, domElt) {
    if ($(this).is(':checked')) {
      if ($(this).val() >= 1) {
        val+=Math.pow(2,$(this).val()-1);
      }
    }
  
  });

  return val;
}


function getMultiCheckBoxHtml(myList, listId, selectValues) {
  var html = [];
  var idx = 0;
  
  $.each(myList, function(key, value) {
    if (selectValues != null && selectValues.contains(key)) {
      html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + key + "' " + "name='" + listId + "[]' value='" + key + "' checked /> " + value + " ";
    } else {
      html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + key + "' " + "name='" + listId + "[]' value='" + key + "' /> " + value + " ";
    }
  });
  
  return html.join("");
}

function getSortableListHtml(list, id, name, defaultValue, className, hint) {
  if (defaultValue == undefined) {
    defaultValue = '';
  }
  if (className == undefined) {
    className = '';
  }
  if (hint == undefined) {
    hint = '';
  }
  var html = [];
  var idx = 0;
  var list_keys = getArrayKeys(list);
  
  html[idx++] = "<div style='position: relative;'>"
      + "<table id='" + id + "_table'>"
      + "<tr><td rowspan='3'>"
      + "<select id='" + id + "_options' class='" + className + "' multiple size=" + list_keys.length + " style='overflow:hidden;'>";
  
  var keys;
  if (defaultValue == '') {
    keys = list_keys;
    defaultValue = keys.join(",");
  } else {
    keys = defaultValue.split(",");
    if (keys.length < list_keys.length) {
      keys = list_keys;
      defaultValue = keys.join(",");
    }
  }
  
  for (var i=0; i<keys.length; i++) {
    var key = keys[i];
    html[idx++] = "<option value='" + key + "'>" + stripslashes(list[key]) + "</option>";
  }
  
  html[idx++] = "</select></td><td height='11' valign=top style='vertical-align:top;height: 11px; max-height: 11px;'><img src='/images/icons/flechehaut.jpg' alt='" + _('Move Up') + "' title='" + _('Move Up') + "' onclick='moveOptionsUp(\"" + id + "\")'/>";
  
  if (hint.length) {
    html[idx++] = "<span class='questionmark' style='margin: 0px 0 0 10px;'><span class='tooltip'>" + hint + "<span class='tooltip-pointer'>&nbsp;</span></span></span>";
  }
  html[idx++] = "</td></tr><tr height=80%><td>&nbsp;</td></tr><tr><td height='11' valign=bottom style='vertical-align:bottom;'><img src='/images/icons/flechebas.jpg' alt='" + _('Move Down') + "' title='" + _('Move Down') + "' onclick='moveOptionsDown(\"" + id + "\")'/></td></tr></table>";  
  html[idx++] = "</div><input type='hidden' id='" + id + "' name='" + name + "' value='" + defaultValue + "'/>";

  return html.join("");
}

function getRadioButtonValue(name) {
  var val = '';
  $('input[type=radio][name="' + name + '"]').each(function(index, domElt) {
      if ($(this).is(':checked')) {
        val = $(this).val();
      }
    });
  return val;
}

function checkRadioButtonByValue(name, val) {
  $('input[type=radio][name="' + name + '"]').each(function(index, domElt) {
      if ($(this).val() == val) {
        $(this).attr('checked', 'checked');
      } else {
        $(this).removeAttr('checked');
      }
    });
}

function getMultipleCheckboxValues(name) {
  vals = Array();
  $('input[type=checkbox][name="' + name + '"]').each(function(index, domElt) {
      if ($(this).is(':checked')) {
        vals.push($(this).val());
      }
    });
  return vals.join(',');
}

function getFCKEditorHtml(id, value, height, width, toolbarSet) {
  FCKeditorAPI = null; 
  __FCKeditorNS = null;
  var oFCKeditor = new FCKeditor(id) ;
  oFCKeditor.BasePath	= '/js/fckeditor/';
  oFCKeditor.Height	= height;
  oFCKeditor.Width	= width;
  oFCKeditor.ToolbarSet	= toolbarSet;
  oFCKeditor.Config['LinkBrowser']	= 'false';
  oFCKeditor.Config['LinkUpload']	= 'false';
  oFCKeditor.Value	= value;
  var html = oFCKeditor.CreateHtml();
  return html;
}

function setFCKEditor(id, name, value, height, width, toolbarSet) {
  var html = getFCKEditorHtml(id, value, height, width, toolbarSet);
  $('#' + id).replaceWith(html);
  $('#' + id).attr('name', name);
}

function buildCalendar(fieldId, onFocus) {
  var dateOptions = {
    showOn: onFocus ? "focus" : "button",
    buttonImage: "../images/datepicker/datepicker.jpg",
    buttonImageOnly: true,
    showButtonPanel: true,
    changeMonth: true,
    changeYear: true,
    showOtherMonths: true,
    selectOtherMonths: true,
    //dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    dateFormat: global_dateFormat,
    constrainInput: false,
    showAnim: null,
    duration: '',
  	//minDate: 0,
  	beforeShow: function(input, inst) { $('#ui-datepicker-div').css('z-index', 9999);},
  	create: function(event, ui) { $('#ui-datepicker-div').css('z-index', 9999); }
  };
  var $el = $("#" + fieldId);
  $el.datepicker(dateOptions);
}
function buildCombobox(fieldId, suggestionList, callback) {
  var input = $('#' + fieldId);
  
  input.autocomplete({
    source: suggestionList,
    minLength:0,
    select: function(event, ui) {
			input.val(ui.item.label);
			if (callback) {
        callback(event, ui);
      }
			return false;
		}
  });
  var button = $( "<button class='dropdown-icon'>&nbsp;</button>" )
  	.attr("tabIndex", -1)
  	.attr("title", _("Show All Items"))
  	.insertAfter(input)
  	.click(function() {
  	  //var input = $('#' + fieldId);
  		// close if already visible
  		if (input.autocomplete("widget").is(":visible")) {
  			input.autocomplete("close");
  			return;
  		}
  		// pass empty string as value to search for, displaying all results
  		input.autocomplete("search", "");
  		input.focus();
  	});
}

function buildMenuFromInput(input, data, menuId, liPrefix, callback) {
  input.hide();
  var inputId = input.attr('id');
  
  var menu = $('#' + menuId);
  if (menu.length) {
    menu.remove();
  }
  //if (!menu.length) {
    var menuElt = to_ul(data, menuId, liPrefix);
    menu = $(menuElt);
    $(document.body).append(menu);
    menu.hide();
  //}
  var buttonId = 'menu-button-' + inputId;
  var label = input.val() ? $('#' + liPrefix + input.val()).find('a').first().text() : _('--');
  var button = $('<button class="menu-button" id="' + buttonId + '"><span>' + label + '</span></button>');
  button.insertAfter(input);
  //menu.insertAfter(button);
  //var label = input.val() ? $('#' + liPrefix + input.val()).find('a').first().text() : _('Please select');
  //button.text(label);
  //alert(ul.innerHTML);

  /*button.button({
		icons: {
			//primary: "ui-icon-home",
			secondary: "ui-icon-triangle-1-s"
		}
	});*/
	button.focus(function() {
    $(this).addClass('focus');
  }).blur(function() {
    $(this).removeClass('focus');
  });
  
	menu.menu({
		select: function(event, ui) {
			//alert(ui.item[0].tagName);
			var li = ui.item;
			/*
      if (li.children().find('span.disabled').length) {
			  //menu.menu("right", event);
			  //event.stopPropagation();
			   
			  if (menu.menu("right", event)) {
					event.stopImmediatePropagation();
				}
				menu.menu("blur", event);
				menu.menu("focus", event, li);
				event.preventDefault();
			   
        return false;
      }
      */
      
			$(this).hide();
			var title = li.find('a').first().text();
			var key = li.attr('id') ? li.attr('id').replace(liPrefix, '') : '';
			input.val(key);
			//$('.ui-button-text', button).text(title);
			//button.text(title);
			$('span', button).text(title);
			if (callback) {
        callback(event, ui);
      }
			//$("#log").append("<div>Selected " + ui.item.text() + "</div>");
		},
		input: button
	}).hide();
  
  button.click(function(event) {
		//var menu = $(this).next();
		if (menu.is(":visible")) {
			menu.hide();
			return false;
		}
		menu.show().position({
			my: "left top",
			at: "left bottom",
			of: this
		}).css({zindex:99999});
/*		
    var buttonPos = button.findPos();
		menu.css({
      position:'absolute',
		  top:(buttonPos.y + button.height()) + "px",
		  left:(buttonPos.x) + "px",
		  'z-index':99999
		});
*/		
		$(document).one("click", function() {
			menu.hide();
		});
		return false;
	});  

}

function to_ul(obj, id, liPrefix) {
  var ul = document.createElement("ul");
  if (id) {
    ul.id = id;
  }
  for (var i = 0; i < obj.length; i++) {
    li = document.createElement ("li");
    var li = document.createElement("li");
    if (obj[i].key) {
      li.id = liPrefix + obj[i].key;
    }
    if (obj[i].style) {
      li.style.cssText = obj[i].style;
    }
    
    var a = document.createElement("a");
    a.href = '#';
    var span = document.createElement("span");
    if (obj[i].addClass) {
      span.className = obj[i].addClass;
    }
    //span.appendChild(document.createTextNode(obj[i].title))
    a.appendChild(span);
    a.appendChild(document.createTextNode(obj[i].title));
    if (obj[i].onClick) {
      a.onclick = obj[i].onClick;
    }
    li.appendChild(a);
    
    // if the child has a 'folder' prop on its own, call me again
    if (obj[i].children && obj[i].children.length) {
      li.appendChild (to_ul(obj[i].children, undefined, liPrefix));
    }
    ul.appendChild (li);
  }
  return ul;
}

/*
function to_ul (obj) {
  // --------v create an <ul> element
  var f, li, ul = document.createElement ("ul");
  // --v loop through its children
  for (f = 0; f < obj.children.length; f++) {
    li = document.createElement ("li");
    li.appendChild (document.createTextNode (obj.children[f].title));
    // if the child has a 'folder' prop on its own, call me again
    if (obj.children[f].children) {
      li.appendChild (to_ul (obj.children[f].children));
    }
    ul.appendChild (li);
  }
  return ul;
}
*/
/* End Fields */

/* Menu */
function trimLastSlash(s) {
  if (s.charAt(s.length-1,1) == "/")
    return s.substring(0,s.length-1);
  return s;
}
function highlightActiveMenu(menuId)
{
	if (!menuId) {
    menuId = "nav";
  }
  var currentUrl = document.location.href ? document.location.href : document.location;
  $('#' + menuId + ' li').each(function(i, liElt) {
    var selected = false;
    $('a', $(this)).each(function(j, aElt) {
      if(trimLastSlash(aElt.href) == trimLastSlash(currentUrl)) {
    	 selected = true;
      }
    });
    if (selected) {
      $(this).addClass("active");
    } else {
      $(this).removeClass("active");
    }
  });
/*  
  var currentUrl = document.location.href ? document.location.href : document.location;
  var navRoot = document.getElementById(menuId);
  for (var i=0; i<navRoot.childNodes.length; i++) {
    var node = navRoot.childNodes[i];
    if (node.nodeName=="LI") {
      var links = node.getElementsByTagName("a");
      var selected = false;
      for (var j=0; j < links.length; j++) {
    		if(trimLastSlash(links[j].href) == trimLastSlash(currentUrl))
    		{
  				selected = true;
  				break;
    		}
      }
      if (selected) {
        node.className += " active";
      } else {
        node.className.replace(" active", "");
      }
      //setLastSubMenuClass(node);
    })
  }
*/
}

function highlightActiveSubmenu() {
  var currentUrl = document.location.href ? document.location.href : document.location;
  $('#menu ul li, .sub-menu ul li').each(function(i, liElt) {
    var selected = false;
    $('a', $(this)).each(function(j, aElt) {
      if(trimLastSlash(aElt.href) == trimLastSlash(currentUrl)) {
    	 selected = true;
      }
    });
    if (selected) {
      $(this).addClass("active");
      var activeMenuId = $(this).parent().parent().attr('id').replace('sub_menu_', 'menu_');
      if (activeMenuId)
        $('#' + activeMenuId).addClass("active");
    } else {
      $(this).removeClass("active");
    }
  });
}

function setLastSubMenuClass(node) {
  var ullist = node.getElementsByTagName("ul");
  if (ullist.length) {
    var ulnode = ullist[0];
    var lilist = ulnode.getElementsByTagName("li");
    if (lilist.length) {
      lilist[lilist.length - 1].className += " last";
    }
  }
}

/* End Menu */
/* IE manage hover */
function ie_manage_hover(id) {
  if (document.all&&document.getElementById) {
    if (document.getElementById(id)) {
      navRoot = document.getElementById(id);
      for (i=0; i<navRoot.childNodes.length; i++) {
        node = navRoot.childNodes[i];
        if (node.nodeName=="LI") {
          manage_hover(node);
          for (j=0; j<node.childNodes.length; j++) {
            node2 = node.childNodes[j];
            //alert(node2.innerHTML);
            if (node2.nodeName=="UL") {
              for (k=0; k<node2.childNodes.length; k++) {
                node3 = node2.childNodes[k];
                if (node3.nodeName=="LI") {
                  manage_hover(node3);
                }
              }
            }
          }
        }
      }
    }
  }
}

function manage_hover(node) {
  node.onmouseover=function() {
    //if (this.className.indexOf("active") == -1)
      this.className+=" over";
  }
  node.onmouseout=function() {
    this.className=this.className.replace(" over", "");
  }
}
/* End IE manage hover */

/* Multi select checkbox */
function initMSC() {
  if (isIE6) {
    $('.MCP_option input').each(function(index, domElt) {
      $(this).mouseover(function(event) {
        $(this).addClass('hover');
      });
      $(this).mouseout(function(event) {
        $(this).removeClass('hover');
      });
    });
  }
  window.currentMSC = null;
  $(document).click(function(e) {
    hideMSCOnClick(e);
  });
  $(document).keydown(function(e) {
    hideMSCOnKeyPress(e);
  });
}

   
function hideMSCOnClick(event) {
  var elt = $(event.target);
  if (window.currentMSC != null) {
    if (!elt.descendantOf($('#' + window.currentMSC + '_optionsContainer')) && !elt.descendantOf($('#' + window.currentMSC + '_select'))) {
        closeMSC(window.currentMSC);    
    }
  }
}

function hideMSCOnKeyPress(event) {
  if (event.keyCode == 27) {
    if (window.currentMSC != null) {
      closeMSC(window.currentMSC);
    }
  }
}
function toggleMSC(id) {
	var node = $('#' + id + '_optionsContainer');
	if (node.length > 0) {
		if (node.css("display") == 'none' || node.css("display") == '') {
			openMSC(id);
			if (isIE6) {
			 node.bgiframe();
			}
		} else {
			closeMSC(id);
		}
	}
}
function openMSC(id) {
  if (window.currentMSC != null) {
    closeMSC(window.currentMSC);
  }
  $('#' + id + '_optionsContainer').css("display", "block");
  //showMSCIframe(id);
  $('#' + id + '_label').addClass('focus');
  window.currentMSC = id;
}
function showMSCIframe(id) {
  if (isIE6) {
  //alert($(id + '_optionsContainer').offsetHeight);
    $('#' + id + '_iframehack').css("display", "block");
    $('#' + id + '_iframehack').height($('#' + id + '_optionsContainer').height());
  }
}

function closeMSC(id) {
  //if (isIE6) {
  //  $(id + '_iframehack').style.display = 'none';
  //}
  $('#' + id + '_optionsContainer').css("display", "none");
  $('#' + id + '_label').removeClass('focus');
  window.currentMSC = null;
  //updateMSC(id);
}
function updateMSC(id) {
  var tmp = Array();
  var labels = Array();
  selectedGroupList = Array();
  
  $('#' + id + '_optionsContainer input').each(function(index, domElt) {
    var currentInput = $(this);
    if (currentInput.is(':checked')) {
			if (currentInput.val()) {
				tmp.push(currentInput.val());
				labels.push(currentInput.next().html());
			}
		}
  });
  
	$('#' + id).val(tmp.join(','));
	var labelElt = $('#' + id + '_label');
	var label = '';
	if (tmp.length > 0) {
		//label.value = tmp.length + ' ' + label.selectedLabel;
		label = labels.join(',');
  } else {
		label = labelElt.data('emptyLabel');
  }
  labelElt.val(label);
  labelElt.attr('title', label);
  
  $('#' + id + '_optionsContainer .MCP_group').each(function(i, groupItem) {
    var groupElt = $(this);
    var folderId = groupElt.attr('id').replace('_group_', '_folder_');
    var selected = false;
    
    $('#' + folderId + ' input').each(function(j, domElt) {
      var currentInput = $(this);
      if (currentInput.is(':checked')) {
  			if (currentInput.val()) {
  				selected = true;
  				//break;
  			}
  		}
    });
    
    if (selected) {
      if (!groupElt.hasClass('selected')) {
        groupElt.addClass('selected');
      }
    } else {
      if (groupElt.hasClass('selected')) {
        groupElt.removeClass('selected');
      }
    }
  });

}

function toggleMSCFolder(groupElt, id, folderId) {
  var folderElt = $('#' + folderId);
  if (folderElt.css('display') == undefined
    || folderElt.css('display') == ''
    || folderElt.css('display') == 'none') {
    folderElt.css('display', 'block');
    $(groupElt).removeClass('expand');
    $(groupElt).addClass('collapse');
  } else {
    folderElt.css('display', 'none');
    $(groupElt).removeClass('collapse');
    $(groupElt).addClass('expand');
  }
  //if (isIE6) {
  //  var ref_height = $(id + '_optionsContainer').offsetHeight;
  //  $(id + '_iframehack').style.height = $(id + '_optionsContainer').offsetHeight;
  //}
}

function getMultiSelectCheckBoxHtml(myList, name, selectValues, width, width2, height, emptyLabel, selectedLabel, two_levels, sortBy) {
  var html = [];
  var idx = 0;

    //$ie6_hover = 'onmouseover="Element.addClassName(this,\'hover\');" onmouseout="Element.removeClassName(this,\'hover\')" ';
  if (emptyLabel == undefined)
    emptyLabel = '';
  if (selectedLabel == undefined)
    selectedLabel = '';

    if (selectValues && selectValues.length) {
      //label = selectValues.length + ' ' + selectedLabel;
      label = selectValues.join(',');
      value = html.join(',');
    } else {
      label = emptyLabel;
      value = '';
    }
	  html[idx++] = '<div class="MCP_control" id="' + name + '_select" onmousedown="toggleMSC(\'' + name + '\');"><input type="text" id="' + name + '_label" value="' + label + '" style="width:' + width + 'px;" onkeydown="return false;"/></div>';

		if (width2 == undefined)
  		width2 = (two_levels ? width + 150 : width);
		if (height == undefined || height == 0)
  		height = 160;
  		
	  html[idx++] = '<div class="MCP_optionsContainer" id="' + name + '_optionsContainer" style="width:' + width2 + 'px; max-height:' + height + 'px; height: expression(this.scrollHeight > ' + height + ' ? "' + height + 'px" : "auto");">';

    var sortedKeys = sortKeys(myList, sortBy);

    if (!two_levels) {

      for (var i = 0; i < sortedKeys.length; i++) {
        checked = (selectValues.length > 0 && selectValues.indexOf(sortedKeys[i]) > -1);
        currentId		= name + '_' + sortedKeys[i];
  			html[idx++] = '<div class="MCP_option' + (two_levels ? ' second-level' : '') + '">'
  							+ '<input type="checkbox" class="checkbox" id="' + currentId + '" value="' + sortedKeys[i] + '" '
  							+  (checked ? ' checked="checked" ' : '')
  							+ ' onclick="updateMSC(\'' + name + '\');"/>'
  							+ '<label style="width:' + (width2 - 47) + 'px;" '
  							+ 'onclick="$(\'#' + currentId + '\').attr(\'checked\', !$(\'#' + currentId + '\').is(\':checked\')); '
  							+ 'updateMSC(\'' + name + '\');">' + myaddslashes(myList[sortedKeys[i]]) + '</label>'
  							+ '<div style="clear:both;"></div>'
  							+ '</div>';
      
      }
    
    } else {
      var groupCounter = 0;
      $.each(myList, function(groupKey, subList) {
        groupCounter += 1;
        var groupId		= name + '_group_' + groupCounter;
        var folderId		= name + '_folder_' + groupCounter;
        //html[idx++] = '<div class="MCP_group expand" id="' + groupId + '" onclick="toggleMSCFolder(this, \'' + name + '\',\'' + folderId + '\');">' + group.key + '</div><div class="MCP_folder" id="' + folderId + '">';
      
        //var subList = myList[groupKey];
        var sortedKeys = sortKeys(subList, sortBy);

        var html2 = [];
        var idx2 = 0;
        isSelected = false;
        for (var i = 0; i < sortedKeys.length; i++) {
          checked = (selectValues.length > 0 && selectValues.indexOf(sortedKeys[i]) > -1);
          if (checked) {
            isSelected = true;
          }
          currentId		= name + '_' + sortedKeys[i];
    			html2[idx2++] = '<div class="MCP_option' + (two_levels ? ' second-level' : '') + '">'
    							+ '<input type="checkbox" class="checkbox" id="' + currentId + '" value="' + sortedKeys[i] + '" '
    							+  (checked ? ' checked="checked" ' : '')
    							+ ' onclick="updateMSC(\'' + name + '\');"/>'
    							+ '<label style="width:' + (width2 - 47) + 'px;" '
    							+ 'onclick="$(\'#' + currentId + '\').attr(\'checked\', !$(\'#' + currentId + '\').is(\':checked\')); '
    							+ 'updateMSC(\'' + name + '\');">' + myaddslashes(subList[sortedKeys[i]]) + '</label>'
    							+ '<div style="clear:both;"></div>'
    							+ '</div>';
        }
        html[idx++] = '<div class="MCP_group expand' + (isSelected ? ' selected' : '') + '" id="' + groupId + '" onclick="toggleMSCFolder(this, \'' + name + '\',\'' + folderId + '\');">' + group.key + '</div><div class="MCP_folder" id="' + folderId + '">';
        html[idx++] = html2.join(""); 
        html[idx++] = '</div>'; 
      });
      
    }
		html[idx++] = '</div>';
		html[idx++] = '<div style="clear:both;"></div>';
		//html[idx++] = '<iframe id="' + name + '_iframehack" style="z-index: 9998; position: absolute; width: ' + (width2+2) + 'px; height: 160px; display: none;" frameborder="0"></iframe>';
		html[idx++] = '<input type="hidden" id="' + name + '" name="' + name + '" value="' + value + '" />';
		html[idx++] = '<script type="text/javascript">$("#' + name + '_label").data("emptyLabel", "' + emptyLabel + '"); $("#' + name + '_label").data("selectedLabel", "' + selectedLabel + '");</script>';
    return html.join("");
}
/* Multi select checkbox */
/* IE6 select z-index bug */
function hideSelectsIE6() {
  //$$('select').each(function(el) { Element.addClassName(el, 'hideselect');});  
}
function showSelectsIE6() {
  //$$('select').each(function(el) { Element.removeClassName(el, 'hideselect');});  
}
/* End IE6 select z-index bug */

/* Fake drop-down */
function isElementInside(src, dest) {
    while (src != null) {
        if (src.id == dest.id) {
            return true;
        }
        src = src.parentNode;
    }
    return false;
}
$.fn.descendantOf = function(element) {
    element = $(element)[0];
    var current = this[0];
    var body    = document.body;
    while (current && current != element && current != document.body) {
        current = $(current).parent()[0];
    }
    if (typeof(current) == "undefined" || typeof(current) == "null") {
        return false;
    } else if (current == element) {
        return true;
    } else if (current == document.body) {
        return false;
    }
}

function makeDropDown(link_id, menu_div_id) {
  if (!$('#' + link_id).length)
    return;
  $('#' + link_id).click(function() {
    $('#' + menu_div_id).toggle();
    if (isIE6) {
      if ($('#' + menu_div_id).css('display') == 'block') {
        $('#' + menu_div_id).bgiframe();
      }
    }
  });
  
  $(document).click(function(event) {
    var elt = $(event.target);
    if (!elt.descendantOf($('#' + menu_div_id)) && !elt.descendantOf($('#' + link_id))) {
      $('#' + menu_div_id).hide();
    }
  });
  $(document).keydown(function(event) {
    if (event.keyCode == 27) {
      $('#' + menu_div_id).hide();
    }
  });
  
}
/* End Fake drop-down */

/* Images preloading */
function preloadImages() {
	if (document.images) {
		for (var i = 0; i < preloadImages.arguments.length; i++) {
			(new Image()).src = preloadImages.arguments[i];
		}
	}
}
/* End Images preloading */

/* Tooltips */
function addTooltips() {
  $('span.questionmark').each(function(index, domElt) {
    addTooltip($(this));
  });
}

function addTooltip(questionSpan) {
    questionSpan.find('span').first().each(function(index, domElt) {
      var tooltipSpan = $(this);
      if (tooltipSpan.attr('class').indexOf("tooltip")>-1) {
        questionSpan.hover(function() {
          $(this).find('span').each(function(index, domElt) {
            var span2 = $(this);
            if (span2.attr('class').indexOf("tooltip")>-1) {
              span2.parent().parent().css('z-index', 100000);
              span2.show();
            }
          });
        }, function() {
          $(this).find('span').each(function(index, domElt) {
            var span2 = $(this);
            if (span2.attr('class').indexOf("tooltip")>-1) {
              span2.parent().parent().css('z-index', '');
              span2.hide();
            }
          });
        });
      }
    });
}

function addTooltipToField(inputField) {
  inputField.parent().find('span').each(function(index, domElt) {
    var span = $(this);
    if (span.attr('class').indexOf("questionmark")>-1) {
      addTooltip(span);
    }
  });
}

function showTooltip(event, tooltipHtml) {
  var tooltipId = 'tooltip';
  var delta_x = 5;
  var delta_y = 5;
  var zindex = 10000;

  var tooltip = $('#' + tooltipId);
  if (!tooltip.length) {
    tooltip = $('<div id="' + tooltipId + '" style="display:none;"></div>');
    $(document.body).append(tooltip);
  }
  
  // get Mouse position
  if (!event) {
    event = window.event;
  }
  var mouse_x = mousePosX(event);
  var mouse_y = mousePosY(event);

	// decide if wee need to switch sides for the tooltip
	var tooltipWidth = tooltip.width();
	var tooltipHeight = tooltip.height();
	var windowWidth = (navigator.appVersion.indexOf('MSIE')>0) ? document.body.clientWidth : window.innerWidth;
	var windowHeight = (navigator.appVersion.indexOf('MSIE')>0) ? document.body.clientHeight : window.innerHeight;
  
	if ( (tooltipWidth + mouse_x) >= ( windowWidth - delta_x) ){ // too big for X
		mouse_x = mouse_x - tooltipWidth;
		// apply delta to make sure that the mouse is not on the tool-tip
		mouse_x = mouse_x - delta_x;
	} else {
		mouse_x = mouse_x + delta_x;
	}
	
	if ( (tooltipHeight + mouse_y) >= ( windowHeight - delta_y) ){ // too big for Y
		mouse_y = mouse_y - tooltipHeight;
	    // apply delta to make sure that the mouse is not on the tool-tip
		mouse_y = mouse_y - delta_y;
	} else {
		mouse_y = mouse_y + delta_y;
	}
	
	// set the right styles to position the tool tip
  tooltip.html(tooltipHtml);
  tooltip.css({ position:'absolute',
	 								  top:mouse_y + "px",
	 								  left:mouse_x + "px",
									  zindex:zindex,
                    margin: "0px",
                	  padding: "0px",
                	  backgroundColor: "#d6d6fc"
	 								});
  
  tooltip.show();
}

function hideTooltip() {
	$('#tooltip').hide();
}

function showTooltip2(event, title, body) {
  var html = //'<div class="tooltip-title">' + title + '</div>' +
  '<div class="tooltip-body">' + title + '</div>';
  showTooltip(event, html);
}

function showInfotip(id, text) {
  $('<div class="infotip"><div class="infotip-right"></div><div class="infotip-text">' + text + '</div><div class="infotip-left"></div></div>').insertAfter($('#'+id));
}
function hideInfotip(id) {
  $('#'+id).parent().find('div.infotip').remove();
}
/* End Tooltips */

/* Tabs */
function selectTab(id, tab_name, section_name, tabs) {
  if (tabs == undefined)
    tabs = 'tabs';
  if (tab_name == undefined)
    tab_name = 'tab_';
  if (section_name == undefined)
    section_name = 'tabcontent_';
  
  $('#' + tabs).find('li').each(function(index, domElt) {
    var i = index + 1;
    if (i == id) {
      $('#' + tab_name + i).addClass('active');
      $('#' + tab_name + i).removeClass('default');
      $('#' + section_name + i).show();
    } else {
      $('#' + tab_name + i).removeClass('active');
      $('#' + tab_name + i).addClass('default');
      $('#' + section_name + i).hide();
    }
  });
}
/* End Tabs */

/* Editable form */
function showEditMenu(elt) {
  elt.addClass('hover');
  elt.children().each(function(index, domElt) {
    var node = $(this);
    if (node.attr('class') && node.attr('class').indexOf("actions")>-1) {
      node.show();
    }
  });
}

function hideEditMenu(elt) {
  elt.removeClass('hover');
  elt.children().each(function(index, domElt) {
    var node = $(this);
    if (node.attr('class') && node.attr('class').indexOf("actions")>-1) {
      node.hide();
    }
  });
}
/* End editable form */

/* String utilities */
function addslashes( str ) {
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}
function myaddslashes(ch) {
  if (!ch || ch.length == 0) {
    return '';
  }
  ch = ch.replace(/\\/g,"\\\\")
  //ch = ch.replace(/\'/g,"'")
  ch = ch.replace(/\"/g,"'")
  return ch;
}
function stripslashes( str ) {
  return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}
function removeslashes(str) {
  return str.replace('"', '').replace('\'', '');
}
function truncateText(str, len) {
  if (str.length > len) {
    return str.substring(0,len) + '...';
  }
  return str;
}

function utf8_encode(string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	for (var n = 0; n < string.length; n++) {
		var c = string.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	return utftext;
}
 
function utf8_decode(utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;
	while ( i < utftext.length ) {
		c = utftext.charCodeAt(i);
		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return string;
}

function removeAccents(strAccents){
    strAccents = strAccents.split('');
    strAccentsOut = new Array();
    strAccentsLen = strAccents.length;
    var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
    var accentsOut = ['A','A','A','A','A','A','a','a','a','a','a','a','O','O','O','O','O','O','O','o','o','o','o','o','o','E','E','E','E','e','e','e','e','e','C','c','D','I','I','I','I','i','i','i','i','U','U','U','U','u','u','u','u','N','n','S','s','Y','y','y','Z','z'];
    for (var y = 0; y < strAccentsLen; y++) {
        if (accents.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = accentsOut[accents.indexOf(strAccents[y])];
        }
        else
            strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');
    return strAccentsOut;
}
 
/* End String utilities */
/* Sorter */
function moveOptionsUp(id) {
 var selectList = document.getElementById(id + '_options');
 var selectOptions = selectList.getElementsByTagName('option');
 for (var i = 1; i < selectOptions.length; i++) {
  var opt = selectOptions[i];
  if (opt.selected) {
   selectList.removeChild(opt);
   selectList.insertBefore(opt, selectOptions[i - 1]);
  }
 }
  updateSorter(id);
}
function moveOptionsDown(id) {
 var selectList = document.getElementById(id + '_options');
 var selectOptions = selectList.getElementsByTagName('option');
 for (var i = selectOptions.length - 2; i >= 0; i--) {
  var opt = selectOptions[i];
  if (opt.selected) {
   var nextOpt = selectOptions[i + 1];
   opt = selectList.removeChild(opt);
   nextOpt = selectList.replaceChild(opt, nextOpt);
   selectList.insertBefore(nextOpt, opt);
  }
 }
  updateSorter(id);
}
function updateSorter(id)
{
  var selectList = document.getElementById(id + '_options');
  var value = '';
  for (var i=0; i< selectList.options.length;i++)
  {
    if (value != '')
      value += ','
    value += selectList.options[i].value;
  }
  document.getElementById(id).value = value;
}
/* End Sorter */

/* Pagination */

function buildPager(elt, opts) {
    // Parameters
  	opts = jQuery.extend({
      nb_pages:0,
      current_page:1,
      link_to:"#",
      num_display_entries:10,
      num_edge_entries:2,
      prev_text:_('Prev'),
      next_text:_('Next'),
      ellipse_text:'...',
      prev_show_always:true,
      next_show_always:true,
      callback:function(page_id){return false;}
  	},opts||{});

    // Calculate start and end point of pagination links depending on current_page and num_display_entries
    var nb_pages = opts.nb_pages;
    var current_page = opts.current_page;
		var ne_half = Math.ceil(opts.num_display_entries/2);
		var upper_limit = nb_pages - opts.num_display_entries;
		var start = current_page-1>ne_half?Math.max(Math.min(current_page-1-ne_half, upper_limit), 0):0;
		var end = current_page-1>ne_half?Math.min(current_page-1+ne_half, nb_pages):Math.min(opts.num_display_entries, nb_pages);
    
    elt.empty();
    elt.addClass('pagination');
    
    // Generate previous link
		if (opts.prev_text) {
      if(current_page > 1) {
        var $a = $('<a class="prev" href="#">' + opts.prev_text + '</a>');
        $a.data('page_id', current_page - 1);
        /*$a.click(function() {
          return opts.callback($(this).data('page_id'));
        });*/
        elt.append($a);        
      } else {
  		  if (opts.prev_show_always) {
  		    elt.append('<span class="prev disabled">' + opts.prev_text + '</span>');
        }
      }    
    }
    
    // Generate starting points
    if (start > 0 && opts.num_edge_entries > 0) {
      var end2 = Math.min(opts.num_edge_entries, start);

      for (var i=0; i<end2; i++) {
    		if (i == current_page-1) {
  		    elt.append('<span class="current">' + (i + 1) + '</span>');
    		} else {
          var $a = $('<a href="#">' + (i + 1) + '</a>');
          $a.data('page_id', i + 1);
          /*$a.click(function() {
            return opts.callback($(this).data('page_id'));
          });*/
          elt.append($a); 
        }
      }

			if (opts.num_edge_entries < start) {
			  elt.append('<span>' + opts.ellipse_text  + '</span>');
			}
    }
    

		// Generate interval links
    for (var i=start; i<end; i++) {
  		if (i == current_page-1){
		    elt.append('<span class="current">' + (i + 1) + '</span>');
  		} else {
        var $a = $('<a href="#">' + (i + 1) + '</a>');
        $a.data('page_id', i + 1);
        /*$a.click(function() {
          return opts.callback($(this).data('page_id'));
        });*/
        elt.append($a); 
      }
    }
    
    // Generate ending points
    if (end < nb_pages && opts.num_edge_entries > 0) {

			if (nb_pages - opts.num_edge_entries > end && opts.ellipse_text) {
			  elt.append('<span>' + opts.ellipse_text  + '</span>');
			}

      var begin = Math.max(nb_pages - opts.num_edge_entries, end);

      for (var i=begin; i<nb_pages; i++) {
    		if (i == current_page-1){
  		    elt.append('<span class="current">' + (i + 1) + '</span>');
    		} else {
          var $a = $('<a href="#">' + (i + 1) + '</a>');
          $a.data('page_id', i + 1);
          /*$a.click(function() {
            return opts.callback($(this).data('page_id'));
          });*/
          elt.append($a); 
        }
      }
    } 

    // Generate next link
    if (opts.next_text) {
  		if (current_page < nb_pages) {
        var $a = $('<a class="next" href="#">' + opts.next_text + '</a>');
        $a.data('page_id', current_page + 1);
        /*$a.click(function() {
          return opts.callback($(this).data('page_id'));
        });*/
        elt.append($a);        
  		} else {
  		  if (opts.next_show_always) {
  			  elt.append('<span class="next disabled">' + opts.next_text  + '</span>');
        }
      }    
    }
    
    $('a', elt).click(function() {
      return opts.callback($(this).data('page_id'));
    });
}

/* End Pagination */

function checkLength(textField, maxLength, displayCharsLeft) {
    var charsLeft;
    if (textField.value.length > maxLength) {
      textField.value = textField.value.substring(0,maxLength);
      charsLeft = 0;
    }
    else {
      charsLeft = maxLength - textField.value.length;
    }
    if (displayCharsLeft != undefined) {
      displayCharsLeft.innerHTML = ' (' + charsLeft + ' ' + _('characters left') + ')';
    }
}


function clearSearchText(argElement, defaultText) {
  if (!argElement) {
    argElement = $('#searchKeyword');
  } else {
    argElement = $(argElement);
  }
  if (argElement.val() == defaultText) {
    argElement.val('');
    argElement.removeClass('default');
  }
}

function fillSearchText(argElement, defaultText) {
  if (!argElement) {
    argElement = $('#searchKeyword');
  } else {
    argElement = $(argElement);
  }
  if (argElement.val() == '') {
    argElement.val(defaultText);
    argElement.addClass('default');
  }
}

/* Scrolling */
var scrolling = null;

function scroll_up(scroller_id, up_arrow_id, down_arrow_id) {
    var d = document.getElementById(scroller_id);
    d.scrollTop = d.scrollTop - 5 < 0 ? 0 :  d.scrollTop - 5;
    show_hide_arrows(scroller_id, up_arrow_id, down_arrow_id);
    scrolling = window.setTimeout(function() {scroll_up(scroller_id, up_arrow_id, down_arrow_id);},60);
}

function scroll_down(scroller_id, up_arrow_id, down_arrow_id) {
    var d = document.getElementById(scroller_id);
    d.scrollTop = (d.scrollTop + 5) > d.scrollHeight - d.offsetHeight ? d.scrollHeight - d.offsetHeight : d.scrollTop + 5;
    show_hide_arrows(scroller_id, up_arrow_id, down_arrow_id);
    scrolling = window.setTimeout(function() {scroll_down(scroller_id, up_arrow_id, down_arrow_id);},60);
}

function stop_scroll(){
    window.clearTimeout(scrolling);
}

function show_hide_arrows(scroller_id, up_arrow_id, down_arrow_id) {
    var d = document.getElementById(scroller_id);
    if (d.scrollTop <= 0) {
      document.getElementById(up_arrow_id).style.display = 'none';
    } else {
      document.getElementById(up_arrow_id).style.display = 'block';
    }
    
    if (d.scrollTop >= d.scrollHeight - d.offsetHeight) {
      document.getElementById(down_arrow_id).style.display = 'none';
    } else {
      document.getElementById(down_arrow_id).style.display = 'block';
    }
  
}
    
/* End Scrolling */

/* Slideshow */
function slideSwitch() {
  var $active = $('#slideshow div.active');
  if ($active.length == 0) $active = $('#slideshow div.slide:last');
  var $next =  $active.next('div.slide').length ? $active.next('div.slide') : $('#slideshow div.slide:first');
  $active.addClass('last-active');
  $next.css({opacity: 0.0})
      .addClass('active')
      .animate({opacity: 1.0}, 1000, function() {
          $active.removeClass('active last-active');
      });
}

/* End Slideshow */

/* Number utils */
function formatNumber(f,n) {
  return formatThousands(parseFloat(f).toFixed(n));
}

function formatInCurrency(f, n) {
  n = n == undefined ? 2 : n;
  if (!f || isNaN(f)) {
    return '0€';
  }
  return formatThousands(parseFloat(f).toFixed(n))+'€';
}

function formatThousands(v, thousandSeparator) {
    thousandSeparator = thousandSeparator || ' ';
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    //var sub = ps[1] ? '.' + ps[1] : '.00';
    var sub = ps[1] ? '.' + ps[1] : '';
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + thousandSeparator + '$2');
    }
    v = whole + sub;
    return v;
}

function formatMoney(v) {
    v = (Math.round((v - 0) * 100)) / 100;
    v = (v == Math.floor(v)) ? v + ".00": ((v * 10 == Math.floor(v * 10)) ? v + "0": v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.' + ps[1] : '.00';
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    v = whole + sub;
    if (v.charAt(0) == '-') {
        return '-' + v.substr(1);
    }
    return "+" + v;
}

function formatNominal(v) {
	 var value = com.eqd.iprice.utils.formatMoney(v);
	 return value.substring(0, value.length - 3); // no decimal
}
/* End Number utils */

/* Login */
function clear_login() {
	if ($('#login').val() == _('Email')) {
		$('#login').val('');
		$('#password').val('');
	}
}
function init_login() {
	if ($('#login').val() == '') {
		$('#login').val(_('Email'));
	}
}
/* End Login */

/* Videos */
function initPlayer(theWrapper, thePlaceholder, thePlayerId, theFile, options) { 
    deletePlayer(theWrapper, thePlaceholder, thePlayerId); 
    createPlayer(thePlaceholder, thePlayerId, theFile);
}

function deletePlayer(theWrapper, thePlaceholder, thePlayerId) { 
    //swfobject.removeSWF(thePlayerId);
    var tmp=document.getElementById(theWrapper);
    if (tmp) { tmp.innerHTML = "<div id=" + thePlaceholder + "></div>"; }
}

function createPlayer(thePlaceholder, thePlayerId, theFile, options) {
    options.width = options.width || "344";
    options.height = options.height || "300";
    options.autostart = options.autostart || "false";
    
    var flashvars = {
            file:theFile, 
            autostart:options.autostart
    }
    var params = {
            allowfullscreen:"true", 
            allowscriptaccess:"always",
            wmode:"transparent"
    }
    var attributes = {
            id:thePlayerId,  
            name:thePlayerId
    }
    swfobject.embedSWF("/js/flvplayer/player.swf", thePlaceholder, options.width, options.height, "9.0.115", false, flashvars, params, attributes);
}
/* End Videos */

