
function mettiInAttesa(form) {
	gestioneAttesa(form, 'wait');
}

function terminaAttesa(form) {
	gestioneAttesa(form, 'default');
}

function gestioneAttesa(form, cursore) {
	document.body.style.cursor=cursore;
	if (form != null) {
		for (ielem=0; ielem<form.elements.length; ++ielem) {
			var elem = form.elements[ielem];
			elem.style.cursor=cursore;
		}
	}
}

function Random(min, max) {
	var seed = Math.random();
	return Math.round(seed * (max - min)) + min;
}

function getUri() {
	var domain = location.hostname;
	var uri = "http://" + domain;
	return uri;
}

// visualizza div
function display_block(id) {
	document.getElementById(id).style.display = "block";
}
function hide_block(id) {
	document.getElementById(id).style.display = "none";
}

function change_display_block(id) {	
	if(document.getElementById(id).style.display == "none")
		document.getElementById(id).style.display = "block";
	else
		document.getElementById(id).style.display = "none";
}

// Restituisce la stringa passata senza gli spazi all'inizio ed alla fine
function Trim(stringa) {
	var newString = "";
	var re = /\s+$|^\s+/g;
	newString = stringa.replace(re, "");
	return newString;
}

// Consente l'immissione di sole cifre o 1 virgola
function numeric(txt, e) {
	// var realkey = String.fromCharCode(event.keyCode);
	browserName = navigator.appName.charAt(0);
	if (browserName == "M")
		key = event.keyCode;
	if (browserName == "N")
		key = e.which;

	// virgola
	if (key == 44) {

		if (txt.value.length > 0 && txt.value.indexOf(',') == -1)
			return true;
		else
			return false;
	}

	// backSpace o canc, solo per Netscape
	if (browserName == "N" && (key == 8 || key == 0))
		return true;

	// cifre
	return ((key >= 48) && (key <= 57)) || key == 13;
}

// Consente l'immissione di sole cifre o '/'
function checkData(e) {

	// var realkey = String.fromCharCode(event.keyCode);
	browserName = navigator.appName.charAt(0);
	if (browserName == "M")
		key = event.keyCode;
	if (browserName == "N")
		key = e.which;

	// backSpace o canc, solo per Netscape
	if (browserName == "N" && (key == 8 || key == 0))
		return true;

	// cifre, Enter(13), slash(47)
	return ((key >= 48) && (key <= 57)) || key == 13 || key == 47;
}

// Consente l'immissione di sole cifre
function intero(e) {
	browserName = navigator.appName.charAt(0);
	if (browserName == "M")
		key = event.keyCode;
	if (browserName == "N")
		key = e.which;

	// backSpace o canc, solo per Netscape
	if (browserName == "N" && (key == 8 || key == 0))
		return true;

	// cifre
	return ((key >= 48) && (key <= 57)) || key == 13;
}

// Consente l'immissione di sole lettere
function lettere(e) {
	browserName = navigator.appName.charAt(0);
	if (browserName == "M")
		key = event.keyCode;
	if (browserName == "N")
		key = e.which;

	// backSpace o canc, solo per Netscape
	if (browserName == "N" && (key == 8 || key == 0))
		return true;

	// lettere minuscole,lettere maiuscole,Enter
	return ((key >= 65) && (key <= 90)) || ((key >= 97) && (key <= 122))
			|| key == 13;
}

// Consente l'immissione di soli numeri e lettere
function alfanumerico(e) {

	return intero(e) || lettere(e);
}

// Consente l'immissione di sole lettere, spazi e apice singolo
function nominativo(e) {
	browserName = navigator.appName.charAt(0);
	if (browserName == "M")
		key = event.keyCode;
	if (browserName == "N")
		key = e.which;

	// backSpace o canc, solo per Netscape
	if (browserName == "N" && (key == 8 || key == 0))
		return true;

	return lettere(e) || key == 32 || key == 39;
}

function isValidCF(cfins) {
	if (isNaN(cfins.substring(0, 1))) {
		var cf = cfins.toUpperCase();
		var cfReg = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
		if (!cfReg.test(cf)) {
			alert('Il codice fiscale non è valido');
			return "";
		} else {
			var set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			var set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
			var setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			var setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
			var 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 è valido');
				return "";
			}
		}
	} else {
		if (cfins != "") {
			if (cfins != "" && cfins.length != 11) {
				alert('Il codice fiscale non è valido');
				return "";
			}
			validi = "0123456789";
			for (i = 0; i < 11; i++) {
				if (validi.indexOf(cfins.charAt(i)) == -1) {
					alert('Il codice fiscale non è valido');
					return "";
				}
			}
			s = 0;
			for (i = 0; i <= 9; i += 2)
				s += cfins.charCodeAt(i) - '0'.charCodeAt(0);
			for (i = 1; i <= 9; i += 2) {
				c = 2 * (cfins.charCodeAt(i) - '0'.charCodeAt(0));
				if (c > 9)
					c = c - 9;
				s += c;
			}
			if ((10 - s % 10) % 10 != cfins.charCodeAt(10) - '0'.charCodeAt(0)) {
				alert('Il codice fiscale non è valido');
				return "";
			}
		}
	}
	return cfins;
}

/**
 * La funzione 'isNull(str)' controlla se la stringa di input e' null
 */
function isNull(str) {
	if (str == "" || str == null) {
		return true;
		// alert("errore")
	} else {
		return false;
		// alert("ok");
	}
}
/**
 * La funzione 'punti(numero)' separa il numero di input utilizzando il punto
 * come separatore delle migliaia Es.: 12345 -> 12.345
 */
function punti(numero) {
	numero = numero.toString();
	dp = numero.indexOf(",") != -1 ? numero.substring(0, numero.indexOf(",")).length
			: numero.length;
	for (i = dp - 3; i > 0; i -= 3)
		numero = numero.substring(0, i) + "." + numero.substr(i);
	numero = numero.replace(/-./, "-");
	return numero
}

/**
 * La funzione 'troncaDecimali(str,cifre)' tronca il numero in input alle prime
 * 'cifre' decimali dopo la virgola
 */
function troncaDecimali(str, cifre) {
	if (str.substr(str.indexOf(",") + 1).length > cifre) {
		alert('Attenzione: il numero sara\' troncato alle prime ' + cifre + ' cifre decimali');
		str = str.substr(0, str.indexOf(",") + cifre + 1);
	}
	return str;
}

/**
 * La funzione 'togliZeriIniziali(str)' toglie gli zeri non significati
 * dall'inizio del numero in input. Es.: 0009,701 ->9,701
 */
function togliZeriIniziali(str) {
	for (i = 0; str.charAt(i) == '0'; i++)
		;
	return str.substr(i);
}

/**
 * La funzione 'toFormatoImporto(valore,dots)' trasforma un numero in formato
 * importo, inserendo i punti come separatore delle migliaia se il parametro
 * dots = true. Restituisce il numero formattato con due cifre decimali ed
 * elimina i punti di separazione superflui, troncando se necessario. Es.:
 * 1.2.3.4,567 -> 1.234,56
 */
function toFormatoImporto(valore, dots) {
	var isOk = false;
	appoggio = valore;
	valore = valore.toString().replace(/\./g, "");
	valore = valore.toString().replace(/\,/g, ".");
	valore = togliZeriIniziali(valore.toString());
	if (!isNull(valore)) {

		if (isNaN(valore) || parseFloat(valore) == 0.0) {
			alert('Il valore immesso non è un numero valido');
			return appoggio;
		} else if (valore.substr(0, valore.indexOf(".") + 1).length == valore.length) {
			alert('Il valore immesso non è un numero valido');
			return appoggio;
		} else {
			valore = valore.replace(".", ",");
			isOk = true;
			valore.indexOf(",") == -1 ? valore += ",00" : valore.substr(valore
					.indexOf(",")).length == 2 ? valore += "0" : null;
			valore.indexOf(",") == 0 ? valore = "0" + valore : null;
			valore.indexOf("-,") == 0 ? valore = "-0" + valore.substr(1) : null;
		}

		isOk ? dots ? valore = punti(valore) : null : null;
		valore = troncaDecimali(valore, 2);
	}
	return valore;
}

function toFormatoImporto1(valore, dots, campo) {
	var isOk = false;
	appoggio = valore;
	valore = valore.toString().replace(/\./g, "");
	valore = valore.toString().replace(/\,/g, ".");
	valore = togliZeriIniziali(valore.toString());
	if (isNull(valore) || valore == 0) {
		val = new String(0);
		isOk = true;
		val.indexOf(",") == -1 ? val += ",00"
				: val.substr(val.indexOf(",")).length < 2 ? val += "00" : null;
		val.indexOf(",") == 0 ? val = "0" + val : null;
		val.indexOf("-,") == 0 ? val = "-0" + val.substr(1) : null;
		return val;
	} else {
		if (!isNull(valore)) {
			if (isNaN(valore)) {
				alert('Il valore ' + campo + ' immesso non e\' valido');
				valore = "0,00"
				return valore;
			} else if (valore.substr(0, valore.indexOf(".") + 1).length == valore.length) {
				alert('Il valore ' + campo + ' immesso non e\' valido');
				valore = "0,00"
				return valore;
			} else {
				valore = valore.replace(".", ",");
				isOk = true;
				valore.indexOf(",") == -1 ? valore += ",00"
						: valore.substr(valore.indexOf(",")).length == 2 ? valore += "0"
								: null;
				valore.indexOf(",") == 0 ? valore = "0" + valore : null;
				valore.indexOf("-,") == 0 ? valore = "-0" + valore.substr(1)
						: null;
			}
			isOk ? dots ? valore = punti(valore) : null : null;
			valore = troncaDecimali(valore, 2);
		}
		return valore;
	}
}

function toFormatoImporto2(valore, dots, campo) {
	var isOk = false;
	appoggio = valore;
	valore = valore.toString().replace(/\./g, "");
	valore = valore.toString().replace(/\,/g, ".");
	valore = togliZeriIniziali(valore.toString());
	if (isNull(valore) || valore == 0) {

		if (appoggio.toString() == '') {
			return '';
		}

		val = new String(0);
		isOk = true;
		val.indexOf(",") == -1 ? val += ",00"
				: val.substr(val.indexOf(",")).length < 2 ? val += "00" : null;
		val.indexOf(",") == 0 ? val = "0" + val : null;
		val.indexOf("-,") == 0 ? val = "-0" + val.substr(1) : null;
		return val;
	} else {
		if (!isNull(valore)) {
			if (isNaN(valore)) {
				alert('Il valore ' + campo + ' immesso non e\' valido');
				valore = "0,00"
				return valore;
			} else if (valore.substr(0, valore.indexOf(".") + 1).length == valore.length) {
				alert('Il valore ' + campo + ' immesso non e\' valido');
				valore = "0,00"
				return valore;
			} else {
				valore = valore.replace(".", ",");
				isOk = true;
				valore.indexOf(",") == -1 ? valore += ",00"
						: valore.substr(valore.indexOf(",")).length == 2 ? valore += "0"
								: null;
				valore.indexOf(",") == 0 ? valore = "0" + valore : null;
				valore.indexOf("-,") == 0 ? valore = "-0" + valore.substr(1)
						: null;
			}
			isOk ? dots ? valore = punti(valore) : null : null;
			valore = troncaDecimali(valore, 2);
		}
		return valore;
	}
}

/**
 * La funzione 'toFormatoNumero(valore,dots)' trasforma un numero inserendo i
 * punti come separatore delle migliaia se il parametro dots = true. Elimina i
 * punti di separazione delle migliaia superflui. Es.: 1.2.3.4,567 -> 1.234,567
 * (dots=true); 1.2345,4567 -> 12345,4567 (dots=false);
 */
function toFormatoNumero(valore, dots) {
	var isOk = false;
	appoggio = valore;
	valore = valore.toString().replace(/\./g, "");
	valore = valore.toString().replace(/\,/g, ".");
	valore = togliZeriIniziali(valore.toString());
	if (!isNull(valore)) {
		if (isNaN(valore) || parseFloat(valore) == 0.0) {
			alert('Il valore immesso non e\' un numero valido');
			appoggio = "0"
			return appoggio;
		} else if (valore.substr(0, valore.indexOf(".") + 1).length == valore.length) {
			alert('Il valore immesso non e\' un numero valido');
			appoggio = "0"
			return appoggio;
		} else {
			valore = valore.replace(".", ",");
			isOk = true;
			if (valore.indexOf(",") != -1) {
				valore.substr(valore.indexOf(",")).length == 2 ? valore += "0"
						: null
			}
			valore.indexOf(",") == 0 ? valore = "0" + valore : null;
			valore.indexOf("-,") == 0 ? valore = "-0" + valore.substr(1) : null;
		}
		isOk ? dots ? valore = punti(valore) : null : null;
	}
	return valore;
}

function toFormatoNumero1(valore, dots, campo) {
	var isOk = false;
	appoggio = valore;
	valore = valore.toString().replace(/\./g, "");
	valore = valore.toString().replace(/\,/g, ".");
	valore = togliZeriIniziali(valore.toString());
	if (isNull(valore)) {
		val = "0";
		isOk = true;
		return val;
	} else {

		if (isNaN(valore) || parseFloat(valore) == 0.0) {
			alert('Il valore ' + campo + ' immesso non e\' valido');
			appoggio = "0";
			return appoggio;
		} else if (valore.substr(0, valore.indexOf(".") + 1).length == valore.length) {
			alert('Il valore ' + campo + ' immesso non e\' valido');
			appoggio = "0";
			return appoggio;
		} else {
			valore = valore.replace(".", ",");
			isOk = true;
			if (valore.indexOf(",") != -1) {
				valore.substr(valore.indexOf(",")).length == 2 ? valore += "0"
						: null
			}
			valore.indexOf(",") == 0 ? valore = "0" + valore : null;
			valore.indexOf("-,") == 0 ? valore = "-0" + valore.substr(1) : null;
		}
		isOk ? dots ? valore = punti(valore) : null : null;
	}
	return valore;
}

/*
 * La funzione 'toFormatoNumeroIntero(valore,campo)' controlla che il valore del
 * campo contenga soltanto numeri
 */
function toFormatoNumeroIntero(valore, campo) {
	if (isNull(valore))
		return ("");

	var re = new RegExp(/^[0-9]+$/);
	if (!valore.match(re)) {
		alert('Il valore ' + campo + ' immesso non e\' valido' + '\n (Inserire soltanto numeri)');
		appoggio = "0";
		return appoggio;
	}

	return valore;
}

/*
 * La funzione 'toFormatoAlfabetico(valore,campo)' controlla che il valore del
 * campo contenga soltanto lettere
 */
function toFormatoAlfabetico(valore, campo) {
	if (isNull(valore))
		return ("");

	var re = new RegExp(/^[a-zA-Z]+$/);
	if (!valore.match(re)) {
		alert('Il valore ' + campo + ' immesso non e\' valido' + '\n (Inserire soltanto lettere)');
		appoggio = "";
		return appoggio;
	}

	return valore;
}

/*
 * La funzione 'toFormatoAlfanumerico(valore,campo)' controlla che il valore del
 * campo contenga soltanto lettere e numeri
 */
function toFormatoAlfanumerico(valore, campo) {
	if (isNull(valore))
		return ("");

	var re = new RegExp(/^[a-zA-Z0-9]+$/);
	if (!valore.match(re)) {
		alert('Il valore ' + campo + ' immesso non e\' valido' + '\n (Inserire soltanto lettere e numeri)');
		appoggio = "";
		return appoggio;
	}

	return valore;
}

/*
 * La funzione 'toFormatoNominativo(valore,campo)' controlla che il valore del
 * campo contenga soltanto lettereMinuscole,lettereMaiuscole,spazi,apici
 */
function toFormatoNominativo(valore, campo) {
	if (isNull(valore))
		return ("");

	var re = new RegExp(/^[a-zA-Z ']+$/);
	if (!valore.match(re)) {
		alert('Il valore ' + campo + ' immesso non e\' valido');
	}

	return valore;
}

/*
 * Controlla il corretto formato data inserito ( 8 cifre oppure GG/MM/YYYY)
 */
function toFormatoData(valore) {

	data = Trim(valore);

	if (isNull(data))
		return ("");

	var re = new RegExp(/^[0-9]{8}$/);
	var re1 = new RegExp(/^\d{2}(\/)\d{2}(\/)\d{4}$/);

	if (!data.match(re) && !data.match(re1)) {
		alert('La data non e\' valida');
		return ("");
	}

	if (data.length == 8 && data.indexOf("/") == -1) {
		data = data.substr(0, 2) + "/" + data.substr(2, 2) + "/"
				+ data.substr(4);
	}

	var parts = data.split('/');
	var gg = parseInt(parts[0],10);
	var mm = parseInt(parts[1],10);
	var yy = parseInt(parts[2],10);

	if (mm == 0 || mm > 12) {
		alert('Il numero dei mesi non e\' valido');
		return ("");
	}
	
	if (mm==2){
		modulo = yy - (parseInt(yy / 4, 10)* 4);
		if (modulo==0){
			if (gg == 0 || gg > 29) {
				alert('Il numero dei giorni non e\' valido');
				return ("");
			}			
		}else{
			if (gg == 0 || gg > 28) {
				alert('Il numero dei giorni non e\' valido');
				return ("");
			}			
		}
	} else if ((mm==4) || (mm==6)|| (mm==9)|| (mm==11)){
		if (gg == 0 || gg > 30) {
			alert('Il numero dei giorni non e\' valido');
			return ("");
		}
	}else {
		if (gg == 0 || gg > 31) {
			alert('Il numero dei giorni non e\' valido');
			return ("");
		}
	}
	return data;
}

// Funzioni per il controllo dell'ora
/*function IsValidTime(timeStr) {
	// Controllo che l'ora sia nel formato HH:MM.

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		alert('L\'ora non e\' un\'ora valida.');
		return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];

	if (hour < 0 || hour > 23) {
		alert('L\'ora non e\' un\'ora valida.');
		return false;
	}

	if (minute < 0 || minute > 59) {
		alert('L\'ora non e\' un\'ora valida.');
		return false;
	}

	return true;
}*/
//Funzioni per il controllo dell'ora
function ControllaOrario(strOrario){
	RE = /^([0-1]?[0-9]|[2][0-3]):([0-5][0-9])$/
	if(!RE.test(strOrario)){
		alert('Il formato deve essere HH:mm')
		return false
	}else return true
}


/**
 * 
 * 
 * Funzioni per il check degli indirizzi email
 * 
 * 
 */

/**
 * 
 * @param formInput
 * @return
 */
function checkValidation(formInput) {

    if (typeof(formInput) != "object") {
        alert(strValidationNotSupported);
        return(false);
    }

    var message;

    if (stringEmpty(formInput.value)) {
        message = strNoInputValue;
        alert(message);
    } else if (noAtSign( formInput.value )) {
        message = strNoAtSign;
        alert(message);
    } else if (nothingBeforeAt(formInput.value)) {
        message = strNothingBeforeAt;        
        alert(message);
    } else if (noLeftBracket(formInput.value)) {
        message = strNoLeftBracket;        
        alert(message);
    } else if (noRightBracket(formInput.value)) {
        message = strNoRightBracket;        
        alert( message);
    } else if (noValidPeriod(formInput.value)) {
        message = strNoValidPeriod;
        alert(message);
    } else if (noValidSuffix(formInput.value)) {
        message = strNoValidSuffix;        
        alert(message);
    } else {
        message = "Success! The email address \"" + formInput.value + "\" validates OK.";
        return true;
    }

    var objType = typeof(formInput.focus);
    if (objType == "object" || objType == "function") {
         formInput.focus();
    }

    return (false);
}

function checkValid (formField) {
    if ( checkValidation ( formField ) == true ) {       
    	return true;
    }

    return ( false );
}

function stringEmpty (formField) {
    // CHECK THAT THE STRING IS NOT EMPTY
    if ( formField.length < 1 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function noAtSign (formField) {
    // CHECK THAT THERE IS AN '@' CHARACTER IN THE STRING
    if (formField.indexOf ('@', 0) == -1) {
        return ( true )
    } else {
        return ( false );
    }
}

function nothingBeforeAt (formField) {
    // CHECK THERE IS AT LEAST ONE CHARACTER BEFORE THE '@' CHARACTER
    if ( formField.indexOf ( '@', 0 ) < 1 ) {
        return ( true )
    } else {
        return ( false );
    }
}

function noLeftBracket (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR LEFT BRACKET
    if ( formField.indexOf ( '[', 0 ) == -1 && formField.charAt (formField.length - 1) == ']') {
        return ( true )
    } else {
        return ( false );
    }
}

function noRightBracket (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN CHECK FOR RIGHT BRACKET
    if (formField.indexOf ( '[', 0 ) > -1 && formField.charAt (formField.length - 1) != ']') {
        return ( true );
    } else {
        return ( false );
    }
}

function noValidPeriod (formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if (formField.indexOf ( '@', 0 ) > 1 && formField.charAt (formField.length - 1 ) == ']')
        return ( false );

    // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
    if (formField.indexOf ( '.', 0 ) == -1)
        return ( true );

    return ( false );
}

function noValidSuffix(formField) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']') {
        return ( false );
    }

    // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
    var len = formField.length;
    var pos = formField.lastIndexOf ( '.', len - 1 ) + 1;
    if ( ( len - pos ) < 2 || ( len - pos ) > 4 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function isDataMinore(date1, date2){

	if (date1!='' && date2!=''){
		var dateStr1 = date1.substr(6) + date1.substr(3,2) + date1.substr(0,2);
		var dateStr2 = date2.substr(6) + date2.substr(3,2) + date2.substr(0,2);

		if (dateStr1>dateStr2){
			return false;
		}else{	
			return true;
		}
	}else{
		return true;
	}
}

//Verifica che il testo non contenga stringhe xss.
function isValorizzatoXss(testo){
	if ((testo.toUpperCase().indexOf("<SCRIPT")>-1) || (testo.toUpperCase().indexOf("&#060;SCRIPT")>-1)){
		return true;
   	}		
	return false;
}


