/**Funzioni Script di carattere generale
 *
 */

function selectOption(tagSelect, value) {
	var i;
	var option;

	for(i=0; i < tagSelect.options.length; i++) {
        	if(tagSelect.options[i].value == value)
        		tagSelect.options[i].selected = true;
	}
}

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")
}

function checkModificaDocumento(){
      	var i;
      	var stato = false;
      	var check = false;

      	for(i=0; i < parseInt(formMain.indice.value); i++) {
        	if(eval("formMain.riga_"+i+".checked")) {
			check=true;
         	}
       	}

      	if(!check) stato=true;
      	if(!stato)
           	formMain.submit();
  	else
        	alert("Attenzione! Almeno una riga deve essere selezionata");
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkForm() {
        var ele;
        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) {
		formMain.submit();
      	} else {
      		alert("Attenzione! I campi devono essere riempiti");
	}
}

/**
* Funzione per selezionare tutti i checkbox presenti
* @return
*/
function checkAll() {
	var ele;
      	var i;
	for (i=0; i < document.formMain.elements.length; i++) {
          	ele = document.formMain.elements[i];
		if (ele.type == "checkbox" ) {
			ele.checked =true;
           	}
  	}
}

/**
 * Funzione per testare se i campi text, sono stati riempiti
 * Il form è quello solito formMain
 *
 */
function checkFormObbligatori(){
    	var i;
    	var stato = false;
	var ele;
    	for (i=0; i < document.formMain.elements.length; i++) {
		ele = document.formMain.elements[i];
    		if (ele.className == "obbligatorio" && ele.value == "") {
    			stato=true;
           	}
           	if (ele.className == "obbligatorioNumerico" && !isNumeric(ele.value)) {
             		stato=true;
           	}
           	if (ele.className == "obbligatorioNumericoIntero" && !isNumericInteger(ele.value)) {
           		stato=true;
           	}
           	if(ele.type == "radio"
                   && ele.className == "obbligatorio") {
            		var el = document.forms[0].elements;
            		var radiogroup = el[ele.name]; // get the whole set of radio buttons.
	    		var itemchecked = false;
            		for(var j = 0 ; j < radiogroup.length ; ++j) {
	    			if(radiogroup[j].checked) {
		 			itemchecked = true;
		 			break;
				}
	   		}
	   		if(!itemchecked) {
	   			stato=true;
	   		}
	  	}
        }
	if(!stato) {
    		formMain.submit();
	} else {
        	alert("Attenzione! I campi obbligatori devono essere riempiti");
    	}
  	return !stato;
}

/**
* Metodo per il controllo della partita iva
*/
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;
}

/**
* Metodo per il controllo del codice Fiscale
*/
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;
}

/**
* Funzione per il controllo dei campi numerici
*/
function checkNumeric(obj) {
	if(!isNumeric(obj.value)) {
		obj.value="999999999";
		obj.value="";
		alert("Attenzione campo Numerico!!")
    	}
}

/**
 * Funzione per la sostituzione si 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

/**
 * Funzione per aprire un URL in una nuova pagina.
 */
function openUrl(url, name) {
	if(url != "") {
		if(name != "") {
                  name = replaceSubstring(name, " ", "");
                  name = replaceSubstring(name, ".", "");
		} else {
                  name = "_";
                }
        	window.open(''+url,''+name,'left=20,top=20,width=500,height=500,toolbar=0,resizable=1,scrollbars=1');
	}
}

