
//browser detection

if (navigator.appName == "Netscape")var isNetscape = true;
if (navigator.appName == "Microsoft Internet Explorer") var isExplorer = true;
if (window.opera) var isOpera = true;
if (navigator.userAgent.toLowerCase().indexOf("safari") != -1) var isSafari=true;

//OS detection
if (navigator.appVersion.indexOf("Win") != -1) var isWin = true;
if (navigator.appVersion.indexOf("Mac") != -1) var isMac = true;
if (navigator.appVersion.indexOf("X11") != -1) var isUnix = true;
if (navigator.appVersion.indexOf("Linux") != -1) var isLinux = true;

//Version detection
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);
var version = navigator.appVersion.substring(0, 1);

//windowDimensionDetection
var winWidth,winHeight;

function obj(objId) {
  return document.getElementById(objId);
}

function createEl(theEl) {
  return document.createElement(theEl);
}

function selectAllCheckBoxes(formId) {
  var f = obj(formId);
  for (var k = 0; k < f.elements.length; k++) {
    var e = f.elements[k];
    if (e.type.toLowerCase() == 'checkbox')
      e.checked = 'true';
  }
}

/*
function getWindowDimensionH() {
  if (isNetscape) {
    winHeight = top.window.innerHeight;
  }
  if (isExplorer) {
    winHeight = document.documentElement.offsetHeight;
  }
  return winHeight;
}

function getWindowDimensionW() {
  if (isNetscape) {
    winWidth = top.window.innerWidth;
  }
  if (isExplorer) {
    winWidth = document.documentElement.offsetWidth-20;
  }
  return winWidth;
}
*/
function getWindowDimensionH() {
  return $(window).height();
}

function getWindowDimensionW() {
  return $(window).width();
}


function sendWindowResizeMessage() {
  obj("commander").src = contextPath + "/command.jsp?CM=UPDATEWINSIZE&PAGE_HEIGHT=" + getWindowDimensionH() + "&PAGE_WIDTH=" + getWindowDimensionW();
}

function truebody(){
  return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function getEvent(){
  return window.event;
}

//mouse position detection
if (!isExplorer) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;
var mouseX = 0;
var mouseY = 0;
function getMouseXY(e) {
  if (isExplorer) {
    mouseX = event.clientX + truebody().scrollLeft;
    mouseY = event.clientY + truebody().scrollTop;
  } else {
    mouseX = e.pageX;
    mouseY = e.pageY;
  }
  if (mouseX < 0) {
    mouseX = 0;
  }
  if (mouseY < 0) {
    mouseY = 0;
  }
  return true;
}

function showHideDiv(divId) {
  if (obj(divId))
    if (obj(divId).style.visibility == 'hidden') {
      obj(divId).style.visibility = 'visible';
    } else {
      obj(divId).style.visibility = 'hidden';
    }
}

// return true when set to visible
function showHideSpan(spanId, callback) {
  var span = $('#' + spanId);
  var visibility;
  if (span.css("display") == 'none') {
    span.fadeIn(500, function() {
      if(typeof callback=="function")
        callback();
      }
    );
    visibility = true;
  } else {
    span.fadeOut(500, function() {
      if(typeof callback=="function")
        callback();
      }
    );
    visibility = false;
  }
     
  return visibility;
}

function showHide(id) {
  if (obj(id))
    if (obj(id).style.display == 'none') {
      obj(id).style.display = 'block';
    } else {
      obj(id).style.display = 'none';
    }
}

function displayDiv(divId) {
  if (obj(divId))
    obj(divId).style.display = '';
  var i=0;
}

function displayNoneDiv(divId) {
  if (obj(divId))
    obj(divId).style.display = 'none';
}

function hideDiv(divId) {
  if (obj(divId))
    obj(divId).style.visibility = 'hidden';
}

function showDiv(divId) {
  if (obj(divId))
    obj(divId).style.visibility = 'visible';
}

function centerPopup(url, nome, w, h, scroll, resiz) {
  var winl = (screen.width - w) / 2;
  var wint = (screen.height - h) / 2;
  if(!resiz)
    resiz=true;
  winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable='+resiz+', toolbars=false, status=false, menubar=false';
  //alert (winprops);
  win = window.open(url, nome, winprops)
  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;
  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 (parseInt(navigator.appVersion) >= 4) {
    win.window.focus();
  }
}

//----------------------------------positioning------------------------------------------------------
// to determinate 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 determinate the real y position of the element
function getAbsoluteTop(el) {
  if (el){
    yPos = el.offsetTop;
    tempEl = el.offsetParent;
    while (tempEl != null) {
      yPos += tempEl.offsetTop;
      tempEl = tempEl.offsetParent;
    }
    return yPos;
  }
}

function getAbsoluteLeftWin(el) {
  if (isExplorer)
    xPos = window.screenLeft + getAbsoluteLeft(el);
  else
    xPos = window.screenX + getAbsoluteLeft(el);
  return xPos;
}

function getAbsoluteTopWin(el) {
  if (isExplorer)
    yPos = window.screenTop + getAbsoluteTop(el);
  else
    yPos = window.screenY + getAbsoluteTop(el);
  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 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())) {
      var t = (el.offsetHeight + target.offsetHeight);
      // valore azzerato per visualizzare il calendar nel front-end
      t = 0;
      target.style.marginTop = (-(t)) + "px";
    }
    target.style.visibility = "visible";
  }
}

function centerObject(objId) {
  if (obj(objId)) {
    var theObject = $("#"+objId);

    theObject.css({
      position:"absolute",
      top:$(window).scrollTop()+($(window).height()  - parseFloat(theObject.outerHeight())) / 2,
      left:$(window).scrollLeft()+($(window).width() - parseFloat(theObject.outerWidth())) / 2
    });
  }
}

/*
function positionIt(where, theObj) {
  var el = document.all ? document.all(where) : obj ? obj(where) : null;
  var target = document.all ? document.all(theObj) : obj ? obj(theObj) : null;
  if (el) {
    trueX = getAbsoluteLeft(el);
    //trueX += distanceX;
    trueY = getAbsoluteTop(el);
    var h = el.offsetHeight;
    elHeight = parseFloat(h);
    trueY += parseFloat(elHeight); //+ distanceY;
    target.style.left = trueX;
    target.style.top = trueY;
  }
}
 */
//END positioning

function fadeIn(objId,opac,speed){
  if (!speed) speed=100;
  subj=obj(objId);
  //opac=parseInt(subj.getAttribute("opac"));
  if (opac<100){
    opac=opac+speed;
    //subj.setAttribute("opac",opac)
    //distinguere moz da ie
    if (isExplorer)
      subj.style.filter="alpha(opacity="+opac+")";
    else
      subj.style.opacity=opac/100;
    setTimeout("fadeIn('"+objId+"',"+opac+", "+speed+")", 1)
  }
}

function fadeOut(objId,opac,speed){
  if (!speed) speed=100;
  subj=obj(objId);
  //opac=parseInt(subj.getAttribute("opac"));
  if (opac>0){
    opac=opac-speed;
    //subj.setAttribute("opac",opac)
    //distinguere moz da ie
    if (isExplorer)
      subj.style.filter="alpha(opacity="+opac+")";
    else
      subj.style.opacity=opac/100;
    setTimeout("fadeOut('"+objId+"',"+opac+", "+speed+")", 1)
  }
}

// event handling START -------------------------------

function getTarget(e) {
  if (isExplorer) {
    return e.srcElement;
  }
  if (isNetscape) {
    return e.target;
  }
}

function getKeyCode(e) {
  if (isExplorer) {
    return e.keyCode;
  }
  if (isNetscape) {
    return e.which;
  }
}

function stopBubble(e) {
  if (isNetscape)
    e.stopPropagation();
  e.cancelBubble = true;
  return false;
}
// event handling END -------------------------------


//START AJAX --
//var xmlHttpRequestObject;
function getXMLObj() {
  //if (xmlHttpRequestObject) {
  //  return xmlHttpRequestObject;
  //} else {
  // branch for native XMLHttpRequest object
  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;
      }
    }
  }
  //xmlHttpRequestObject = req;
  return req;
  //}
}

function getContent(href, data) {
  // in order to avoid caching on IE
  if (href.indexOf("?") < 0)
    href = href + "?";
  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(null);
    req.send('');
  }

  if (req.status == 200) {
    ret = req.responseText;
    //setTimeout("hideLoading()", 800);
    return ret;

    // 404 url not found -
  } else if(req.status == 404) {
    return 'File not found';

    // 500 internal server error
  } else if (req.status == 500 ) {
    //setTimeout("hideLoading()", 800);
    //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) {
  obj(objId).value = getContent(href);
}

function loadSyncroPortletContent(href, objId) {
  var ext = getFileExtension(href);
  var contenuto = replacePortletPreviewContent(href)
  obj(objId).innerHTML = contenuto;
}

function replacePortletPreviewContent(href) {
  var contenuto = getContent(href);
  contenuto = bodyCleaner (contenuto);
  return contenuto;
}

function replaceTemplatePreviewContent(divId) {
  var contenuto = obj(divId).innerHTML;
  contenuto = bodyCleaner (contenuto);
  obj(divId).innerHTML = contenuto;
}

function bodyCleaner (contenuto) {
  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');
  return contenuto;
}

function getI18n(stringToTranslate){
  var url = contextPath+'/applications/webwork/js/i18n_js.jsp';
  return getContent(url,'I18NENTRY='+stringToTranslate);
}

function  getFileExtension(stringa){
  var ext;
  ext = stringa.substring( stringa.length, stringa.lastIndexOf(".")+1 );
  return ext;
}

function fileExtentionInspector(ext) {
  var ok = ( ext=="jpg" || ext=="JPG" || ext=="gif" || ext=="GIF" || ext=="png" || ext=="PNG" || ext=="jpeg" || ext=="JPEG" );
  return ok;
}

// start asynchronous part
/*
 function loadAsyncroContent(href, objId,data) {
 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)
 //obj(objId).outerHTML = req.responseText;
 $('#' + objId).replaceWith(ajax.responseText);
 window.status = "";
 } else {
 alert("Error opening:[" + href + "] status:" + ajax.status);
 }
 }
 };
 if (data)
 ajax.send(data);
 else
 ajax.send(null);
 }

 function ajaxSubmit(formId, domIdToReload){
 var f;
 f=obj(formId);
 var url='';
 first=true;
 for (i=0;i<f.elements.length;i++){
 el=f.elements[i];
 if (el.value !=null && el.value!="")
 url=url+(first ? '' : '&')+el.name+'='+escape(el.value);
 first=false;
 }
 url=f.action+"?"+url;
 loadAsyncroContent (url,domIdToReload);
 }
 */
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) {
          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 reloadPageAfterAjaxSubmit (formId, logOutUrl) {
  var f;
  f=obj(formId);
  var url="";
  first=true;
  var actualUrl=self.location.href;

  var parametersInUrl = false;
  if (actualUrl.indexOf('?')>-1) {
    parametersInUrl = true;
  }

  var byPassParameter='';
  var firstParam = true;
  for (i=0;i<f.elements.length;i++) {
    el=f.elements[i];
    if (el.value !=null && el.value!=""){
      url=url+(first ? '' : '&')+el.name+'='+escape(el.value);
      // to intercept invalid login in CDC wp_login
      var priorUlr = self.location.href;
      if(priorUlr.indexOf("INVALIDLG")==-1 && ( el.value.indexOf('LG')>-1 || el.name.indexOf('FLD_LOGIN_NAME')>-1) ) {
        if(el.value.indexOf('LG')>-1) {
          byPassParameter = byPassParameter + (firstParam && !parametersInUrl ? '?' : '&' ) + 'INVALIDLG='+el.value;
        }
        firstParam = false;
      }
    }
    first=false;
  }

  if (!parametersInUrl) {
    // teoros changed december 2008
    //url=f.action +"?"+url;
    url=f.action + (f.action.indexOf('?')>-1 ? '&' : '?' ) + url;
  } else {
    url=f.action+"&"+url;
  }

  // in case of user with empty pwd the ce must be created or the md5 in Operator.authenticateUser will fail (null is different from empty string)
  if(url.indexOf('FLD_PWD')==-1) {
    url = url + "&FLD_PWD=";
  }

  // url params cleaning
  if(url.indexOf("?&"))
    url = url.replace("?&", "?");

  // thanx to IE cache management
  url = url+"&ts="+Math.random();

  ajax = getXMLObj();
  ajax.open('GET', url, true);
  ajax.setRequestHeader("connection", "close");
  ajax.onreadystatechange =
      function() {
        if(ajax.readyState === 4) {
          window.status ="Ajax loading...";
          if(ajax.status == 200){
            self.location.href = (logOutUrl ? logOutUrl : self.location.href ) + byPassParameter;
            // receptronics
            //self.location.href = url;
            // cdc //self.location.href = self.location.href + byPassParameter;
            window.status ="";
          } else{
            alert("Error opening:[" + href+"] status:"+ajax.status);
          }
        }
      };
  ajax.send(null);
}

// missing firefox function emulation

function emulateHTMLModel() {
  HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
    var r = this.ownerDocument.createRange();
    r.setStartBefore(this);
    var df = r.createContextualFragment(sHTML);
    this.parentNode.replaceChild(df, this);

    return sHTML;
  });

  HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {
    switch (this.tagName) {
      case "AREA":
      case "BASE":
      case "BASEFONT":
      case "COL":
      case "FRAME":
      case "HR":
      case "IMG":
      case "BR":
      case "INPUT":
      case "ISINDEX":
      case "LINK":
      case "META":
      case "PARAM":
        return false;
    }
    return true;
  });

  HTMLElement.prototype.__defineGetter__("outerHTML", function () {
    var attr, attrs = this.attributes;
    var str = "<" + this.tagName;
    for (var i = 0; i < attrs.length; i++) {
      attr = attrs[i];
      if (attr.specified)
        str += " " + attr.name + '="' + attr.value + '"';
    }
    if (!this.canHaveChildren)
      return str + ">";

    return str + ">" + this.innerHTML + "</" + this.tagName + ">";
  });
}

// END AJAX ----------------------------------------------------------------------------

// END xmlHttpRequestObject -------------------------------------------



// debugger ----------------------------------------------------------------------------

var debugPopup;
var str = "";
function scriptDebugger() {
  str = str + "<br>";
  for (i = 0; i < arguments.length; i++) {
    str += arguments[i] + "<br>-------------------------------------------------------------<br>";
  }
  if (!debugPopup)
    debugPopup = window.open("", "debugWin", "width=300,height=200,resizable"); // a window object
  debugPopup.document.open("text/html", "replace");
  debugPopup.document.write("<HTML><HEAD><TITLE>New Document</TITLE></HEAD><BODY>" + str + "</BODY></HTML>");
  debugPopup.document.close();
}

// isRequired ----------------------------------------------------------------------------

function findTab(theEl){
  while ((theEl.getAttribute('isTabSetDiv')!="true")) {
    if(theEl.nodeName=='BODY') return "";
    theEl =isNetscape ? theEl.parentNode: theEl.parentElement;
  }
  return theEl.id;
}

/*
var theRequiredTabset="";
var theOldtabSelId;
var allDiv;
function canSubmitForm(idForm) {
  var canSubmit=true;
  //var alertMessage=""
  elementsq= obj(idForm).elements.length;
  for (h=0;h<=elementsq; h++){
    theElement= obj(idForm).elements[h];
    if (theElement && theElement.className=="formElementsError")
      theElement.className="formElements";
    if (theElement && (theElement.value=="" || theElement.value.length==0) && theElement.getAttribute('required')=="true" && theElement.type!="hidden"){
      theElement.className="formElementsError";
      //alertMessage+= theElement.name +'\n';
      canSubmit=false;
      if (theRequiredTabset=="")
        theRequiredTabset=findTab(theElement);
    }
  }
  if (canSubmit==false)  {
    if (theRequiredTabset!=""){
      theSuffix="div_tabset_";
      therequiredTabLinkId=theRequiredTabset.substring(theSuffix.length, theRequiredTabset.length);
      allTabLabel= document.getElementsByTagName('TD');
      if (allTabLabel.length>0){
        for (i=0;i<=allTabLabel.length;i++){
          if (allTabLabel[i] && allTabLabel[i].className=="tabSelected"){
            allTabLabel[i].className="tabUnselected";
          }
        }
      }
      obj(therequiredTabLinkId).className="tabSelected";
      if(obj(theOldtabSelId)) obj(theOldtabSelId).className="tabUnselected";
      allDiv= document.getElementsByTagName('DIV');
      if (allDiv.length>0){
        for (i=0;i<=allDiv.length;i++){
          if (allDiv[i] && allDiv[i].id!=theRequiredTabset && allDiv[i].getAttribute('isTabSetDiv')=="true") allDiv[i].style.display="none";
          obj(theRequiredTabset).style.display="";
        }
      }
      theRequiredTabset=""
    }
  }
  return canSubmit;
}
*/
function canSubmitForm(idForm) {
  var canSubmit = true;
  var firstErrorElement = "";
  var inputs =  $("#" + idForm).find(":input[required=true]").each(function() {
    var theElement = $(this);
    theElement.removeClass("formElementsError");
    if (theElement.val().trim().length == 0) {
      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;
}

var muteAlertOnChange=false;

function alertOnUnload() {
  if (!muteAlertOnChange) {
    for (i=0; i<document.forms.length; i++) {
      var currForm = document.forms[i];
      if ('true'==''+currForm.getAttribute('alertOnChange')) {
        for (j=0; j<currForm.elements.length; j++) {
          anInput = currForm.elements[j];
          oldValue = anInput.getAttribute("oldValue");
          if (anInput.attributes.getNamedItem("oldValue") && (anInput.value.replace(/\r/g,"")!=oldValue.replace(/\r/g,"")))
            if (isExplorer)
              event.returnValue = "You have some unsaved data on the page!";
            else {
              return "You have some unsaved data on the page!";
            }
        }
      }
    }
  }
}

if (!isExplorer) {
  window.onbeforeunload = alertOnUnload;
}

function addEvent(obj,event_name,func_name){
  if (obj.attachEvent){
    obj.attachEvent("on"+event_name, func_name);
  }else if(obj.addEventListener){
    obj.addEventListener(event_name,func_name,true);
  }else{
    obj["on"+event_name] = func_name;
  }
}

// Removes an event from the object
function removeEvent(obj,event_name,func_name){
  if (obj.detachEvent){
    obj.detachEvent("on"+event_name,func_name);
  }else if(obj.removeEventListener){
    obj.removeEventListener(event_name,func_name,true);
  }else{
    obj["on"+event_name] = null;
  }
}

// Stop an event from bubbling up the event DOM
function stopEvent(evt){
  evt || window.event;
  if (evt.stopPropagation){
    evt.stopPropagation();
    evt.preventDefault();
  }else if(typeof evt.cancelBubble != "undefined"){
    evt.cancelBubble = true;
    evt.returnValue = false;
  }
  return false;
}

// Get the obj that starts the event
function getElement(evt){
  if (window.event){
    return window.event.srcElement;
  }else{
    return evt.currentTarget;
  }
}
// Get the obj that triggers off the event
function getTargetElement(evt){
  if (window.event){
    return window.event.srcElement;
  }else{
    return evt.target;
  }
}
// For IE only, stops the obj from being selected
function stopSelect(obj){
  if (typeof obj.onselectstart != 'undefined'){
    addEvent(obj,"selectstart",function(){ return false;});
  }
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function getCaretEnd(obj){
  if(typeof obj.selectionEnd != "undefined"){
    return obj.selectionEnd;
  }else if(document.selection&&document.selection.createRange){
    var M=document.selection.createRange();
    var Lp=obj.createTextRange();
    Lp.setEndPoint("EndToEnd",M);
    var rb=Lp.text.length;
    if(rb>obj.value.length){
      return -1;
    }
    return rb;
  }
}
// Get the start position of the caret in the object
function getCaretStart(obj){
  if(typeof obj.selectionStart != "undefined"){
    return obj.selectionStart;
  }else if(document.selection&&document.selection.createRange){
    var M=document.selection.createRange();
    var Lp=obj.createTextRange();
    Lp.setEndPoint("EndToStart",M);
    var rb=Lp.text.length;
    if(rb>obj.value.length){
      return -1;
    }
    return rb;
  }
}
// sets the caret position to l in the object
function setCaret(obj,l){
  obj.focus();
  if (obj.setSelectionRange){
    obj.setSelectionRange(l,l);
  }else if(obj.createTextRange){
    m = obj.createTextRange();
    m.moveStart('character',l);
    m.collapse();
    m.select();
  }
}
// sets the caret selection from s to e in the object
function setSelection(obj,s,e){
  obj.focus();
  if (obj.setSelectionRange){
    obj.setSelectionRange(s,e);
  }else if(obj.createTextRange){
    m = obj.createTextRange();
    m.moveStart('character',s);
    m.moveEnd('character',e);
    m.select();
  }
}

/*    Escape function   */
String.prototype.addslashes = function(){
  return this.replace(/(["\\\.\|\[\]\^\*\+\?$\(\)])/g, '\$1');
}
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());
  }
};
/* --- Escape --- */

/* Offset position from top of the screen */
function curTop(obj){
  toreturn = 0;
  while(obj){
    toreturn += obj.offsetTop;
    obj = obj.offsetParent;
  }
  return toreturn;
}
function curLeft(obj){
  toreturn = 0;
  while(obj){
    toreturn += obj.offsetLeft;
    obj = obj.offsetParent;
  }
  return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function isNumber(a) {
  return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function replaceHTML(obj,text){
  while(el == obj.childNodes[0]){
    obj.removeChild(el);
  };
  obj.appendChild(document.createTextNode(text));
}

function addToFavorites(favoriteTitle){
  if(!favoriteTitle)favoriteTitle=document.title;
  if( window.sidebar && window.sidebar.addPanel ) {
    //Gecko (Netscape 6 etc.) - add to Sidebar
    window.sidebar.addPanel( favoriteTitle ? favoriteTitle:document.title, document.location.href, '' );
  } else if( window.external && ( navigator.platform == 'Win32' ||
      ( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 ) ) ) {
    //IE Win32 or iCab - checking for AddFavorite produces errors in
    //IE for no good reason, so I use a platform and browser detect.
    //adds the current page page as a favourite; if this is unwanted,
    //simply write the desired page in here instead of 'location.href'
    window.external.AddFavorite( location.href, favoriteTitle ? favoriteTitle:document.title );
  } else if( window.opera && window.print ) {
    //Opera 6+ - add as sidebar panel to Hotlist
    return true;
  } else if( document.layers ) {
    //NS4 & Escape - tell them how to add a bookmark quickly (adds current page,
    //not target page)
    window.alert( 'Please click OK then press Ctrl+D to create a bookmark' );
  } else {
    //other browsers - tell them to add a bookmark (adds current page, not target page)
    window.alert( 'Please use your browser\'s bookmarking facility to create a bookmark' );
  }
  return false;
}


// VIDEO MANAGE
function showMovie(theMovie,title, autostart, pageOrContainerId, width, height, popupWidth, popupHeight, params){
  if (!autostart)
    autostart=false;
  if (!width)
    width=480;
  if (!height)
    height=360;

  if (pageOrContainerId && (pageOrContainerId.indexOf("/")>-1 || 'popup'==pageOrContainerId.toLowerCase())) {
    // default
    if('popup'==pageOrContainerId.toLowerCase())
      pageOrContainerId = contextPath+"/applications/webwork/rss/showMultimedia.jsp?"+params;

    if (!popupWidth)
      popupWidth=width;
    if (!popupHeight)
      popupHeight=height;

    centerPopup(pageOrContainerId,"moviePlayer", popupWidth, popupHeight, 'no', 'no' );

  } else {
    var image = theMovie.replace('.flv', '.jpg');
    // non apre popup (era la funzione flvPlayer eliminata)
    var videoContent ="";
    videoContent +='<object type="application/x-shockwave-flash" data="'+contextPath+'/commons/layout/multimedia/flv/mediaplayer.swf?image='+image+'&autostart='+autostart+'&file='+theMovie+'" width="'+width+'" height="'+height+'" wmode="transparent">';
    videoContent +='<param name="movie" value="'+contextPath+'/commons/layout/multimedia/flv/mediaplayer.swf?image='+image+'&autostart='+autostart+'&file='+theMovie+'" width="'+width+'" height="'+height+'"/>';
    videoContent +='<param name="wmode" value="transparent" />';
    videoContent +='<param name="allowfullscreen" value="true" />';
    videoContent +='</object>';
    obj(pageOrContainerId).innerHTML = videoContent;
  }
}


/*
 // PRINT START
 */
function stampa(relativePathToCss, printableTagId, siteHeader, urlLogo) {
  /*var testo = "<html><head>" + relativePathToCss + "</head>";*/
  var testo = "<html><head>" + relativePathToCss;
  testo += "<script type='text/javascript' src='"+contextPath+"/applications/webwork/js/jquery/jquery.js'></script>";
  testo += "<script type='text/javascript' src='"+contextPath+"/applications/webwork/js/webwork.js'></script>";
  testo += "</head>";
  testo += "<body id=\"fo\" class=\"print\">"
  var drawSiteHeader = (siteHeader && siteHeader!=null && siteHeader!='null');
  var drawUrlLogo = (urlLogo && urlLogo!=null && urlLogo!='null');
  testo+="<div style=\"background-color:white; padding:3px;\">";
  if ( drawSiteHeader || drawUrlLogo ) {
    testo += "<table><tr><td>";
    if(drawUrlLogo)
      testo += "<img src='"+urlLogo+"'><br><br>";
    if(drawSiteHeader)
      testo += "<h7>" + siteHeader + "</h7>";
    testo += "</td></tr></table>";
  }

  if (isExplorer)
    testo += obj(printableTagId).outerHTML;
  else
    testo += obj(printableTagId).innerHTML;

  testo += "</div></body></html>";

  var ident_finestra = window.open("","printWindow","width=750,height=450, menubar=no, scrollbars=yes");
  ident_finestra.document.open();
  ident_finestra.document.write(testo);
  ident_finestra.document.close();
  ident_finestra.print();
  setTimeout(function(){ident_finestra.close();},500)
}

//-- START - DRAG script for date field --
var dragObj = new Object();
var zIndex = 1;

function dragStart(event, id) {
  var el;
  var x, y;
  // If an element id was given, find it. Otherwise use the element being
  // clicked on.
  if (id)
    dragObj.elNode = obj(id);
  else {
    if (isExplorer)
      dragObj.elNode = window.event.srcElement;
    else
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (isExplorer) {
    x = window.event.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
        + document.body.scrollTop;
  } else {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = getAbsoluteLeft(dragObj.elNode);
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop = getAbsoluteTop(dragObj.elNode);


  // Update element's z-index.

  function findContainer(theEl) {
    while (theEl.getAttribute("type") != "container") {
      theEl = theEl.parentNode;
    }
    return theEl;
  }
  var theContainer = findContainer(dragObj.elNode);
  zIndex++;
  theContainer.style.zIndex = zIndex;

  // Capture mousemove and mouseup events on the page.
  actualStyle = dragObj.elNode.className;
  if (isExplorer) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup", dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    document.addEventListener("mousemove", dragGo, true);
    document.addEventListener("mouseup", dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {
  var x, y, candidateLeft, candidateTop;

  // Get cursor position with respect to the page.

  if (isExplorer) {
    x = window.event.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
        + document.body.scrollTop;
  } else {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  candidateLeft = dragObj.elStartLeft + x - dragObj.cursorStartX;
  dragObj.elNode.style.left = ((candidateLeft >= 0) ? candidateLeft : 0) + "px";
  candidateTop = dragObj.elStartTop + y - dragObj.cursorStartY;
  dragObj.elNode.style.top = ((candidateTop >= 0) ? candidateTop : 0) + "px";
  dragObj.elNode.className = actualStyle + " drag";
  if (isExplorer) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else
    event.preventDefault();
}

function dragStop(event) {
  dragObj.elNode.className = actualStyle;

  // Stop capturing mousemove and mouseup events.

  if (isExplorer) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup", dragStop);
  } else {
    document.removeEventListener("mousemove", dragGo, true);
    document.removeEventListener("mouseup", dragStop, true);
  }
}
//-- END - DRAG script --

// -- PayPal Button
function recalculatePayPalShipping(inputVal, shippingPrice) {
  if( (shippingPrice && shippingPrice>0) && (inputVal && inputVal>1))
    obj('shipping').value = inputVal*shippingPrice;
}

function recalculatePayPalPrice(price, additionalPrices, isPercentage) {
  if( additionalPrices && additionalPrices>0) {
    var finalVal;
    if(isPercentage) {
      var perc = price*additionalPrices;
      finalVal = price + perc;
    } else {
      finalVal = Number(price) + Number(additionalPrices);
    }
    obj('amount').value = finalVal;
  }
}
// -- PayPal Button end

// ---------------------------------- form validator
function ValidateEmail(emailID, mex, divId) {
  if ( !echeck(emailID.value, mex, divId)) {
    emailID.value = "";
    emailID.focus();
    return false;
  }
  return true;
}

function echeck(str, message, divId) {
  var at="@";
  var dot=".";
  var lat=str.indexOf(at);
  var lstr=str.length;

  if (str.indexOf(at)==-1){
    alertx(message, divId);
    return false;
  }
  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
    alertx(message, divId);
    return false;
  }
  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
    alertx(message, divId);
    return false;
  }
  if (str.indexOf(at,(lat+1))!=-1){
    alertx(message, divId);
    return false;
  }
  if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
    alertx(message, divId);
    return false;
  }
  if (str.indexOf(dot,(lat+2))==-1){
    alertx(message, divId);
    return false;
  }
  if (str.indexOf(" ")!=-1){
    alertx(message, divId);
    return false;
  }
  return true;
}

// Print Util -------------------------------------------------;

$.fn.printForm= function(){
  $("input[type='text'], textarea").each(function(){
    var txt=$(this).val();
    $(this).parent().append("<div class='altFormText'>"+txt+"</div>");
    $(this).hide();
  });
};

$.fn.restoreForm=function(){
  $("input:not(:hidden), textarea").show();
  $(".altFormText").hide();
};

// 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);
    }
  }
}

function fieldValidator(fieldID, message, divId) {
  if ((fieldID.value==null)||(fieldID.value=='')){
    alertx(message, divId);
    fieldID.focus();
    return false;
  } else {
    alertx("&nbsp;", divId);
  }
}

function alertx(message, divId) {
   if(divId && divId!=undefined) {
    obj(divId).innerHTML = message;
    showHideSpan(divId);
   } else {
     alert(message);
   }
}

// ---------------------------------- initialize management
// leaves only char from A to Z, numbers, _ -> valid ID
String.prototype.asId = function () {
  return this.replace(/[^a-zA-Z0-9_]+/g, '');
}

var __initedComponents= new Object();
function initialize(url,includeAsScript){
  var normUrl=url.asId();
  if (!__initedComponents[normUrl]) {
    if (!includeAsScript){
      var text = getContent(url);
      $("body").before(text);
    } else{
      $.ajax({type: "GET",
        url: url,
        dataType: "script",
        async:false});
    }
    __initedComponents[normUrl]="1";
  }
}

if (typeof document._ppInit =="undefined")
  document._ppInit= new Object();

function pp_loadFile(filename, filetype){
  var fileref;
  if (filetype=="js"){ //if filename is a external JavaScript file
    fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", filename);
  }
  else if (filetype=="css"){ //if filename is an external CSS file
    fileref=document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);
  }
  if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

function pp_checkFile(filename, filetype){
  var ID=filename.asId();
  if (!document._ppInit[ID]){
    pp_loadFile(filename, filetype);
    document._ppInit[ID]=1; //List of files added in the form "[filename1] [filename2] etc"
  }
}

jQuery.fn.mb_bringToFront= jQuery.fn.bringToFront = function(){
  var zi=10;
  $('*').each(function() {
    if($(this).css("position")=="absolute" || $(this).css("position")=="fixed"){
      var cur = parseInt($(this).css('zIndex'));
      zi = cur > zi ? parseInt($(this).css('zIndex')) : zi;
    }
  });
  $(this).css('zIndex',zi+=1);
  return $(this);
};

function overlay(el, overlayCanNotClose) {
  var overlay = $("<div class='overlay' style='display:none'/>");
  var overlayContent = $(el);
  overlayContent.css({position:"fixed"});
  $("body").append(overlay);
  overlay.mb_bringToFront().fadeIn();
  var closEl= !overlayCanNotClose ? $(".overlay, .overlayClose") : $(".overlayClose");
  closEl.bind("click", function() {
    overlay.fadeOut("slow", function() {
      overlay.remove();
    });
    overlayContent.fadeOut("slow");
  });
  $("body").append(overlayContent);
  overlayContent.mb_bringToFront().fadeIn();
}

/*-----------------------------------------
 AJAX
 ------------------------------------------*/
function loadDocuments(absolutePath, docId, pageId, currentPageId, placeHolderId) {
  var data =  (docId ? 'docId='+docId : '' ) +
              (pageId ? (docId ? '&' : '') + 'pageId='+pageId : '' ) +
              (currentPageId ? (docId || pageId ? '&' : '') + 'MID='+currentPageId : '' )+'&ts='+new Date().getTime();
  $.ajax({
    type: "POST",
    url: absolutePath,
    data: data,
    cache:false,
    success: function(ret){
      $('#'+placeHolderId).html(ret);
    },
    error: function(err){
      $('#'+placeHolderId).html(err.statusText);
    }
  });
}


/*-----------------------------------------
 AJAX fields validation - used by textfield
 ------------------------------------------*/
function executeCommand(command, data) {
  return getContent(contextPath + "/command.jsp?CM=" + command, data);
}
function validateField(e) {
  var rett=true;
  $('#' + $(this).attr('id') + 'error').remove();
  // 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);
      rett=false;
    }
  }
  return rett;
}

//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"));

    // fake highlight element
    firstErrorElement.addClass("inputWarning");
    setTimeout(
      function(){
        firstErrorElement.removeClass("inputWarning");
      },
    1500);
  }
  return canSubmit;
}

function showFeedbackMessage(type, message){
//  var indo=$("#__FEEDBACKMESSAGEPLACE");
//  if (indo.size()>0)
//    indo.after(getContent(contextPath+"/commons/layout/feedbackFromController/ajaxFeedbackDrawer.jsp", "MESSAGE=" + encodeURIComponent(message)+"&MESSAGE_TYPE="+encodeURIComponent(type)));
//  else
//    alert ("DOM element '__FEEDBACKMESSAGEPLACE' is missing. Add it on screen.\n" + message);
  var place=$("#__FEEDBACKMESSAGEPLACE");
  var mess={type:type,message:message};
  place.append($.JST.createFromTemplate(mess,"errorTemplate"));
  place.fadeIn();
  $("body").oneTime(3000,"hideffc",function(){$(".FFC_" + type).slideUp();});
}

/*  BLACK POPUP-PAG MANAGEMENT  ------------------------------------------------------------------------------ */
//returns a jquery object where to write content
function createBlackPage(width,height, divId, onCloseCallBack) {
  if (!width)
    width='900px';
  if (!height)
    height='500px';

  if(!divId)
    divId = "__blackpopup__";


  $("#"+divId).remove();

  var bg=$("<div>").attr("id", divId);
  var bastardIEcolor = $.browser.msie ? "url(" + contextPath + "'/applications/webwork/images/brown_60.png')" : "rgba(0,0,0,.5)";
  bg.css({position:'fixed',top:"0px",paddingTop:"50px", left:0,width:'100%',height:'100%', background: bastardIEcolor});

  bg.append("<div id='bwinPopupd' name='bwinPopupd'></div>");
  bg.mb_bringToFront();

  var ret=bg.find("#bwinPopupd");
  ret.css({width:width, height:height, top:100, "-moz-box-shadow":'1px 1px 6px #333333', overflow:'auto', "-webkit-box-shadow":'1px 1px 6px #333333', border:'1px solid #777', backgroundColor:"#fff", margin:"auto" });

  var bdiv= $("<div>").css({width:width, position:"relative", height:"0px", textAlign:"right", margin:"auto" });
  var img=$("<img src='" + contextPath + "/applications/webwork/images/closeBig.png' style='cursor:pointer;position:absolute;right:-40px;top:5px;' title='" + getI18n("CLOSE") +"'>");
  bdiv.append(img);
  img.click( function(){
    closeBlackPopup(divId);
  });

  bg.prepend(bdiv);
  $("body").append(bg);

  //close call callback
  bg.bind("close",function(){
    bg.remove();
    if (typeof(onCloseCallBack)=="function")
      onCloseCallBack();
  });

  //destroy do not call callback
  bg.bind("destroy",function(){
    bg.remove();
  });

  return ret;
}

function getBlackPopup(divId){
  if(!divId)
    divId = "__blackpopup__";

  var ret=$("#"+divId);
  if (typeof(top)!="undefined"){
    ret=top.$("#"+divId);
  }
  return ret;
}

function closeBlackPopup(divId){
  getBlackPopup(divId).trigger("close");
}


/*-----------------------------------------
 centralized onload system
 ------------------------------------------*/
var setQA,setStart,setDrop, setInitTree, setInitSizeTree;
init= function() {
  if (setStart==true) start();
  if (setQA==true) quickAccessPos();
  if (setDrop==true) dropInit();
  if (setInitTree==true) inittree();
  if (setInitSizeTree==true) initSizeTree();
  if (isNetscape) emulateHTMLModel();

  $("input[innerLabel][value='']:visible,textarea[innerLabel][value='']:visible").each(function (i) {
    var theField = $(this);
    var wrapper= $("<span/>").css({position:"relative"});
    theField.wrap(wrapper);
    theField.before("<span id='lbdv_" + this.id + "' class='innerLabel'>" + 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();
      }
    });
  });

  //$('.validated').bind('blur', function() { alert('11111'); validateField });
  $('.validated').livequery('blur', validateField);

};


window.onload=init;
