//browser detection

// works also for IE8 beta
var isExplorer = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isNetscape = (navigator.userAgent.indexOf("Netscape") != -1) ? true : false;
var isFirefox = (navigator.userAgent.indexOf("Firefox") != -1) ? true : false;
var isChrome = (navigator.userAgent.indexOf("Chrome") != -1) ? true : false;
var isSafari = !isChrome && (navigator.userAgent.indexOf("Safari") != -1) ? true : false;

isNetscape = isNetscape || isFirefox;

//OS detection
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isMac = (navigator.appVersion.toLowerCase().indexOf("mac") != -1) ? true : false;
var isUnix = (navigator.appVersion.toLowerCase().indexOf("x11") != -1) ? true : false;
var isLinux = (navigator.appVersion.toLowerCase().indexOf("linux") != -1) ? true : false;

//Version detection
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var version = navigator.appVersion.substring(0, 1);


// global variables
var zIndex=0;
var mouseX = 0;
var mouseY = 0;
var muteAlertOnChange = false;
var inhibitTooltips = false;


// decrecated use $("#domid").get()
function obj(element) {
  if (arguments.length > 1) {
    alert("invalid use of obj with multiple params:" + element)
  }
  return document.getElementById(element);
}

function truebody() {
  return $("body").get(0);
}

function createEl(theEl) {
  return document.createElement(theEl);
}

if(!window.console) {
  window.console = new function() {
    this.log = function(str) {alert(str)};
    this.debug = function(str) {alert(str)};
  };
}

function sendWindowResizeMessage() {
  executeCommand('UPDATEWINSIZE', "PAGE_HEIGHT=" + getWindowDimensionH() + "&PAGE_WIDTH=" + getWindowDimensionW());
}

//get mouse position
function pageX(event){
  mouseX = event.clientX+$(document).scrollLeft();
  return mouseX;
}
function pageY(event){
  mouseY = event.clientY+$(document).scrollTop();
  return mouseY;
}

function getMouseXY(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
  if (mouseX < 0) {
    mouseX = 0;
  }
  if (mouseY < 0) {
    mouseY = 0;
  }

}

// return true when set to visible
function showHideSpan(spanId) {
  var span = $('#' + spanId);
  var visibility;
  if (span.css("display") == 'none') {
    span.fadeIn();
    visibility = true;
  } else {
    span.fadeOut();
    visibility = false;
  }
  return visibility;
}

function showHideDiv(divId) {
  var div = $('#' + divId);
  if (div.css("display") == 'none') {
    displayDiv(divId);
  } else {
    displayNoneDiv(divId);
  }
}

function displayDiv(divId) {
  if (obj(divId))
    obj(divId).style.display = '';
}

function displayNoneDiv(divId) {
  if (obj(divId))
    obj(divId).style.display = 'none';
}

function centerPopup(url, target, w, h, scroll, resiz) {
  var winl = (screen.width - w) / 2;
  var wint = (screen.height - h) / 2;
  var winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable=' + resiz + ', toolbars=false, status=false, menubar=false';
  var win = window.open(url, target, winprops);
  if (!win)
    alert("A popup blocker was detected: please allow them for this application (check out the upper part of the browser window).");
  if (parseInt(navigator.appVersion) >= 4) {
    win.window.focus();
  }
}

function openCenteredWindow(url, target, winprops) {
  var prop_array = winprops.split(",");
  var i = 0;
  var w = 800;
  var h = 600;
  if (winprops && winprops != '') {
    while (i < prop_array.length) {
      if (prop_array[i].indexOf('width') > -1) {
        s = prop_array[i].substring(prop_array[i].indexOf('=') + 1);
        w = parseInt(s);
      } else if (prop_array[i].indexOf('height') > -1) {
        s = prop_array[i].substring(prop_array[i].indexOf('=') + 1);
        h = parseInt(s);
      }
      i += 1;
    }
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    winprops = winprops + ",top=" + wint + ",left=" + winl;
  }
  win = window.open(url, target, winprops);
  if (!win)
    alert("A popup blocker was detected: please allow them for this application (check out the upper part of the browser window).");
  if (parseInt(navigator.appVersion) >= 4) {
    win.window.focus();
  }
}


//----------------------------------positioning-----------------------------------------------
$.fn.bringToFront=function(){
      var zi=10;
      $('*').each(function() {
        if($(this).css("position")=="absolute"){
          var cur = parseInt($(this).css('zIndex'));
          zi = cur > zi ? parseInt($(this).css('zIndex')) : zi;
        }
      });

      $(this).css('zIndex',zi+=10);
    };

/*function bringToFront(elid) {
  var elsInPage = $("*");
  obj(elid).style.zIndex = elsInPage.length + 1;
}*/

function bringToFront(elid) {
  $("#"+elid).bringToFront();
}

// to determine the real x position of the element
function getAbsoluteLeft(el) {
  if (el) {
    var xPos = el.offsetLeft;
    var tempEl = el.offsetParent;
    while (tempEl != null) {
      xPos += tempEl.offsetLeft;
      tempEl = tempEl.offsetParent;
    }
    return xPos;
  }
}

// to determine the real y position of the element

function getAbsoluteTop(el) {
  yPos = el.offsetTop;
  tempEl = el.offsetParent;
  while (tempEl != null) {
    yPos += tempEl.offsetTop;
    tempEl = tempEl.offsetParent;
  }
  return yPos;
}

// 09/09/09 Modify by bicocchi
function nearBestPosition(whereId, theObjId) {
  var el = obj(whereId);
  var target = obj(theObjId);
  if (el) {
    target.style.visibility = "hidden";
    var trueX = getAbsoluteLeft(el);
    var trueY = getAbsoluteTop(el);
    var h = el.offsetHeight;
    var elHeight = parseFloat(h);
    trueY += parseFloat(elHeight);
    var left = trueX + "px";
    var top = trueY + "px";
    var marginTop = "0px";
    var barHeight = (isExplorer) ? 45 : 35;
    var barWidth = (isExplorer) ? 20 : 0;
    //added if by Pietro 10Aug07
    if (trueX && trueY) {
      target.style.left = left;
      target.style.top = top;
    }
    if (getAbsoluteLeft(target) >= (getWindowDimensionW() - target.offsetWidth)) {
      left = getWindowDimensionW() - target.offsetWidth - barWidth + "px";
      target.style.left = left;
    }

    /*if ((getAbsoluteTop(target)  + target.offsetHeight >= ((getWindowDimensionH() - barHeight))) && (target.offsetHeight < getWindowDimensionH())) {

      console.debug("target.offsetHeight "+target.offsetHeight);
      console.debug("getWindowDimensionH() "+getWindowDimensionH());  

      target.style.marginTop = (-(el.offsetHeight + target.offsetHeight)) + "px";
    } */
    target.style.visibility = "visible";
  }
}

$.fn.keepItVisible= function(){
  var isFixed= false;  // todo: verify
  var thisTop = $(this).offset().top;
  var thisLeft = $(this).offset().left;
  var windowH = isFixed ? $(window).height() : $(window).height() + $(window).scrollTop();
  var windowW = isFixed ? $(window).width(): $(window).width() + $(window).scrollLeft();
  if(thisTop + $(this).outerHeight() > windowH)
   $(this).css("margin-top", -$(this).outerHeight());
  if(thisLeft + $(this).outerWidth() > windowW)
   $(this).css("margin-left", -$(this).outerWidth());
  $(this).css("visibility","visible");
}

//windowDimension
function getWindowDimensionH() {
  return $(window).height();
}

function getWindowDimensionW() {
  return $(window).width();
}                                                                 

/*function getScrollW() {
  return  window.pageXOffset ||
          document.body.scrollLeft ||
          document.documentElement.scrollLeft;
}

function getScrollH() {
  return  window.pageYOffset ||
          document.body.scrollTop ||
          document.documentElement.scrollTop;
}*/


function centerObject(objId) {
  if (obj(objId)) {
    var theObject = obj(objId);
    if (theObject) {
      theObject.style.position = "absolute";
      theObject.style.top = document.body.scrollTop + (document.body.clientHeight - parseFloat(theObject.offsetHeight)) / 2 + 'px';
      theObject.style.left = document.body.scrollLeft + (document.body.clientWidth - parseFloat(theObject.offsetWidth)) / 2 + 'px';
    }
  }
}
//END positioning


// event handling START -------------------------------
function getTarget(e) {
  var listTheTarget = (isExplorer) ? event.srcElement : e.target;
  if (listTheTarget.nodeType == 3)
    listTheTarget = listTheTarget.parentNode;
  return listTheTarget;
}

function dragStart(event, id) {
  $("#"+id).draggable({stop:function(e,o){$(this).draggable("destroy");}});
  bringToFront(id);
}

//-- START AJAX ---------------------------------------------------------------------------

//var xmlHttpRequestObject;
function getXMLObj() {
  var req;
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch(e) {
      req = false;
    }
    // branch for IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        req = false;
      }
    }
  }
  return req;
}

function getContent(href, data) {
  // in order to avoid caching on IE
  if (href.indexOf("?") < 0)
    href = href + "?_=" + new Date().getMilliseconds();
  else
    href = href + "&_=" + new Date().getMilliseconds();
  //ret must be absolute!!!!!!!!!!!!!!
  ret = "";
  req = getXMLObj();
  req.open('POST', href, false);
  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

  if (data) {
    req.send(data);
  } else {
    req.send('');
  }

  if (req.status == 200) {
    ret = req.responseText;
    return ret;

    // 404 url not found -
  } else if (req.status == 404) {
    return 'File not found';

    // 500 internal server error
  } else if (req.status == 500) {
    //alert('ajax request status is ' + req.status + ' for ' + href) ;
    return 'ajax request status is ' + req.status + ' for ' + href;
  }
}

function loadSyncroContent(href, objId, data) {
  //if (obj(objId))
  //  obj(objId).innerHTML = getContent(href, data);
  $("#"+objId).html(getContent(href, data));
}

function loadSyncroTextContent(href, objId, data) {
  obj(objId).value = getContent(href, data);
}

function loadSyncroPortletContent(href, id) {
  var contenuto = bodyCleaner(getContent(href));
  //if (obj(id))
  //  obj(id).innerHTML = contenuto;
  $("#"+id).html(contenuto);
}


function executeCommand(command, data) {
  return getContent(contextPath + "/command.jsp?CM=" + command, data);
}


/**
 returns "propname" of persistent object of class "classname" andid "id"
 */
function getPropertyValue(className, id, propName) {
  return executeCommand("GETP", "CN=" + className + "&OBID=" + id + "&PN=" + propName);
}


/**
 returns "varname" object filled with  propertiesToHidrate reading data from persistent object of class "classname" and id "id"
 */
function getObjectHidrated(objToHidrate, className, id, propertiesToHidrate) {
  var META_SEPARATOR = "$~$";
  var props = "";
  var o = objToHidrate;
  // seems silly but eval uses the local name of the variable do no change
  var isFirst = true;
  for (var i = 3; i < arguments.length; i++) {
    if (!isFirst) {
      props = props + META_SEPARATOR;
    } else
      isFirst = false;
    props = props + arguments[i]
  }
  var toEval = executeCommand("RETOB", "CN=" + className + "&OBID=" + id + "&OBN=o&SL=" + props);
  //alert (toEval);
  return eval(toEval)
}



//GENERATE TR VIA AJAX


function getFirstChildWithTagName(node, tagName) {
  var ret = null;
  if (node != null && node.childNodes != null)
    for (var i = 0; i < node.childNodes.length; i++) {
      if (node.childNodes[i].tagName == tagName) {
        ret = node.childNodes[i];
        break;
      }
    }
  return ret;
}

function loadSyncroTRContent(href, tableId, trId, appendTr) {
  var hiddenDiv = document.createElement("DIV");
  hiddenDiv.id = tableId + "_divHid";
  hiddenDiv.style.display = "";
  document.body.appendChild(hiddenDiv);
  loadSyncroContent(href, tableId + "_divHid");
  var focusedTrIndex;
  if (trId)
    focusedTrIndex = obj(trId).rowIndex + 1;

  //                   div       table      tbody      tr
  var table = getFirstChildWithTagName(hiddenDiv, "TABLE");
  var tBody = getFirstChildWithTagName(table, "TBODY");
  var trsNewTable;
  if (tBody == null)
    trsNewTable = table.childNodes;
  else
    trsNewTable = tBody.childNodes;

  for (var i = 0; i < trsNewTable.length; i++) {
    if (trsNewTable[i].nodeType == 1) {
      var trNewTable = trsNewTable[i];
      var newTrId = trNewTable.id;
      var newRow;
      if (trId) {
        focusedTrIndex = focusedTrIndex++;
        newRow = insertRow(tableId, newTrId, focusedTrIndex);
      } else
        newRow = insertRow(tableId, newTrId);
      var tds = trNewTable.childNodes;
      var k = 0;
      for (var j = 0; j < tds.length; j++) {
        if (tds[j].nodeType == 1)
          insertCell(newRow, tds[j], k++);
      }
    }
  }

  if (appendTr == false) {
    tableRemoveLine(trId);
  }
  document.body.removeChild(hiddenDiv);
}

function insertRow(tableId, trId, rowIndex) {
  var table = obj(tableId);
  var newRow = '';
  if (!rowIndex)
    rowIndex = -1;
  newRow = table.insertRow(rowIndex);
  copyAttributes(obj(trId), newRow);
  newRow.id = trId;
  return newRow;
}

function insertCell(newRow, td, position) {
  var text = (td.innerHTML);
  var newCell = newRow.insertCell(position);
  copyAttributes(td, newCell);
  newCell.innerHTML = td.innerHTML;
  // newCell.className=td.className;
}

function copyAttributes(source, dest) {
  for (var att = 0; att < source.attributes.length; att++) {
    var namex = source.attributes[att].name;
    var valuex = source.attributes[att].value;
    // thnx to IExplorer
    if (namex != "id" && namex != "onmousedown" && valuex != null && valuex != "null" && valuex != '' && valuex != 'false') {
      if (namex == "class") dest.className = valuex;
      else dest.setAttribute(namex, valuex);
    }
    //    if (isExplorer && namex=="onmousedown" && valuex!="null") {
    //      //alert(valuex)
    //     //addEvent(dest,"mousedown", valuex));
    //      }
  }
}

// END GENERATE TR VIA AJAX

function bodyCleaner(contenuto) {
  var ret = '';
  if (contenuto) {
    contenuto = contenuto.replace(/<script/g, '<div style="display:none;"');
    contenuto = contenuto.replace(/<\/script/g, '</div');
    contenuto = contenuto.replace('<form', '<disabled');
    contenuto = contenuto.replace('</form', '</disabled');
    contenuto = contenuto.replace(/required/g, 'disabled');
    contenuto = contenuto.replace(/<link/g, '<disabled');
    contenuto = contenuto.replace(/onclick/g, 'disabled');
    contenuto = contenuto.replace(/onClick/g, 'disabled');
    contenuto = contenuto.replace(/onchange/g, 'disabled');
    contenuto = contenuto.replace(/onChange/g, 'disabled');
    contenuto = contenuto.replace(/onkeyup/g, 'disabled');
    contenuto = contenuto.replace(/optgroup/g, 'disabled');
    contenuto = contenuto.replace(/submit/g, 'disabled');
    contenuto = contenuto.replace(/href/g, 'disabled');
    contenuto = contenuto.replace(/input/g, 'input disabled');
    contenuto = contenuto.replace(/pointer/g, 'default');
    contenuto = contenuto.replace(/obj/g, 'disabled');
    contenuto = contenuto.replace(/select/g, ' select disabled');
    contenuto = contenuto.replace(/SELECT/g, 'select disabled');
    //contenuto = contenuto.replace(/document.write/g, '//document.write');
    contenuto = contenuto.replace(/document.write/g, '');
    ret = contenuto;
  }
  return ret;
}

function getI18n(stringToTranslate) {
  return executeCommand("GETI18N", 'I18NENTRY=' + stringToTranslate);
}


// start asynchronous part


/**
 *load obj.innerHtml with content of href asynchronously
 *if objId is null call the href but do not refresh
 */
function loadAsyncroHtml(href, objId, data, callBackFunction) {
  var ajax = getXMLObj();
  ajax.open('POST', href, true);
  ajax.setRequestHeader("connection", "close");
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  ajax.onreadystatechange = function() {
    if (ajax.readyState === 4) {
      window.status = "Ajax loading...";
      if (ajax.status == 200) {
        if (objId)
          $('#' + objId).html(ajax.responseText)
        window.status = "";
        if (callBackFunction) {
          callBackFunction.call();
        }
      } else {
        alert("Error opening:[" + href + "] status:" + ajax.status);
      }
    }
  };
  if (data)
    ajax.send(data);
  else
    ajax.send(null);
}

/**
 *load obj.outerHtml with content of href asynchronously
 *if objId is null call the href but do not refresh
 */
function loadAsyncroContent(href, objId, data, callBackFunction) {
  var ajax = getXMLObj();
  ajax.open('POST', href, true);
  ajax.setRequestHeader("connection", "close");
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  ajax.onreadystatechange = function() {
    if (ajax.readyState === 4) {
      window.status = "Ajax loading...";
      if (ajax.status == 200) {
        if (objId)
          $('#' + objId).replaceWith(ajax.responseText)
        window.status = "";
        if (callBackFunction) {
          //alert('calling callback!'+callBackFunction);
          callBackFunction.call();
        }
      } else {
        alert("Error opening:[" + href + "] status:" + ajax.status);
      }
    }
  };
  if (data)
    ajax.send(data);
  else
    ajax.send(null);
}


function ajaxSubmit(formId, domIdToReload, callBackFunction) {
  loadSyncroContent(obj(formId).action, domIdToReload, getDataFromForm(formId));
  if (callBackFunction)
    callBackFunction();
  //loadAsyncroContent(obj(formId).action, domIdToReload, getDataFromForm(formId), callBackFunction);
}

function getDataFromForm(formId) {
  var f,first,el;
  f = obj(formId);
  var url = '';
  first = true;
  for (var i = 0; i < f.elements.length; i++) {
    el = f.elements[i];
    var value;
    if (el.type == 'radio') {
      //alert(el.name+' '+ el.checked+' '+el.value);
      if (el.checked) {
        value = el.value;
      } else {
        value = null;
      }
    } else {
      value = el.value;
    }
    //Aug 25, 2008 changed by Pietro: empty valued client entries should be sent!
    //if (value != null && value != "") {
    if (value != null) {
      //url = url + (first ? '' : '&') + el.name + '=' + escape(el.value);  // escape() is lesser safe than encodeURIComponent() see: http://xkr.us/articles/javascript/encode-compare/
      url = url + (first ? '' : '&') + el.name + '=' + encodeURIComponent(value);
      first = false;
    }
  }
  return url;
}

function showSavingMessage(){
  $("#SAVINGMESSAGE:hidden").fadeIn();
}
function hideSavingMessage(){
  $("#SAVINGMESSAGE:visible").fadeOut();
}

// END AJAX ----------------------------------------------------------------------------


function removeSmartComboEntry(smartComboName) {
  obj(smartComboName).value = '';
  obj(smartComboName + '_txt').value = '';
}

function setSmartComboEntry(smartComboName, code, descr) {
  obj(smartComboName).value = code;
  obj(smartComboName + '_txt').value = descr;
}


// Table management functions ----------------------------------------------------------------------------
function tableRemoveLine(trId) {
  obj(trId).parentNode.removeChild(obj(trId));
}

// isRequired ----------------------------------------------------------------------------

//return true if every mandatory field is filled and highlight empty ones
jQuery.fn.isFullfilled = function() {
  var canSubmit = true;
  var firstErrorElement = "";

  this.each(function() {
    var theElement = $(this);
    theElement.removeClass("formElementsError");
    if (theElement.val().trim().length == 0 || theElement.attr("invalid") == "true") {
      if (theElement.attr("type") == "hidden") {
        theElement = $("#" + theElement.attr("id") + "_txt");
      }
      theElement.addClass("formElementsError");
      canSubmit = false;
      if (firstErrorElement == "")
        firstErrorElement = theElement;
    }
  });

  if (!canSubmit) {
    // get the tabdiv
    var theTabDiv = firstErrorElement.parents("[isTabSetDiv='true']");
    if (theTabDiv.length > 0)
      hideTabsAndShow(theTabDiv.attr("thisTabId"), theTabDiv.attr("thisTabsetId"));

    // highlight element
    firstErrorElement.effect("highlight", { color: "red" }, 1500);
  }
  return canSubmit;

}



function canSubmitForm(idForm) {
  return $("#" + idForm).find(":input[required=true],:input[invalid=true]").isFullfilled();
}


function addEvent(obj, event_name, func_name) {
  $(obj).bind(event_name,func_name);
}

// Removes an event from the object
function removeEvent(obj, event_name, func_name) {
  $(obj).unbind(event_name,func_name);
}


/*    Caret Functions     */
function setSelection(input, start, end) {
  if (isNetscape) {
    input.setSelectionRange(start, end);
  } else {
    // assumed IE
    var range = input.createTextRange();
    range.collapse(true);
    range.moveStart('character', start);
    range.moveEnd('character', end - start);
    range.select();
  }
  input.focus();
}


function getCaretEnd(obj) {
  obj.focus();
  if (typeof obj.selectionStart != "undefined") {
    return obj.selectionStart;
  } else if (document.selection && document.selection.createRange) {

    var bookmark = document.selection.createRange().getBookmark();
    obj.selection = obj.createTextRange();
    // create in textarea object and
    obj.selection.moveToBookmark(bookmark);
    // match to document.selection
    obj.selectRigth = obj.createTextRange();
    // create textrange object
    obj.selectRigth.collapse(true);
    // for left amount of textarea &
    obj.selectRigth.setEndPoint("EndToStart", obj.selection);
    // align them
    return (obj.selection.text.length + obj.selectRigth.text.length);
  }
}

function setCaret(obj, pos) {
  setSelection(obj, pos, pos);
}

//-- Caret Functions END ---------------------------------------------------------------------------- --

/*    Escape function   */

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

String.prototype.beginsWith = function(t, i) {
  if (!i) {
    return (t == this.substring(0, t.length));
  } else {
    return (t.toLowerCase()== this.substring(0, t.length).toLowerCase());
  }
};

String.prototype.endsWith = function(t, i) {
  if (!i) {
    return (t== this.substring(this.length - t.length));
  } else {
    return (t.toLowerCase() == this.substring(this.length -t.length).toLowerCase());
  }
};

// leaves only char from A to Z, numbers, _ -> valid ID
String.prototype.asId = function () {
  return this.replace(/[^a-zA-Z0-9_]+/g, '');
}
/* --- Escape --- */

/* ----- date format --------- */

var dateFormat = function () {
	var	token = /d{1,4}|M{1,4}|yy(?:yy)?|([HhmsTt])\1?|[LloSZj]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			M = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			m = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			S = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				M:    M + 1,
				MM:   pad(M + 1),
				MMM:  dF.i18n.monthNames[M],
				MMMM: dF.i18n.monthNames[M + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				m:    m,
				mm:   pad(m),
				s:    s,
				ss:   pad(s),
				S:    pad(S, 3),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				j:   "GMT"+ (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60),2) +":" + pad(Math.abs(o) % 60, 2), // gives the GMT+03:00 compatible with java
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd MMM dd yyyy HH:MM:ss",
	shortDate:      "M/d/yy",
	mediumDate:     "MMM d, yyyy",
	longDate:       "MMMM d, yyyy",
	fullDate:       "dddd, MMMM d, yyyy",
	shortTime:      "h:mm TT",
	mediumTime:     "h:mm:ss TT",
	longTime:       "h:mm:ss TT Z",
	isoDate:        "yyyy-MM-dd",
	isoTime:        "hh:mm:ss",
	isoDateTime:    "yyyy-MM-dd'T'hh:mm:ss",
	isoUtcDateTime: "UTC:yyyy-MM-dd'T'hh:mm:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};



/* Types Function */

function isValidURL(url){
  var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
  return RegExp.test(url);
}

function isValidEmail(email){
  var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/;
  return RegExp.test(email);
}

function isNumber (el) {
  var patt = /^-?[0-9]*\\.[0-9]*$/;
  return !isNaN(el.nodeType == 1 ? el.value : el) && ( !patt.test(el));
}

// is a given input a number?
// it doesn't work at all !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function isNumberValue(num, id) {
  var numStr = "-0123456789,.";
  var thisChar;
  var counter = 0;
  if (num == "")
    return false;
  for (var i = 0; i < num.length; i++) {
    thisChar = num.substring(i, i + 1);
    if (numStr.indexOf(thisChar) != -1)
      counter++;
  }
  if (counter == num.length) {
    return true;
  } else {
    alert("Numeric field");
    if (id)
      obj(id).value = '0';
    return false;
  }
}


/* ----- millis format --------- */
/**
* @param         str         - Striga da riempire
* @param         len         - Numero totale di caratteri, comprensivo degli "zeri"
* @param         ch          - Carattere usato per riempire
*/
function pad(str, len, ch){
  if ((str+"").length<len){
    return new Array(len-(''+str).length+1).join(ch) + str;
  } else{
    return str
  }
}

function getMillisInHours(millis) {
  var sgn=millis>=0?1:-1;
  var hour = Math.floor(millis / 3600000);
  return  (sgn>0?"":"-")+pad(hour,2,"0");  
}
function getMillisInHoursMinutes(millis) {
    var sgn=millis>=0?1:-1;
    millis=Math.abs(millis);
    var hour = Math.floor(millis / 3600000);
    var min = Math.floor((millis % 3600000) / 60000);
    return  (sgn>0?"":"-")+pad(hour,2,"0") + ":" + pad(min,2,"0");
}

function getMillisInDaysHoursMinutes(millis) {
    // millisInWorkingDay is set on partHeaderFooter

    var sgn=millis>=0?1:-1;
    millis=Math.abs(millis);
    var days = Math.floor(millis / millisInWorkingDay);
    var hour = Math.floor((millis % millisInWorkingDay) / 3600000);
    var min = Math.floor((millis-days*millisInWorkingDay-hour*3600000) / 60000);
    return (sgn>=0?"":"-")+(days > 0 ? days + "  " : "") + pad(hour,2,"0") + ":" + pad(min,2,"0");
}

function millisFromHourMinute(stingHourMinutes) { //todo does not support 1M2W... syntax
  var result = 0;
  var semiColSeparator = stingHourMinutes.indexOf(":");
  var dotSeparator = stingHourMinutes.indexOf(".");

  if (semiColSeparator < 0 && dotSeparator < 0 && stingHourMinutes.length > 5) {
    return parseInt(stingHourMinutes); //already in millis
  } else {

    if (dotSeparator > -1) {
      var d = parseFloat(stingHourMinutes);
      result = d * 3600000;
    } else {
      var hour = 0;
      var minute = 0;
      if (semiColSeparator == -1)
        hour = parseInt(stingHourMinutes);
      else {
        hour = parseInt(stingHourMinutes.substring(0, semiColSeparator));
        minute = parseInt(stingHourMinutes.substring(semiColSeparator + 1));
      }
      result = hour * 3600000 + minute * 60000;
    }
    if (!result)
      result=0;
    return result;
  }
}


/* Object Functions */

function stopBubble(e) {
  if (isNetscape) {
    e.stopPropagation();
    e.preventDefault();
  }
  if (isExplorer) e = event;
  e.cancelBubble = true;
  e.returnValue = false;
  return false;
}

//validation functions - used by textfield
function validateField(e) {
  var rett=true;
  $('#' + $(this).attr('id') + 'error').remove();
   $(this).removeAttr("invalid").removeClass("formElementsError");
  // check serverside only if not empty
  if ($(this).val()) {
    var ret = executeCommand('validateField', 'entryType=' + $(this).attr('entryType') + '&entryValue=' + $(this).val() + '&fieldId=' + $(this).attr('id'));
    if (ret.trim().length > 0) {
      $(this).after(ret);
      $(this).attr("invalid","true").addClass("formElementsError");
      rett=false;
    }
  }
  return rett;
}

function createErrorAlert (fieldId,errorCode,message,errorImagePath){
  if (!obj(fieldId + "error")){
    var err="<span id=\"" + fieldId + "error\" error='1'>&nbsp;";
    var errMess=errorCode + ": " + message;
    err+="<img height='17' width='17' onclick=\"alert($(this).attr('tooltip'))\" border='0' align='absmiddle' tooltip=\""+errorCode+"\" src=\""+ errorImagePath+"\">";
    err+="</span>\n";
    $("#"+fieldId).after(err);
  }
}


var __feedbackMessageTemplates=new Object();

function fillFeedbackMessageTemplates() {
  $.get(contextPath + "/commons/layout/feedbackFromController/ajaxFeedbackDrawer.jsp", function(data) {
    var tmp = $("<div>");
    tmp.html(data);
    tmp.find("div.ffcWrapper").each(function(){
      var ffc=$(this);
      __feedbackMessageTemplates[ffc.children().attr("type")]=ffc.html();
      ffc.remove();
    });
    tmp.remove();
  });
}

function showFeedbackMessage(type, message){
  var indo=$("#__FEEDBACKBOX");
  if (indo.size()>0){
    //get template and substitute
    var ffc = __feedbackMessageTemplates[type]; // recover template
    ffc=ffc.replace(new RegExp("##message##","gi"),message);
    indo.append(ffc);
    $("#__FEEDBACKBOX:hidden").fadeIn();
    $("body").oneTime(3000,function(){$(".FFC_OK").slideUp();});
  } else{
    alert ("DOM element '__FEEDBACKBOX' is missing. Add it on screen.");
  }
}

// fade in fade out functions START ------------------  uses "opac" attribute in the objet to be faded --
//deprecated ----- use jquery functions (fadeIn(), fadeOut(), etc. instad
function setOpac(subj, opac) {
  $("#"+subj).css({opacity:opac / 100})
}
function fadeIn(objId, delayInMillis, step, op) {
  $("#"+objId).fadeIn(delayInMillis/step);
}
function fadeOut(objId, delayInMillis, step) {
  $("#"+objId).fadeOut(delayInMillis/step);
}

// button submit support BEGIN ------------------

function saveFormValues(idForm) {
  var formx = obj(idForm);
  formx.setAttribute("savedAction", formx.action);
  formx.setAttribute("savedTarget", formx.target);
  var el = formx.elements;
  for (i = 0; i < el.length; i++) {
    if (el[i].getAttribute("savedValue") != null) {
      el[i].setAttribute("savedValue", el[i].value);
    }
  }
}

function restoreFormValues(idForm) {
  var formx = obj(idForm);
  formx.action = formx.getAttribute("savedAction");
  formx.target = formx.getAttribute("savedTarget");
  var el = formx.elements;
  for (i = 0; i < el.length; i++) {
    if (el[i].getAttribute("savedValue") != null) {
      el[i].value = el[i].getAttribute("savedValue");
    }
  }
}
// button submit support END ------------------


// textarea limit size -------------------------------------------------
function limitSize(ob) {
  if (ob.getAttribute("maxlength")) {
    var ml = ob.getAttribute("maxlength");
    if (ob.value.length > ml) {
      ob.value = ob.value.substr(0, ml);
      alert(getI18n("ERR_FIELD_MAX_SIZE_EXCEEDED") + ":" + ml);
    }
  }
}

// verify before unload BEGIN ----------------------------------------------------------------------------
function alertOnUnload() {
  if (!muteAlertOnChange) {
    for (var i = 0; i < document.forms.length; i++) {
      var currForm = document.forms[i];
      if ('true' == '' + currForm.getAttribute('alertOnChange')) {
        for (var j = 0; j < currForm.elements.length; j++) {
          var anInput = currForm.elements[j];
          if (!('true' == '' + anInput.getAttribute('excludeFromAlert')) && "" + anInput.getAttribute('oldValue') == "1") {
            var oldValue = (__oldValues__[anInput.id] + "").trim();
            if ($(anInput).attr("maleficoTiny")) {
              if (tinymce.EditorManager.get($(anInput).attr("id")).isDirty()) {
                //alert("isDirty:" + tinymce.EditorManager.get($(anInput).attr("id")).isDirty());
                if (isExplorer) {
                  event.returnValue = getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
                } else {
                  return getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
                }
              }

            } else  if ($(anInput).val().trim() != oldValue) {
              //alert("name:"+anInput.name+" id:"+anInput.id+" ov:" + oldValue + "\nnv:" + $(anInput).val().trim());
              if (isExplorer) {
                event.returnValue = getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
              } else {
                return getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
              }
            }
          }
        }
      }
    }
  }
}

// verify before unload END ----------------------------------------------------------------------------

// ---------------------------------- oldvalues management
var __oldValues__= new Object();


// update all values selected
jQuery.fn.updateOldValue= function(){
  this.each(function(){
    var el = $(this);
    var id = el.attr("name");
    if (!id)
      id=el.attr("id");
    if (id!="")    {
      __oldValues__[id] = el.val();
    }
  });
  return this;
}

// return true if at least one element has changed
jQuery.fn.isValueChanged=function (){
  var ret=false;
  this.each(function(){
    var el = $(this);
    var id = el.attr("name");
    if (!id)
      id=el.attr("id");
    if (id && el.val()+"" != __oldValues__[id] + ""){
      ret=true;
      return false;
    }
  });
  return ret;
}

jQuery.fn.getOldValue=function(){
  var id = $(this).attr("name");
  if (!id)
    id=$(this).attr("id");
  if (id)
    return __oldValues__[id]+"";
  else
    return undefined;
}

// ------ ------- -------- wraps http://www.mysite.com/.......   with <a href="...">
jQuery.fn.activateLinks = function (showImages) {
  var httpRE = /(['"]\s*)?(http[s]?:[\d]*\/\/[^"<>\s]*)/g;
  var wwwRE = /(['"/]\s*)?(www.[^"<>\s]*)/g;
  var imgRE = /(['"]\s*)?(http[s]?:[\d]*\/\/[^"<>\s]*\.(?:gif|jpg|png|jpeg|bmp))/g;


  this.each(function() {
    var el = $(this);
    var html = el.html();

    // workaround for negative look ahead
    html = html.replace(imgRE, function($0, $1) {
      return $1 ? $0 : "<div class='imgWrap'><a href='" + $0 + "' target='_blank'><img src='" + $0 + "'></a></div>";
    });

    html = html.replace(httpRE, function($0, $1) {
      return $1 ? $0 : "<a href='" + $0 + "' target='_blank'>" + $0 + "</a>";
    });

    html = html.replace(wwwRE, function($0, $1) {
      return $1 ? $0 : "<a href='http://" + $0 + "' target='_blank'>" + $0 + "</a>";
    });


    el.html(html);

  });
  return this;
}

jQuery.fn.emoticonize = function () {
  function convert(text) {
    var faccRE = /(:\))|(:-\))|(:-])|(:-\()|(:\()|(:-\/)|(:-\\)|(:-\|)|(;-\))|(:-D)|(:-P)|(:-p)|(:-0)|(:-o)|(:-O)|(:'-\()|(\(@\))/g;
    return text.replace(faccRE, function(str) {
      var ret = {":)": "smile",
        ":-)": "smile",
        ":-]": "polite_smile",
        ":-(": "frown",
        ":(": "frown",
        ":-/": "skepticism",
        ":-\\": "skepticism",
        ":-|": "sarcasm",
        ";-)": "wink",
        ":-D": "grin",
        ":-P": "tongue",
        ":-p": "tongue",
        ":-o": "surprise",
        ":-O": "surprise",
        ":-0": "surprise",
        ":'-(": "tear",
        "(@)": "angry"}[str];
      if (ret) {
        ret = "<img src='" + imgCommonPath + "smiley/" + ret + ".png' align='absmiddle'>";
        return ret;
      } else
        return str;
    });
  } ;

  this.each(function() {
    var el = $(this);
    var html = convert(el.html());
    el.html(html);
  });
  return this;
}

// ---------------------------------- initialize management
var __initedComponents= new Object();

function initialize(url,includeAsScript){
  var normUrl=url.asId();
  if (!__initedComponents[normUrl]){
    if (!includeAsScript){
      //console.debug(url+" as DOM");
      //var text = getContent(url);
      url= url + (url.indexOf("?")>-1?"&":"?")+buildNumber;
      var text =  $.ajax({
          type:"GET",
          url: url,
          async:false,
          dataType:"html",
          cache:true
         }).responseText;
      $("body").before(text);
    } else{
      $.ajax({type: "GET",
              url: url+"?"+buildNumber,
              dataType: "script",
              async:false,
              cache:true});
    }
    __initedComponents[normUrl]="1";
  }
}

/*
// centralized onload system
*/

var setStart, setDrop, setInitTree, setInitSizeTree, setResize;

$(document).ready(function() {

    if (setDrop == true) dropInit();
    if (setInitTree == true) inittree();
    $(document).bind("mousemove", getMouseXY);

      window.onbeforeunload = alertOnUnload;
    //again because... something does not work.. RB and MB don't remember..



  $("input[innerLabel][value='']:visible").each(function (i) {
    var theField = $(this);
    //Pietro&Bicocchs 10March2009: was "wrap" but with jquery 1.3.2. wrap eats all contents :-(
    //before:  theField.wrap("<span id='lbdv_" + this.id + "' class='innerLabel' >" + theField.attr("innerLabel") + "</span>");
    theField.wrap("<span style='position:relative;'></span>");
    theField.after("<span id='lbdv_" + this.id + "' class='innerLabel' style='position:absolute;top:-3;left:0;'>" + theField.attr("innerLabel") + "</span>");
    var theSpan = $("#lbdv_" + this.id);
    theSpan.width(theField.outerWidth()).height(theField.outerHeight()).bind('click', function() {
      theField.focus()
    });
    theField.bind('focus', function(e) {
      theSpan.fadeOut(50);
    }).bind('blur', function() {
      if ($(this).val() == "") {
        theSpan.fadeIn()
      }
    })
  });

  var updateOldValues=function (){
    $(this).updateOldValue();  //todo inglobarlo nell'unica chiamata di livequery
  }

  $(":input[oldValue]").livequery(updateOldValues);

  $('.validated').livequery('blur', validateField);


  $("img[roll]").live("mouseover", function(e) {var arr=$(this).attr('src').split("."); arr[0]=arr[0]+"Over."+arr[1]; $(this).attr('src',arr[0]);} );
  $("img[roll]").live("mouseout", function(e) { $(this).attr('src',$(this).attr('src').replace("Over.",".")); });


  if (!isExplorer)
    $("tr[rl=1]").livequery("mouseover", function(){ $(this).addClass("trOver").one("mouseout",function(){$(this).removeClass("trOver")})});

  //set default jquery ajax encoding
  $.ajaxSetup({
    contentType:"application/x-www-form-urlencoded; charset=UTF-8"
  });

})

// ---------------------------------- tinyMCE ajax reloader
function tinyMCEReloader(absolutePath, elID, data) {
  var ed = tinyMCE.get(elID);
  // window.setTimeout fakes ajax call
  ed.setProgressState(1); // Show progress
  window.setTimeout(function() {
    ed.setProgressState(0); // Hide progress
    ed.setContent(getContent(absolutePath, data));
  }, 1000);
}
