/*
Funzione per aggiungere un evento alla pagina.
*/
function addEvent( obj, szEventType, fnHandler, fUseCapture) {
    if( obj.attachEvent != null ) {
        obj.attachEvent( "on" + szEventType, fnHandler );
	return true;
    } else if( obj.addEventListener != null ) {
	obj.addEventListener(szEventType, fnHandler, fUseCapture);
	return true;
    } else {
        return false;
    }
}

// Controlla se la richiesta ajax e' andata a buon fine
function requestSuccess(xmlHttpRequest) {
    return (200 == xmlHttpRequest.status) ? true : false;
}

// Recupera un valore dalla request XML
function getDataFromRequest(xmlHttpRequest, tagName) {
    return xmlHttpRequest.responseXML.getElementsByTagName(tagName).item(0).firstChild.data;
}

// Recupera un valore dalla request XML dall'elemento chiamato 'stato'
function getStatoFromRequest(xmlHttpRequest) {
    return getDataFromRequest(xmlHttpRequest, 'stato');
}

// Recupera un valore dalla request XML dall'elemento chiamato 'result'
function getResultFromRequest(xmlHttpRequest) {
    return getDataFromRequest(xmlHttpRequest, 'result');
}

/* Restituisce il value di un oggetto passandogli l'id dell'oggetto (Pippo)
Id: l'attributo id dell'oggetto.
Se l'oggetto non esiste ritorna una stringa vuota.
I tipi di oggetti supportati sono:
INPUT TEXT
INPUT CHECKBOX
INPUT RADIO
INPUT HIDDEN
SELECT
*/
function getValue(id) {
	var obj = document.getElementById(id);
        var ret = '';
	if(obj) {
		var tag = obj.tagName.toUpperCase();
		if('INPUT' == tag) {
			var type = obj.type.toUpperCase();
			if('CHECKBOX' == type
                          || 'RADIO' == type) {
				if(obj.checked) {
					ret = obj.value;
				}
			} else { // TEXT || HIDDEN
				ret = obj.value;
			}
		} else if('SELECT' == tag) {
			ret = obj[obj.selectedIndex].value;
		} else {
			ret = obj.value;
		}
	}
        return ret;
}

/*
* Seleziona una option all'interno di una select (Pao)
* elSelectId: L'id della select o l'oggetto Select
* value: il value della option da selezionare
* fRaiseOnChange (opzionale): se true, una volta selezionata la option scatena
*                 l'evento onchange della select. Di default è false.
*/
function selectOptions(oSelect, value, fRaiseOnChange) {
    var selObj = getObject(oSelect);
    for (j = 0; j < selObj.options.length; j++)
        if (selObj.options[j].value == value) {
            selObj.options[j].selected = true;
            if (fRaiseOnChange)
                selObj.onchange();
            break;
        }
}

//funzione per aprire una finestra modale, viene specificato l'url,  l'altezza e la larghezza della finestra
function apriModale(url,larghezza,altezza){
  window.showModalDialog(url,window,"dialogHeight: " + altezza + "px;dialogWidth: " + larghezza + "px;center=yes;status=no;scroll=yes;help=no;resizable=yes");
}

//funzione per aprire una finestra non modale, viene specificato l'url,  l'altezza e la larghezza della finestra
function apriNonModale(url,larghezza,altezza){
  window.showModelessDialog(url,window,"dialogHeight: " + altezza + "px;dialogWidth: " + larghezza + "px;center=yes;status=no;help=no;resizable=yes");
}

function apriNonModaleLeft(url,larghezza,altezza){
  window.showModelessDialog(url,window,"dialogTop: 10px; dialogLeft: 500px;dialogHeight: " + altezza + "px;dialogWidth: " + larghezza + "px;center=yes;status=no;help=no;resizable=yes");
}

function isNumeric(strString, strValid)
//  check for valid numeric strings
{
	var strValidChars;
	var strChar;
	var blnResult = true;

	if( (strString == null) || (strString.length == 0) )
        	return false;

	if( (strValid == null) || (strValid.length == 0) )
		strValidChars = "0123456789.-";
        else
		strValidChars = strValid;

   	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
      		if (strValidChars.indexOf(strChar) == -1)
      		{
         		blnResult = false;
    		}
    	}
	return blnResult;
}

function isNumericInteger(str)
// returns true if str is numeric is it contains only the digits 0-9
// returns false otherwise
// returns false if empty
{
	return isNumeric(str, "0123456789")
}

/**
 * Funzione per la sostituzione di sottostringhe contenute in una stringa madre.
 */
function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

/**
 * Gestione dei checkbox
 */
function checkBox(obj, nameTag, pathOn, textOn, pathOff, textOff) {
  if(obj.src.indexOf(pathOff.substring(1, pathOff.length)) != -1) {
    obj.src = pathOn;
    obj.alt = textOn;
    obj.title = textOn;
    document.getElementById(nameTag).value = "1";
  } else {
    obj.src = pathOff;
    obj.alt = textOff;
    obj.title = textOff;
    document.getElementById(nameTag).value = "0";
  }
}

/**
  Funzione per formattare i campi currency
  */
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 formatCur(obj) {
  var tmp = obj.value;
  tmp = replaceSubstring(tmp, " ", "");
  tmp = replaceSubstring(tmp, "€", "");
  tmp = replaceSubstring(tmp, ".", "");
  tmp = replaceSubstring(tmp, ",", ".");
  obj.value = formatCurrency(tmp);
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkForm(){
  var i;
  var stato = false;

  for (i=0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.type == "text" && ele.value == "") {
      stato=true;
    }
  }
  if(!stato) {
    document.formMain.submit();
  } else {
    alert("Attenzione! I campi devono essere riempiti");
  }
}

/**
* Funzione per selezionare tutti i checkbox presenti
* @return
*/
function checkAll(){
  var i;

  for (i=0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.type == "checkbox" ) {
      ele.checked =true;
    }
  }
}

function checkMax(obj,valore){
 var numero;

 numero = parseInt(obj.value,10);
 if(numero>0 && numero <=valore){
   numero=0;
 }else{
   obj.value=valore;
 }
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkFormObbligatori(){
  var stato = false;

  for (var i = 0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.className == "obbligatorio" && ele.value == "") {
      stato=true;
    } else {
      if (ele.className == "obbligatorioNumerico" && !isNumeric(ele.value)) {
        stato=true;
      } else {
        if (ele.className == "obbligatorioNumericoIntero" && !isNumericInteger(ele.value)) {
          stato=true;
        }
      }
    }
    if (ele.type == "radio" && ele.className == "obbligatorio") {
      var el = document.formMain.elements;
      var radiogroup = document.getElementsByName(ele.name);
      var itemchecked = false;
      if(radiogroup.length == 1 || null == radiogroup.length) {
        if(ele.checked == true) {
          itemchecked = true;
        }
      } else {
        for(var j = 0 ; j < radiogroup.length; ++j) {
          if(radiogroup[j].checked == true) {
            itemchecked = true;
            break;
          }
        }
      }
      if(itemchecked == true) {
        stato = false;
      } else {
        stato = true;
      }
    }
  }
  if(!stato) {
    document.formMain.submit();
  } else {
    alert("Attenzione! I campi obbligatori devono essere riempiti");
  }
  return !stato;
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkFormObbligatori_message(errorMsg){
  var stato = false;

  for (var i = 0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.className == "obbligatorio" && ele.value == "") {
      stato=true;
    } else {
      if (ele.className == "obbligatorioNumerico" && !isNumeric(ele.value)) {
        stato=true;
      } else {
        if (ele.className == "obbligatorioNumericoIntero" && !isNumericInteger(ele.value)) {
          stato=true;
        }
      }
    }
    if (ele.type == "radio" && ele.className == "obbligatorio") {
      var el = document.formMain.elements;
      var radiogroup = document.getElementsByName(ele.name);
      var itemchecked = false;
      if(radiogroup.length == 1 || null == radiogroup.length) {
        if(ele.checked == true) {
          itemchecked = true;
        }
      } else {
        for(var j = 0 ; j < radiogroup.length; ++j) {
          if(radiogroup[j].checked == true) {
            itemchecked = true;
            break;
          }
        }
      }
      if(itemchecked == true) {
        stato = false;
      } else {
        stato = true;
      }
    }
  }
  if(!stato) {
    document.formMain.submit();
  } else {
    alert(errorMsg);
  }
  return !stato;
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkFormObbligatori_message_noSubmit(errorMsg){
  var stato = false;

  for (var i=0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.className == "obbligatorio" && ele.value == "") {
      stato = true;
    } else {
      if (ele.className == "obbligatorioNumerico" && !isNumeric(ele.value)) {
        stato = true;
      } else {
        if (ele.className == "obbligatorioNumericoIntero" && !isNumericInteger(ele.value)) {
          stato = true;
        }
      }
    }
    if (ele.type == "radio" && ele.className == "obbligatorio") {
      var el = document.formMain.elements;
      var radiogroup = document.getElementsByName(ele.name);
      var itemchecked = false;
      if(radiogroup.length == 1 || null == radiogroup.length) {
        if(ele.checked == true) {
          itemchecked = true;
        }
      } else {
        for(var j = 0 ; j < radiogroup.length; ++j) {
          if(radiogroup[j].checked == true) {
            itemchecked = true;
            break;
          }
        }
      }
      if(itemchecked == true) {
        stato = false;
      } else {
        stato = true;
      }
    }
  }
  if(!stato) {
    return true;
  } else {
    alert(errorMsg);
  }
  return !stato;
}
/*
* Invia un comando all'handler definito nell'hidden "handler" (Pao)
* sCommand: il comando da inviare
* fWarn (opzionale): se true chiede conferma prima di inviare il comando
* sWarnText (opzionale): il testo del messaggio di conferma
* restituisce: false se l'utente ha scelto di non continuare
*/
function sendCommand(sCommand, fWarn, sWarnText) {
    if (sWarnText == undefined)
        sWarnText = "";
    if (!fWarn || confirm(sWarnText))
        with (document.formMain) {
            command.value = sCommand;
            submit();
            return true;
        }
    return false;
}



/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkFormObbligatori_noSubmit(){
  var stato =false;
  for (var i = 0; i < document.formMain.elements.length; i++) {
    ele = document.formMain.elements[i];
    if (ele.className == "obbligatorio" && ele.value == "") {
      stato=true;
    } else {
      if (ele.className == "obbligatorioNumerico" && !isNumeric(ele.value)) {
        stato=true;
      } else {
        if (ele.className == "obbligatorioNumericoIntero" && !isNumericInteger(ele.value)) {
          stato=true;
        }
      }
    }
    if (ele.type == "radio" && ele.className == "obbligatorio") {
      var el = document.formMain.elements;
      var radiogroup = document.getElementsByName(ele.name);
      var itemchecked = false;
      if(radiogroup.length == 1 || null == radiogroup.length) {
        if(ele.checked == true) {
          itemchecked = true;
        }
      } else {
        for(var j = 0 ; j < radiogroup.length; ++j) {
          if(radiogroup[j].checked == true) {
            itemchecked = true;
            break;
          }
        }
      }
      if(itemchecked == true) {
        stato = false;
      } else {
        stato = true;
      }
    }
  }
  if(!stato) {
    return true;
  } else {
    alert("Attenzione! I campi obbligatori devono essere riempiti");
    return false;
  }
}

function ControllaPIVA(pi) {
var stato = true;

if( pi == '' )
 stato=false;
if( pi.length != 11 ) {
 alert("La lunghezza della partita IVA non è\n" + "corretta: la partita IVA dovrebbe essere lunga\n" + "esattamente 11 caratteri.\n");
  stato=false;
 }
validi = "0123456789";
for( i = 0; i < 11; i++ ){
if( validi.indexOf( pi.charAt(i) ) == -1 ) {
 alert("La partita IVA contiene un carattere non valido `" + pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n");
  stato=false;
 }
}
s = 0;
for( i = 0; i <= 9; i += 2 )
	s += pi.charCodeAt(i) - '0'.charCodeAt(0);
for( i = 1; i <= 9; i += 2 ){
    c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
	if( c > 9 )
	c = c - 9;
	s += c;
}
if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) ) {
	alert("La partita IVA non è valida:\n" + "il codice di controllo non corrisponde.\n");
	stato=false;
	}
return stato;
}

function ControllaCF(cf) {
 var validi, i, s, set1, set2, setpari, setdisp;
 var stato=true;
 if( cf == '' )
  stato=false;
  cf = cf.toUpperCase();
  if( cf.length != 16 ){
   alert("La lunghezza del codice fiscale non è\n" +"corretta: il codice fiscale dovrebbe essere lungo\n" +"esattamente 16 caratteri.\n");
   stato=false;
  }
  validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  for( i = 0; i < 16; i++ ){
    if( validi.indexOf( cf.charAt(i) ) == -1 ) {
	  alert("Il codice fiscale contiene un carattere non valido `" + cf.charAt(i) + "'.\nI caratteri validi sono le lettere e le cifre.\n");
	    stato=false;
	  }
   }
  set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
 setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
 s = 0;
 for( i = 1; i <= 13; i += 2 )
   s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
 for( i = 0; i <= 14; i += 2 )
   s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
 if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) ) {
   alert("Il codice fiscale non è corretto:\n"+ "il codice di controllo non corrisponde.\n");
     stato=false;
   }
 return stato;
}

function setStyle(objId, style) {
	if (navigator.userAgent.indexOf("Opera") != -1)
      	{ 	//Opera
        	styleObj = eval('document.all.' + objId);
              	styleObj.style.display = style;
      	} else if (document.getElementById) {
                //Netscape 6 & IE 5
        	myObj = document.getElementById(objId);
              	myObj.style.display = style;
      	} else {
      		alert('This website uses DHTML. We recommend you upgrade your browser.');
      	}
}

/**
* Funzione per il controllo dei campi numerici
*/
function checkNumeric(obj){
	if(!isNumeric(obj.value)) {
    		obj.value = "999999999";
      		obj.value = "";
		alert("Attenzione campo Numerico!!")
    	}
}
/* Versione abbreviata di document.getElementById. "id" può essere sia l'id
dell'oggetto che l'oggetto stesso (Pao) */
function o(id) {
    return getObject(id);
}

/* Restituisce true se l'oggetto o è "", undefined o null (Pao) */
function isEmpty(o) {
    return (o == undefined || o == null || o == "");
}
/* Restituisce l'oggetto document.getElementById(obj) se obj è una stringa,
altrimenti reistituisce obj. */
function getObject(obj) {
    return (typeof obj == "string") ? document.getElementById(obj) : obj;
}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only,text) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
                } else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
                } else {
			return;
                }
		var re = new RegExp(regex);
		for (var i=0; i<obj.options.length; i++) {
                        if(text) {
          			if (re.test(obj.options[i].text)) {
	          			obj.options[i].selected = selected1;
                                } else {
			        	if (only == true) {
				        	obj.options[i].selected = selected2;
                                        }
                                }
                        } else {
          			if (re.test(obj.options[i].value)) {
	          			obj.options[i].selected = selected1;
                                } else {
			        	if (only == true) {
				        	obj.options[i].selected = selected2;
                                        }
                                }
                        }
                }
        }
}
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex,text){
  selectUnselectMatchingOptions(obj,regex,"select",false,text);
}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex,text){
  selectUnselectMatchingOptions(obj,regex,"select",true,text);
}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in.
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex,text){
  selectUnselectMatchingOptions(obj,regex,"unselect",false,text);
}
/*
Funzione per disabilitare tutti gli campi che hanno uno contenitore in comune.
container = object or id of the element that contains the elements being changed.
disable = boolean, disabled value
*/
function switchEnableElements(container, disable) {
	var children = ($(container) || document.body).getElementsByTagName('*');
	for(var i = 0; i < children.length; i++) {
		if(['input', 'select', 'textarea'].include(children[i].tagName.toLowerCase())) {
			children[i].disabled = disable;
		}
	}
}
