//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);


//function obj(objId) {
//  return document.getElementById(objId);
//}

function obj(element) {
  if (arguments.length > 1) {
    var elements = new Array();
    var length = arguments.length;
    for (var i = 0; i < length; i++)
      elements.push(obj(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}

function truebody() {
  return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}

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';
  }
}

//windowDimension
function getWindowDimensionH() {
  if (isNetscape) {
    var winHeight = top.window.innerHeight;
  }
  if (isExplorer) {
    var winHeight = document.documentElement.offsetHeight;
  }
  return winHeight;
}

function getWindowDimensionW() {
  if (isNetscape) {
    var winWidth = top.window.innerWidth;
  }
  if (isExplorer) {
    var winWidth = document.documentElement.offsetWidth - 20;
  }
  return winWidth;
}

function sendWindowResizeMessage() {
  obj("commander").src = contextPath + "/commons/tools/command.jsp?CM=UPDATEWINSIZE&PAGE_HEIGHT=" + getWindowDimensionH() + "&PAGE_WIDTH=" + getWindowDimensionW();
}

function getEvent() {
  var ev;
  if (isExplorer)
    ev = window.event;
  else if (isNetscape)
    ev = event;
  return ev;
}

//get mouse position
if (!isExplorer) document.captureEvents(Event.MOUSEMOVE)
var mouseX = 0
var mouseY = 0
addEvent(document, 'mousemove', getMouseXY);

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 when set to visible
function showHideDiv(divId) {
  var x;
  if (obj(divId))
    if (obj(divId).style.visibility == 'hidden') {
      obj(divId).style.visibility = 'visible';
      x = true;
    } else {
      obj(divId).style.visibility = 'hidden';
      x = false;
    }
  return x;
}

var shiftPressed;
var altPressed;
var ctrlPressed;
var commandPressed;
function getAdditionalKeys(e) {
  var evt = navigator.appName == "Netscape" ? e : event;
  // NEWER BROWSERS [CROSS-PLATFORM]
  shiftPressed = evt.shiftKey;
  altPressed = evt.altKey;
  ctrlPressed = evt.ctrlKey;
  commandPressed = evt.metaKey;
  return false;
}

addEvent(document, 'mousedown', getAdditionalKeys);

// return true when set to visible
function showHideSpan(spanId) {
  var visibility;
  if (obj(spanId))
    if (obj(spanId).style.display == 'none') {
      obj(spanId).style.display = '';
      visibility = true;
    } else {
      obj(spanId).style.display = 'none';
      visibility = false;
    }
  return visibility;
}

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;
  //oh non deve essere yes?
  //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);
  var win = window.open(url, nome, 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-----------------------------------------------

function bringToFront(elid) {
  var elsInPage = document.getElementsByTagName("*");
  obj(elid).style.zIndex = elsInPage.length + 1;
}
// 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;
}

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) {  // DEPRECATED
  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;
  }
  */
}
// 28-8-07 modificata da Matteo Bicocchi
function nearBestPosition(where, theObj) {
  var el =  obj(where);
  var target = obj(theObj);
  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";
    }
    if (getAbsoluteTop(target) - getScrollH() + target.offsetHeight >= ((getWindowDimensionH() - barHeight))) {
      target.style.marginTop = (-(el.offsetHeight + target.offsetHeight)) + "px";
    }
    target.style.visibility="visible";
  }
}


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;
      theObject.style.left = document.body.scrollLeft+(document.body.clientWidth - parseFloat(theObject.offsetWidth)) / 2;
    }
  }
}


//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 getKeyCode(e) {
  var a;
  if (isExplorer) {
    a= e.keyCode;
  }
  if (isNetscape) {
    a= e.which;
  }
  return a;
}
// event handling END -------------------------------


//-- START - DRAG script --

// drag management START -----------------------------------------------
var actualStyle = "";
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 --


//-- START AJAX ---------------------------------------------------------------------------

//var xmlHttpRequestObject;
function getXMLObj() {
  //if (xmlHttpRequestObject) {
  //  return xmlHttpRequestObject;
  //} else {
  // branch for native XMLHttpRequest object
  //var req    req must be absolute!!!!!!!!!!!!!!
  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 + "?";
  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);

  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,data) {
  obj(objId).value = getContent(href,data);
}

function loadSyncroPortletContent(href, id) {
  var ext = getFileExtension(href);
  var contenuto = replacePortletPreviewContent(href);
  if (obj(id))
    obj(id).innerHTML = contenuto;
}


//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) {
    deleteRow(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));
//      }
  }
}

function deleteRow(trId) {
  obj(trId).parentNode.removeChild(obj(trId));
}

// END GENERATE TR VIA AJAX

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) {
  var ret = '';
  if(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');
    ret = contenuto;
  }
  return ret;
}

function getI18n(stringToTranslate) {
  return getContent(contextPath + "/commons/js/i18n_js.jsp?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

/**
 *load obj.outerHtml with content of href asynchronously
 *if objId is null call the href but do not refresh
 */
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 ajaxSubmit(formId, domIdToReload) {
  loadAsyncroContent(obj(formId).action, domIdToReload,getDataFromForm(formId));
}


// END AJAX ----------------------------------------------------------------------------


function getUrlFromForm(formId, newAction) {
  var url = '';
  if (newAction)
    url = newAction + "?" + getDataFromForm(formId);
  else
    url = obj(formId).action + "?" + getDataFromForm(formId);
  return url;
}


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;
    }
    if (value != null && value != "") {
      //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 removeSmartComboEntry(param) {
  obj(param).value = '';
  obj(param + '_txt').value = '';
}


// Table management functions ----------------------------------------------------------------------------
function tableRemoveLine(trId) {
  obj(trId).parentNode.removeChild(obj(trId));
}

// 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, scrollable"); // 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;
  elementsq = obj(idForm).elements.length;
  for (h = 0; h <= elementsq; h++) {
    theElement = obj(idForm).elements[h];
    if (theElement) theElement.className = "formElements";
  }
  for (h = 0; h <= elementsq; h++) {
    theElement = obj(idForm).elements[h];
    // Modificata Matteo-Ilaria 19/1/2007
    //    if (theElement && theElement.className == "formElementsError")  theElement.className = "formElements";
    if (theElement && theElement.tagName != "embed" && theElement.value != null) {
      if ((theElement.value == "" || theElement.value.trim().length == 0) && theElement.getAttribute('required') == "true") { //  && theElement.type != "hidden"
        theElement.className = "formElementsError";
        if (theElement.type == "hidden") {
          if (obj(theElement.id + "_txt"))  obj(theElement.id + "_txt").className = "formElementsError";
        }
        if (theElement.getAttribute('maleficoTiny')) {
          //obj('maleficoTiny_' + theElement.getAttribute('maleficoTiny')).className = "formElementsError";
          obj(theElement.getAttribute('maleficoTiny')).className = "formElementsError";
        }
        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";
            //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;
}

// verify before unload BEGIN ----------------------------------------------------------------------------
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];
          if (!('true' == '' + anInput.getAttribute('excludeFromAlert'))) {
            oldValue = anInput.getAttribute("oldValue");
            if (anInput.attributes.getNamedItem("oldValue") && (anInput.value.replace(/\r/g, "") != oldValue.replace(/\r/g, "")))
              if (isExplorer) {
                event.returnValue = getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
              } else {
                return getI18n("FORM_IS_CHANGED") + " \"" + getI18n(anInput.name) + "\"";
              }
          }
        }
      }
    }
  }
}

if (!isExplorer) {
  window.onbeforeunload = alertOnUnload;
} else {
  addEvent(window, "beforeunload", alertOnUnload);
}
// verify before unload END ----------------------------------------------------------------------------


// previously in mbGeneral.js

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;
  }
}

// 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     */

function setSelection(input, start, end) {
  input.focus();
  if (isNetscape) {
    input.setSelectionRange(start, end);
  } else {
    // assumed IE
    var range = input.createTextRange();
    range.collapse(true);
    //alert("start:"+start+" end: "+end);
    range.moveStart('character', start);
    range.moveEnd('character', end - start);
    range.select();
  }
}
;


function getCaretStartBOH(ctrl) {

  var CaretPos = 0;
  // IE Support
  if (document.selection) {

    ctrl.focus();
    var Sel = document.selection.createRange();

    Sel.moveStart('character', -ctrl.value.length);

    CaretPos = Sel.text.length;
  }
  // Firefox support
  else if (ctrl.selectionStart || ctrl.selectionStart == '0')
    CaretPos = ctrl.selectionStart;

  return (CaretPos);

}

function getCaretEndMATTI(obj) {

  obj.focus();
  if (typeof obj.selectionEnd != "undefined") {
    return obj.selectionEnd;
  } else if (document.selection && document.selection.createRange) {
    var M = document.selection.createRange();
    var Lp = obj.createTextRange();
    //alert(Lp.htmlText);
    //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 getCaretStartMATTI(obj) {

  obj.focus();
  if (typeof obj.selectionStart != "undefined") {
    return obj.selectionStart;
  } else if (document.selection && document.selection.createRange) {
    var docRange = document.selection.createRange();
    var taTextRange = obj.createTextRange();
    taTextRange.setEndPoint("EndToStart", docRange);
    alert(taTextRange.htmlText);
    return  taTextRange.text.length;
    //if(rb>obj.value.length){
    //	return -1;
    //}
    //return rb;
  }
}

function getCaretStart(obj) {
  alert("1");
  obj.focus();
  if (typeof obj.selectionStart != "undefined") {
    alert("2");
    return obj.selectionStart;
  } else if (document.selection && document.selection.createRange) {
    alert("3");
    var bookmark = document.selection.createRange().getBookmark();
    obj.selection = obj.createTextRange();
    // create in textarea object and
    obj.selection.moveToBookmark(bookmark);
    // match to document.selection
    obj.selectLeft = obj.createTextRange();
    // create textrange object
    obj.selectLeft.collapse(true);
    // for left amount of textarea &
    obj.selectLeft.setEndPoint("EndToStart", obj.selection);
    // align them
    return obj.selectLeft.text.length;

    //var range = document.selection.createRange();
    //obj.createTextRange()


  }
  alert("4");
}

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 getCaretStartINTER(input) {

  if (isNetscape)
    return input.selectionStart;

  input.focus();
  var range = document.selection.createRange();
  var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
  if (!isCollapsed)
    range.collapse(true);
  var b = range.getBookmark();
  return b.charCodeAt(2) - 2;

}
;


function getCaretEndINTER(input) {

  if (isNetscape)
    return input.selectionEnd;

  input.focus();
  var range = document.selection.createRange();
  var isCollapsed = range.compareEndPoints("StartToEnd", range) == 0;
  if (!isCollapsed)
    range.collapse(false);
  var b = range.getBookmark();
  return b.charCodeAt(2) - 2;
}
;


function setCaret(obj, pos) {
  setSelection(obj, pos, pos);
}

//-- Caret Functions END ---------------------------------------------------------------------------- --

/*    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?
// it doesn't work at all !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
function isNumber(a) {
  return typeof a == 'number' && isFinite(a);
}

function isNumberValue(num) {
  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")
     return false;
  }
}

/* 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;
}

function stopBubble(e) {
  if (isNetscape) {
    e.stopPropagation();
    e.preventDefault();
  }
  if (isExplorer) e = event;
  e.cancelBubble = true;
  e.returnValue = false;
  return false;
}

function textAreaMaxLength(objId, maxLength) {
  if (obj(objId).value.length >= maxLength) {
    var older = obj(objId).value;
    alert('Max textarea length excedeed.\nText will be cut.');
    obj(objId).value = older.substring(0, maxLength);
    return false;
  }
}
// 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 + ">";
  });

}


/*
// centralized onload system
*/

var setQA, setStart, setDrop, setInitTree, setInitSizeTree, setResize;

init = function() {
  //if (setStart == true) start();
  if (setResize == true) initActions();
  if (setQA == true) quickAccessPos();
  if (setDrop == true) dropInit();
  if (setInitTree == true) inittree();
  if (setInitSizeTree == true) initSizeTree();
  if (isNetscape) emulateHTMLModel();
  addEvent(document, "mousemove", showTooltip);
}
window.onload = init;

//script for tooltip


function tt_createDiv() {
  var menuDiv = document.createElement("DIV");
  menuDiv.style.position = "absolute";
  menuDiv.id = "toolTipBox";
  menuDiv.name = "toolTipBox";
  menuDiv.setAttribute("isActive", "0");
  menuDiv.setAttribute("opac", "0");
  document.body.appendChild(menuDiv);
}

var actualTarget = "";
var oldTarget = "";
var charTimeout = 70;
var openTT;
var closeTT;
var tt_wait = 500;
function showTooltip(e) {
  if (inhibitTooltips)
    return;
  thetargetel = getTarget(e);
  if (! obj("toolTipBox"))
    tt_createDiv();
  var theTip = obj("toolTipBox");
  var theSecondMysteriousDiv = obj('toolTipBox_div');
  if (thetargetel && thetargetel.tagName)
    if (thetargetel.getAttribute("tooltip") && thetargetel.getAttribute("tooltip") != "") {
      theTip.setAttribute("isActive", "1");
      actualTarget = thetargetel;
      if (actualTarget != oldTarget) {
        oldTarget = actualTarget;
        argument = unescape(thetargetel.getAttribute("tooltip"));
        //if is explorer and Windows generate an iframe under the menu to prevent a bug in Explorer that put a form popup element over everything
        var content = (isExplorer && isWin ? "<iframe id ='toolTipFrame' style='position:absolute;width:0px;height:0px; z-index:1;overflow:hidden; border: 0px solid red' frameborder=0 framespacing=0 border=0 noresize scrolling='no'></iframe>" : "");
        //
        content += "<div id='ttContainer'  style='position:absolute; z-index:1000; border: 1px solid orange; background-color:white' nowrap>\n";
        content += "<table id ='toolTipBox_div' style='border:1px solid #B8B8B8;border-bottom:1px solid #cccccc;border-right:1px solid #cccccc;padding:2px'><tr><td nowrap>\n";
        content += argument;
        content += "</td></tr></table>\n";
        content += "</div>\n";
        theTip.innerHTML = content;
        if (isExplorer && isWin) {
          setTimeout("obj('toolTipFrame').style.height=obj('toolTipBox_div').offsetHeight+'px'", 0);
          setTimeout("obj('toolTipFrame').style.width=obj('toolTipBox_div').offsetWidth+'px'", 0);
          // this skifis trick is mandatory in order to manage trasparency in IE: no dimensions -> no trasparency
          setTimeout("obj('toolTipBox').style.height=obj('toolTipBox_div').offsetHeight+6+'px'", 0);
          setTimeout("obj('toolTipBox').style.width=obj('toolTipBox_div').offsetWidth+6+'px'", 0);
        }
        theTip.style.display = "";
        setOpac(theTip, 0);
        tt_ypos = (mouseY + 10);
        tt_xpos = (mouseX + 10);
        if (theSecondMysteriousDiv) {
          if ((mouseX + theSecondMysteriousDiv.offsetWidth + 20) > getWindowDimensionW() + getScrollW())
            tt_xpos = (mouseX - theSecondMysteriousDiv.offsetWidth - 10);
          if ((mouseY + theSecondMysteriousDiv.offsetHeight + 20) > getWindowDimensionH() + getScrollH())
            tt_ypos = (mouseY - theSecondMysteriousDiv.offsetHeight - 10);
        }
        theTip.style.top = tt_ypos + "px";
        theTip.style.left = tt_xpos + "px";
        openTT = setTimeout("fadeIn('toolTipBox',0,5,90)", tt_wait);
        var counter = 1000 + tt_wait + (argument.length * charTimeout);
        closeTT = setTimeout("fadeOut('toolTipBox',0,20);", counter);
      }
      // move tooltip

      tt_ypos = (mouseY + 10);
      tt_xpos = (mouseX + 10);
      if (theSecondMysteriousDiv) {
        if ((mouseX + theSecondMysteriousDiv.offsetWidth + 20) > getWindowDimensionW() + getScrollW())
          tt_xpos = (mouseX - theSecondMysteriousDiv.offsetWidth - 10);
        if ((mouseY + theSecondMysteriousDiv.offsetHeight + 20) > getWindowDimensionH() + getScrollH())
          tt_ypos = (mouseY - theSecondMysteriousDiv.offsetHeight - 10);
      }
      theTip.style.top = tt_ypos + "px";
      theTip.style.left = tt_xpos + "px";


    } else {
      fadeOut("toolTipBox", 0, 20);
      if (theTip.getAttribute("isActive") == "1") {
        if (closeTT) clearTimeout(closeTT);
        if (openTT) clearTimeout(openTT);
        fadeOut("toolTipBox", 0, 20);
        theTip.setAttribute("isActive", "0");
      }
      actualTarget = "";
      oldTarget = "";
    }
}
//end script for tooltip

// fade in fade out functions START ------------------  uses "opac" attribute in the objet to be faded --

function setOpac(subj, opac) {
  if (isExplorer) {
    subj.style.filter = "alpha(opacity:" + opac + ")";
  } else
    subj.style.opacity = opac / 100;
}
var fadeTimer;
function fadeIn(objId, delayInMillis, step, op) {
  if (!op) op = 100;
  subj = obj(objId);
  subj.style.display = "";
  opac = parseInt(subj.getAttribute("opac"));
  if (opac < op) {
    opac = opac + step;
    subj.setAttribute("opac", opac)
    //distinguere moz da ie
    setOpac(subj, opac)

    if (fadeTimer)
      clearTimeout(fadeTimer);
    fadeTimer = setTimeout("fadeIn('" + objId + "'," + delayInMillis + "," + step + "," + op + ")", delayInMillis)
  }
}

function fadeOut(objId, delayInMillis, step) {
  subj = obj(objId);
  opac = parseInt(subj.getAttribute("opac"));

  if (opac && opac > 0) {
    opac = opac - step;
    subj.setAttribute("opac", opac)
    //distinguere moz da ie
    setOpac(subj, opac)
    if (fadeTimer)
      clearTimeout(fadeTimer);
    fadeTimer = setTimeout("fadeOut('" + objId + "'," + delayInMillis + "," + step + ")", delayInMillis)
  } else
    subj.style.display = "none";

}
//-- fade in fade out functions END ------------------  uses "opac" attribute in the objet to be faded --

// showThumb.js
var mouseDistance = [10,10];
var imgPreview;
var i;
var x = 0;
var theViewer = false;
var theVideoViewer = false;
var noTitle = "";
var objOpacity = .96;
var f;
var thumbWidth = 450

function createThumbDiv() {
  clearTimeout(f);
  var thumbDiv = createEl("DIV");
  thumbDiv.style.position = "absolute";
  thumbDiv.style.display = "";
  thumbDiv.className = "thumbViewer";
  thumbDiv.id = "thumbViewer";
  thumbDiv.name = "thumbViewer";
  thumbDiv.style.zindex = 2000;
  if (!isExplorer)
    thumbDiv.style.opacity = .1;
  else
    thumbDiv.style.filter = "alpha(opacity:" + 0 + ")";
  thumbDiv.style.top = mouseY + mouseDistance[0] + "px";
  thumbDiv.style.left = mouseX + mouseDistance[1] + "px";
  document.body.appendChild(thumbDiv);
  theViewer = obj('thumbViewer');
  x = 0;
  faderIn('thumbViewer');
}

function showPreview(theImage, title, imageWidth) {
  if (!title)title = noTitle;
  if (imageWidth) thumbWidth = imageWidth;
  if (theViewer) document.body.removeChild(theViewer);
  if (!contextPath)
    contextPath = '';
  createThumbDiv();
  imgPreview = "";

  imgPreview += '<div id="img" align="center" style="padding:10px;padding-bottom:35px; background:white; border:1px solid #cccccc;">';
  //width:'+thumbWidth+'px;
  imgPreview += '<img src="' + contextPath + theImage + '" border="0" >';
  imgPreview += '<br><br>' + title + '</div>';
  theViewer.innerHTML = imgPreview;
  var xcoord = mouseDistance[0];
  var ycoord = mouseDistance[1];
  if ((getWindowDimensionW() + truebody().scrollLeft) - mouseX < theViewer.offsetWidth + 25) {
    var diff = (mouseX + theViewer.offsetWidth + 25) - (getWindowDimensionW() + truebody().scrollLeft);
    //xcoord = mouseX - diff;
    xcoord = mouseX - (theViewer.offsetWidth + mouseDistance[0]);
  } else {
    xcoord += mouseX;
  }
  if ((getWindowDimensionH() + truebody().scrollTop) < mouseY + theViewer.offsetHeight + 25) {
    var diff = (mouseY + theViewer.offsetHeight + 25) - (getWindowDimensionH() + truebody().scrollTop);
    ycoord = mouseY - diff;
  } else {
    ycoord += mouseY;
  }
  if (ycoord < 0) {
    ycoord = ycoord * -1;
  }

  theViewer.style.left = xcoord + "px";
  theViewer.style.top = ycoord + "px";

  addEvent(document, "mousemove", followmouse);
}

function showLargeText(text) {
  if (theViewer) document.body.removeChild(theViewer);
  createThumbDiv();
  imgPreview = "";
  imgPreview += '<div id="img" style="padding:10px;padding-bottom:35px;width:400px; background:white; border:1px solid #cccccc;">';
  imgPreview += text + '</div>';

  //  alert(theViewer);
  theViewer.innerHTML = imgPreview;

  var xcoord = mouseDistance[0];
  var ycoord = mouseDistance[1];
  if ((getWindowDimensionW() + truebody().scrollLeft) - mouseX < theViewer.offsetWidth + 25) {
    var diff = (mouseX + theViewer.offsetWidth + 25) - (getWindowDimensionW() + truebody().scrollLeft);
    //xcoord = mouseX - diff;
    xcoord = mouseX - (theViewer.offsetWidth + mouseDistance[0]);
  } else {
    xcoord += mouseX;
  }
  if ((getWindowDimensionH() + truebody().scrollTop) < mouseY + theViewer.offsetHeight + 25) {
    var diff = (mouseY + theViewer.offsetHeight + 25) - (getWindowDimensionH() + truebody().scrollTop);
    ycoord = mouseY - diff;
  } else {
    ycoord += mouseY;
  }
  if (ycoord < 0) {
    ycoord = ycoord * -1;
  }

  theViewer.style.left = xcoord + "px";
  theViewer.style.top = ycoord + "px";

  addEvent(document, "mousemove", followmouse);
}

var fader = .1;
function faderIn(objToFade) {
  if (x <= 10) {
    fader = (objOpacity / 10) * x;
    x++
    f = setTimeout("faderIn('" + objToFade + "')", 0);
  } else x = 0;
  if (obj(objToFade)) {
    if (!isExplorer) obj(objToFade).style.opacity = fader;
    else obj(objToFade).style.filter = "alpha(opacity:" + fader * 100 + ")";
  }
}

function hidePreview() {
  removeEvent(document, "mousemove", followmouse);
  if (theViewer) document.body.removeChild(theViewer);
  theViewer = false;
}

function followmouse(e) {
  if (theViewer) {
    var xcoord = mouseDistance[0];
    var ycoord = mouseDistance[1];
    if ((getWindowDimensionW() + truebody().scrollLeft) - mouseX < theViewer.offsetWidth + 25) {
      var diff = (mouseX + theViewer.offsetWidth + 25) - (getWindowDimensionW() + truebody().scrollLeft);
      //xcoord = mouseX - diff;
      xcoord = mouseX - (theViewer.offsetWidth + mouseDistance[0]);
    } else {
      xcoord += mouseX;
    }
    if ((getWindowDimensionH() + truebody().scrollTop) < mouseY + theViewer.offsetHeight + 25) {
      var diff = (mouseY + theViewer.offsetHeight + 25) - (getWindowDimensionH() + truebody().scrollTop);
      ycoord = mouseY - diff;
    } else {
      ycoord += mouseY;
    }
    if (ycoord < 0) {
      ycoord = ycoord * -1;
    }

    theViewer.style.left = xcoord + "px";
    theViewer.style.top = ycoord + "px";
    if (getTarget(e).tagName != "IMG") {
      hidePreview();
    }
  }
}

function closeList() {
  theListViewer.parentNode.removeChild(theListViewer);
}
function createListDiv() {
  var thumbDiv = createEl("DIV");
  thumbDiv.style.position = "absolute";
  thumbDiv.style.display = "";
  thumbDiv.className = "listViewer";
  thumbDiv.id = "listViewer";
  thumbDiv.name = "listViewer";
  thumbDiv.style.zindex = 2000;
  thumbDiv.style.backgroundColor = "white";
  thumbDiv.style.top = mouseY + mouseDistance[0] + "px";
  thumbDiv.style.left = mouseX + mouseDistance[1] + "px";
  document.body.appendChild(thumbDiv);
  theListViewer = obj('listViewer');

  addEvent(document, "click", closeList);
  x = 0;
}

// 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 ------------------

var canWrite = true;
function disableText(){
  if(!canWrite) {
    var application_body = obj('application_body');
    var inputtext=application_body.getElementsByTagName("INPUT");
    for (i=0;i<inputtext.length;i++){
      if(inputtext[i].type!='hidden') {
        inputtext[i].disabled=true;
        inputtext[i].style.backgroundColor = '#f3f3f3';
      }
    }

    inputtext=application_body.getElementsByTagName("SELECT");
    for (i=0;i<inputtext.length;i++){
      inputtext[i].disabled=true;
      inputtext[i].style.backgroundColor = '#f3f3f3';
    }

    inputtext=application_body.getElementsByTagName("TEXTAREA");
    for (i=0;i<inputtext.length;i++){
      inputtext[i].disabled=true;
      inputtext[i].style.backgroundColor = '#f3f3f3';
    }
  }
}
addEvent(window,"load",disableText);

