
//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 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';
    }
}

function showHideSpan(spanId) {
  if (obj(spanId))
    if (obj(spanId).style.display == 'none') {
      obj(spanId).style.display = '';
    } else {
      obj(spanId).style.display = 'none';
    }
}
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){
  xPos = el.offsetLeft;
  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;
}


function positionIt(where, theObj) {
  //if (!distanceY) distanceY = 0;
  //if (!distanceX) distanceX = 0;
  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;
  }
}

function nearBestPosition(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);
    trueY = getAbsoluteTop(el);
    var h = el.offsetHeight;
    elHeight = parseFloat(h);
    trueY += parseFloat(elHeight);
    target.style.left = trueX;
    target.style.top = trueY;
    barHeight=(isExplorer)?45:35;
    barWidth=(isExplorer)?20:0;
    if (getAbsoluteLeft(target)>=(getWindowDimensionW()-target.offsetWidth)){
      target.style.left=getWindowDimensionW()-target.offsetWidth-barWidth;
    }
    if (getAbsoluteTop(target)+target.offsetHeight>=(getWindowDimensionH()-barHeight)){
      target.style.marginTop=((getAbsoluteTop(target)-((getWindowDimensionH()-barHeight)-el.offsetHeight)))+"px";
    }
  }
}

function centerObject(objId) {
  if (obj(objId)) {
    var theObject = obj(objId)
    theObject.style.position = "absolute";
    theObject.style.top = document.body.scrollTop+(document.body.clientHeight  - parseFloat(theObject.offsetHeight)) / 2;
    theObject.style.left = document.body.scrollLeft+(document.body.clientWidth - parseFloat(theObject.offsetWidth)) / 2;
  }
}
//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);
}

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;
        window.status = "";
      } else {
        alert("Error opening:[" + href + "] status:" + ajax.status);
      }
    }
  };
  if (data)
    ajax.send(data);
  else
  ajax.send(null);
}

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);
}

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);
}
// 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 (alertMessage!="")
  //   alert(alertMessage+"campi obbligatori")

  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";
            //alert(allTabLabel[i].id+"   class=  "+allTabLabel[i].className)
          }
        }
      }
      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;
}

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");
};
/* --- 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\">"
  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)
}

/*
// 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();
}

//-- 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 --

function recalculatePayPalShipping(inputVal, shippingPrice) {
  if( (shippingPrice && shippingPrice>0) && (inputVal && inputVal>1)) {
    var finalValue = inputVal*shippingPrice;
    obj('shipping').value = finalValue;
  }
}


// ---------------------------------- form validator
function echeck(str, message, divId) {
  var at="@"
  var dot="."
  var lat=str.indexOf(at)
  var lstr=str.length
  var ldot=str.indexOf(dot)
  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) {
  obj(divId).innerHTML = message;
  showHideSpan(divId);
}



// ---------------------------------- 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]){
    //alert(url+" -- "+normUrl+" -- "+__initedComponents[normUrl]);
    if (!includeAsScript){
      var text = getContent(url);
      $("body").before(text);
    } else{
      $.ajax({type: "GET",
              url: url,
              dataType: "script",
              async:false});
    }
    __initedComponents[normUrl]="1";
  }
}

window.onload=init;