function AJAXConnect() {
  var xmlhttp, bComplete = false;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new XMLHttpRequest();
      } catch (e) {
        xmlhttp = false;
        }
      }
    }
    if (!xmlhttp) return null;
    this.connect = function(sURL, sMethod, sVars, fnDone, oFormName, oDivName, entityName) {
      if (!xmlhttp) return false;
      bComplete = false;
      sMethod = sMethod.toUpperCase();
      try {
        if (sMethod == "GET") {
          xmlhttp.open(sMethod, sURL+"?"+sVars, true);
          sVars = "";
        }
        else {
          xmlhttp.open(sMethod, sURL, true);
          xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
          xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete) {
          bComplete = true;
          fnDone(xmlhttp, oFormName, oDivName, entityName);
        }
      };
      xmlhttp.send(sVars);
    } catch(z) { return false; }
    return true;
  };
  return this;
}

function myRound(val, precision) {
  //debug('Val: ' + val + '; precision: ' + precision);
  val = Number(val);
  precision = Number(precision);

  // Multiply by 10 to the power of precision and add 0.5 for rounding up
  // Take the nearest integer smaller than this value
  val = Math.floor( val * Math.pow( 10, precision ) + 0.5 );

  // Divide it by 10**precision to get the rounded value
  var result = Number(val / Math.pow( 10, precision ));
  //debug('Diventa: ' + result);
  return result;
}

function failure(failureMessage) {
  if (failureMessage == null || failureMessage == '') {
    failureMessage = 'Attenzione! Si e\' verificato un errore mentre si cercava di compiere l\'operazione richiesta'
  }
  alert(failureMessage);
}

function showHideDiv(divName) {
  if(document.getElementById(divName).style.display == "block") {
    document.getElementById(divName).style.display = "none";
    //document.getElementById('btn'+divName).value = "Apri";
    document.getElementById('btn'+divName).src = '/images/software/freccia_dx.gif';
  }
  else {
    document.getElementById(divName).style.display = "block";
    //document.getElementById('btn'+divName).value = "Chiudi";
    document.getElementById('btn'+divName).src = '/images/software/freccia_dwn.gif';
  }
}

function showHide(elm, arrowId) {
  with(document.getElementById(elm)) {
    if(style.display == "none") {
      style.display = "block";
      document.getElementById(arrowId).src = '/images/software/freccia_dwn.gif';
    } else {
      style.display = "none";
      document.getElementById(arrowId).src = '/images/software/freccia_dx.gif';
    }
  }
}

function open_window(whichPage, pageTitol, width, height) {
  if (!width) width = 510;
  if (!height) height = 386;
  searchWin = window.open(whichPage, pageTitol, 'scrollbars=yes, resizable=yes, width='+width+', height='+height+', status=no, location=no, toolbar=no');
}

 //v2.0
function MM_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}


var imageManagerFormName = "";
var imageManagerFieldName = "";
function openImageManager(htmlField) {
  var currentImage = htmlField.value;
  if (currentImage == null) currentImage = "";
  imageManagerFormName = 'document.' + htmlField.form.name;
  imageManagerFieldName = htmlField.name;
  window.open('/adm/component/imagemanager.do?cmd=start&currentImage=' + currentImage,'','width=650,height=555,toolbar=no,scrollbars=yes,resizable');
}

var repositoryManagerFormName = "";
var repositoryManagerFieldName = "";
function openRepositoryManager(htmlField) {
  var currentDocument = htmlField.value;
  if (currentDocument == null) currentDocument = "";
  repositoryManagerFormName = 'document.' + htmlField.form.name;
  repositoryManagerFieldName = htmlField.name;
  window.open('/adm/component/repositorymanager.do?cmd=start&currentImage=' + currentDocument,'','width=650,height=555,toolbar=no,scrollbars=yes,resizable');
}

function clicca(param) {
  if (confirm(param)) {
    return true;
  } else {
    return false;
  }
}

function loadXsl(xslToLoad) {
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", xslToLoad + '?pid=' + Math.random(), false);
   xmlhttp.send(null);
   var xsl = xmlhttp.responseXML;
   var processor = new XSLTProcessor();
   processor.importStylesheet(xsl);
   return processor;
}

function loadMenu(cmd, targetElem, vars, idXPathString, labelXPathString, secondIdXPathString) {
   if (vars == null || vars == '') {
     targetElem.innerHTML = '';
     return false;
   }
   if (idXPathString == null || idXPathString == '')
     idXPathString = '/root/data//id';
   if (labelXPathString == null || labelXPathString == '')
     labelXPathString = '/root/data//chooseableDescription';

   for (i = 0; i <= targetElem.length; i++) {
    targetElem.remove(targetElem.selectedIndex);
   }
   var voidOpt = document.createElement('option');
   voidOpt.text = '';
   voidOpt.value = '';
   addToDropDownMenu(targetElem, voidOpt);
   var sFromUrl = "/entityResolver.do?cmd=" + cmd + '&' + vars + '&debugxml=true';
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET", sFromUrl + '&serial=' + Math.random(), false);
   xmlhttp.send('');
//   alert(new XMLSerializer().serializeToString(xmlhttp.responseXML));
   var xmlDoc = xmlhttp.responseXML;
   xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
   xmlDoc.setProperty("SelectionLanguage", "XPath");
   var oElem = xmlDoc.selectNodes(idXPathString);
   var oElemV = xmlDoc.selectNodes(labelXPathString);
   var oElemA = null;
   if (secondIdXPathString != null && '' != secondIdXPathString)
     oElemA = xmlDoc.selectNodes(secondIdXPathString);
   for (i = 0; i < oElem.length; i++) {
    var opt = document.createElement('option');
    opt.text = ((oElemV[i].childNodes[0] != null) ? oElemV[i].childNodes[0].nodeValue : '');// new XMLSerializer().serializeToString(oElemV[i]);
    var idOfOption = '';
    if (oElemA != null) {
      idOfOption = oElem[i].childNodes[0].nodeValue + '-' + oElemA[i].childNodes[0].nodeValue;
    } else {
      idOfOption = oElem[i].childNodes[0].nodeValue;
    }
    opt.value = idOfOption;//new XMLSerializer().serializeToString(oElem[i]);
    addToDropDownMenu(targetElem, opt);
  }
//    targetElem.
//        alert(new XMLSerializer().serializeToString(oElem[i]));
//  var result = new XMLSerializer().serializeToString(oElem);
//  return result;

//  xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
//  xmlDoc.setProperty("SelectionLanguage", "XPath");
//   var processor = loadXsl("/xsl/options.xsl");
//   Sarissa.updateContentFromURI(sFromUrl, targetElem, processor, null, 'true');
  return;
}

function addToDropDownMenu(targetElem, opt) {
    try {
      targetElem.add(opt,null); // standards compliant
    } catch(ex) {
      targetElem.add(opt); // IE only
    }
}

function updatePageContent(url, urlArgs, xslToUse, targetElem, callBack) {
  var processor = ((xslToUse != null && xslToUse != '') ? loadXsl(xslToUse) : null);
  Sarissa.updateContentFromURI(url + ((processor != null) ? '?debugxml=true&' : '?') + urlArgs, targetElem, processor, callBack, 'true');
}

function ajaxRequest(url, urlArgs, returnXml) {
  if (returnXml == null)
    returnXml = false;
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", url + "?debugxml=" + returnXml + "&" + urlArgs + '&serial=' + Math.random(), false);
  xmlhttp.send('');
  return xmlhttp;
}

function xpathQuery(xmlObj, xPathQuery) {
  var xmlDoc = xmlObj.responseXML;
  xmlDoc.setProperty("SelectionNamespaces", "xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
  xmlDoc.setProperty("SelectionLanguage", "XPath");
  try {
    return Sarissa.getText(xmlDoc.selectSingleNode(xPathQuery));
  } catch (ignore) {
    return '';
  }
}

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num)) num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  cents = num % 100;
  num = Math.floor(num / 100).toString();
  if (cents < 10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1+i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
  return (((sign) ? '' : '-') + '' + num + ',' + cents);
}

function resetCurrency(num) {
  num = num.toString().replace(/\$|\./g,'');
  num = num.toString().replace(/\,/g,'.');
  return num;
}

function isDefined(variable) {
  return (!(!( variable||false )))
}

function debug(messageToPrint) {
  if (true) {
    if ($('__debug') == null) {
      var debugWindow = document.createElement('textarea');
      debugWindow.id = '__debug';
      debugWindow.cols = 800;
      debugWindow.rows = 20;
      document.body.appendChild(debugWindow);
    }
    $('__debug').value += formatDate(new Date(), 'dd/MM/yyyy hh:mm:ss') + ': ' + messageToPrint + '\n<br/>';
  }
  return false;
}
