<!--
//*************************************************************************************************
//                    VALIDA.JS -- LIBRERIA DI VALIDAZIONE DI FORM DI INPUT.					  *
//											REL. 1.0 											  *
//																								  *
// Per applicare la validazione alla form, per ogni campo soggetto a controllo sarà necessario    *
// assegnare un ID al campo INPUT con la sintassi seguente: 									  *
// <input … ID = "N_OBBL_TIPO">																	  *
// dove:																						  *
// *	N = progressivo del controllo all'interno della form									  *
// *	OBBL = stringa che può valere OBB (obbligatorio) NOB (non obbligatorio)					  *
// *	TIPO = stringa che specifica il tipo; costanti ammesse:									  *
// 	·	INT (intero)																			  *
// 	·	STR (stringa)																			  *
// 	·	DAT (data)	 																			  *
// 	·	PIVA (Partita iva, con algoritmo di validazione)										  *
// 	·	EML (email tipo: nome@dominio.dom2)														  *
// 	·	PWD (password: da usare in combinazione col campo CPW)									  *
// 	·	CPW (conferma password) - richiede un ulteriore parametro in coda a ID: 				  *
//			"_M" dove M è l'indice del campo contenente la password da confrontare				  *
// 																								  *
//*************************************************************************************************


//*************************************************************************************************
// scorre tutti gli elementi della form da validare ed effettua la validazione					  *
//*************************************************************************************************
function validateForm(form) {
	var i;
	var input;

	for (i=0;i<form.elements.length;i++) {
		input = form.elements[i];
		if (!validateControl(input)) return false;
	}
	//validazione dell'accettazione delle condizioni
	if (form.accept) {
		if( form.accept.type=='radio') {
			if (!form.accept[0].checked) {
				alert('Per proseguire è necessario accettare le condizioni');
				return false;
			}
		} else if(form.accept.type=='checkbox'){
			if (!form.accept.checked) {
				alert('Per proseguire è necessario accettare le condizioni');
				return false;
			}
		}
	}
}
//*************************************************************************************************
// dato un controllo di input (oggetto), ne effettua la validazione 							  *
//*************************************************************************************************

function validateControl(input) {
	var ctrl;
	var nomeCampo;
	var id='';
	var value;
	var obbl;
	var tipo;
	
	ctrl = input.name;
	if (input.id) {
		id = input.id;
	} else {
		id = '';
	}
	if (id!=''){
		if (id.substring(1,2) == '_') {
			obbl = id.substring(2,5);
			tipo = id.substring(6,9);
			index = id.substring(0,1);
		} else {
			obbl = id.substring(3,6);
			tipo = id.substring(7,10);
			index = id.substring(0,2);
		}
		// legge il nome del campo dalla tabella, se trova l'ID,
		// altrimenti usa il nome del campi input
		if (document.all)
			if (document.all['TD'+index])
				nomeCampo = document.all['TD'+index].innerText;
			else
				nomeCampo = ctrl;
		else
			nomeCampo = ctrl;
		//se il campo è obbligatorio, verifica se il valore non è vuoto
		if (obbl=='OBB'){
			if (input.type == 'select-one') {
				if (input.selectedIndex==0) {
					alert('Selezionare un valore del campo \'' + nomeCampo + '\'');
					input.focus();
					return false;
				}
			} else {
			if (input.form[input.name].length) {
				trovato=false;
				for(i=0;i<input.form[input.name].length;i++) {
					if (input.form[input.name][i].checked) {
						trovato=true;
					}
				}
				if (!trovato) { 
					alert('Selezionare un valore per il campo \'' + nomeCampo + '\'');
					input.focus();
					return false;
				}
			}
			}
			if (input.value == ''){
				alert('Inserire il campo \'' + nomeCampo + '\'');
				input.focus();
				return false;
			}
		}
		if (input.value != '') {
			//validazione del formato e-mail
			if (tipo=='EML') {
				if (!isEmail(input)){
					alert('Il campo \'' + nomeCampo + '\'' + ' non è un indirizzo email');
					return false;
				}
			}
			//validazione del tipo numerico generico
			if (tipo=='NUM') {
				if (!isNum(input)) {
					alert('Il campo \'' + nomeCampo + '\'' + ' non è un numero');
					return false;
				}
			}
			//validazione del tipo intero
			if (tipo=='INT') {
				if (!isInt(input)) {
					alert('Il campo \'' + nomeCampo + '\'' + ' non è un numero intero');
					return false;
				}
			}
			//validazione del tipo data
			if (tipo=='DAT') {
				if (!isDate(input)) {
					alert("Il campo " + nomeCampo + " è in formato errato. Il formato è gg mm aa oppure gg mm aaaa con qualunque separatore (oppure senza separatore)");
					return false;
				}
			}
			//validazione del tipo partita IVA
			if (tipo=='IVA') {
				switch(checkPIva(input.value)) {
					case (0): {
						break;
					}
					case (1): {
						alert('Il campo \'' + nomeCampo + '\'' + ' non è valido: la P.Iva dev\'essere almeno di 11 numeri');
						input.focus();
						return false;
						break;
					}
					case (2): {
						alert('Il campo \'' + nomeCampo + '\'' + ' non è valido: la P.Iva dev\'essere numerica');
						input.focus();
						return false;
						break;
					}
					case (3): {
						alert('Il campo \'' + nomeCampo + '\'' + ' non è valido: la P.Iva deve almeno una cifra maggiore di 0 nei primi 7 caratteri');
						input.focus();
						return false;
						break;
					}
					case (4): {
						alert('Il campo \'' + nomeCampo + '\'' + ' non è valido: il numero di P.Iva non è valido');
						input.focus();
						return false;
						break;
					}
				}
			}
			//validazione della conferma password
			if (tipo=='CPW') {
				for (var j=0;j<input.form.elements.length;j++) {
					if (input.form.elements[j].id.substring(0,1) == id.substring(10,11)) {
						if (input.form.elements[j].value != input.value) {
							alert("La password non è confermata correttamente");
							input.focus();
							return false
							}
					}
				}
			}
		}
	}
	return true;
}

//*************************************************************************************************
// data una stringa ritorna una stringa senza gli spazi in testa								  *
//*************************************************************************************************
function CutSxSpaces (stringa) {
	//conto gli spazi che ci sono in testa
	var prima = 0;
	var indice = 0;
	var ncar = stringa.length;
	while ((indice <= ncar-1) && (stringa.charAt(indice) == ' ' )) {
		prima++;
		indice++;
	}
	//tolgo gli spazi in testa
	return stringa.substring(prima,ncar);
}
//**************************************************************************************************

//*************************************************************************************************
// data una stringa ritorna una stringa senza gli spazi in coda								  *
//*************************************************************************************************
function CutDxSpaces (stringa) {
	//conto gli spazi che ci sono in coda
	var ncar = stringa.length;
	var dopo = 0;
	var indice = ncar-1;
	while ((indice >= 0) && (stringa.charAt(indice) == ' ' )) {
		dopo++;
		indice--;	
	}
	//tolgo gli spazi in coda
	return stringa.substring(0,ncar-dopo);
}
//**************************************************************************************************


//*************************************************************************************************
// verifica se il contenuto di un campo obbligatorio è vuoto. Se vuoto avverte e ne forza l'input *
//*************************************************************************************************
function IsEmpty(form, campo, nome_campo) {
	if (form.elements[campo].value.length == 0) {
		window.alert('Inserire un valore nel campo: '+nome_campo);
		form.elements[campo].focus();
		return false;
	}
return true;
}
//**************************************************************************************************

//*********************************************************************
//verifica se il contenuto del campo è un numero intero positivo.     *
//ritorna true se è un numero o se è null, altrimenti ritorna false   *
//*********************************************************************
function isInt(campo) {	
	if (campo.value.length == 0) {
		return true;
	}
	
	var numero = campo.value;
	
	//vengono tolti gli spazi in testa ed in coda
	var numero1 = CutDxSpaces(numero);
	var numero2 = CutSxSpaces(numero1);
	
	ncar = numero2.length;

	//vengono ammessi solo digit
	var cifre = '0123456789';
	var ok = true;
	for (var i = 0; i < ncar; i++) {
		if (cifre.indexOf(numero2.charAt(i))<0) {
			//non è un numero
			ok = false;
		}
	}
	if (ok) {
		campo.value = numero2;
		return true;
	} else {
		campo.focus();
		return false;
	}
}
//************************************************************************************************


//**********************************************************************************
//verifica se il contenuto del campo è un numero decimale positivo o negativo.     *
//il formato è del tipo [+,-]ii[,ddddd]                                            *
//dopo il controllo restituisce sempre nel formato [-]ii,dd						   *
//ritorna true se è un numero decimale o se è null, altrimenti ritorna false       *
//**********************************************************************************
function isNum(campo) {
	
	if (campo.value.length == 0) {
		return true;
	}
	
	var numero = campo.value;
	var cifre1 = '+-0123456789,';
	var cifre2 = '0123456789,';
	//vengono tolti gli spazi in testa ed in coda
	var numero1 = CutDxSpaces(numero);
	var numero2 = CutSxSpaces(numero1);
	
	ncar = numero2.length;

	var num_virgole = 0;  // mi dice quante virgole ci sono
	
	// verifico che il 1^ carattere sia un digit oppure "-" oppure "+" oppure ","
	var ok_primo = true;
	if (cifre1.indexOf(numero2.charAt(0))<0) {
		ok_primo = false;
		}
		
	if (numero2.charAt(0) == ',') {
		num_virgole += 1;
	}
	
	//verifico che gli altri caratteri siano o digit o ","
	var ok = true;
	for (var i = 1; i < ncar; i++) {
		//window.alert('cifra '+i+'^ :'+numero2.charAt(i));
		if (cifre2.indexOf(numero2.charAt(i))<0) {
			ok = false;
		}
		if (numero2.charAt(i) == ',') {
			num_virgole += 1;
		}
	}
	
	if (ok && ok_primo && (num_virgole <= 1)) {
		// se c'è tolgo il leading "+"
		if (numero2.charAt(0) == '+') {
			var numero3 = numero2.substr(1);
		} else {
			var numero3 = numero2;
		}
		
		pos_virgola = numero3.indexOf(',');
		var len = numero3.length;				
		var numero_formattato;
		/*
		if (pos_virgola == -1) {
			// è un numero intero; aggiungo ",00" alla fine
			numero_formattato=numero3.concat(",00");
		} else {
			if ((len - pos_virgola -1) > 2) {
				// ci sono più di 2 decimali; tolgo quelli in eccesso
				var ndec = len - pos_virgola -1;	// numero di posizioni decimali
				var dec_da_togliere = ndec -2;		// numero di posizioni decimali da tagliare da destra
				var numero4 = numero3.substr(0, (len - dec_da_togliere));	//ho tolto i decimali di troppo
				numero3 = numero4;
			}
			if (pos_virgola == 0) {
				//la virgola è il 1^ carattere; aggiungo uno 0 in testa
				var numero5 = "0".concat(numero3);
				numero3 = numero5;
			}
			numero_formattato = numero3;
		}
		
		form.elements[campo].value = numero_formattato;
		*/
		return true;
	} else {
		campo.focus();
		return false;
	}
}
//************************************************************************************************


//**********************************************************************************
//Validazione di un campo data													   *
//il formato è del tipo gg*mm*aaaa dove:                                           *
//gg = giorno																	   *
//mm = mese																	       *
//aaaa = anno																	   *
//* = qualsiasi separatore che non sia 0..9										   *
//il separatore viene sempre convertito in /									   *
//**********************************************************************************
function isDate(campo) {
var checkstr = "0123456789";
var DateField = "";
var Datevalue = "";
var DateTemp = "";
var seperator = "/";
var day;
var month;
var year;
var leap = 0;
var err = 0;
var i;
   err = 0;
   DateField = campo;
   DateValue = DateField.value;
   
   if (DateValue=='') return true;
   /* Delete all chars except 0..9 */
   for (i = 0; i < DateValue.length; i++) {
	  if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
	     DateTemp = DateTemp + DateValue.substr(i,1);
	  }
   }
   DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* year is wrong if year = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* Validation of month*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
	  return true
   }
   /* Error-message if err != 0 */
   else {
	  return false
      DateField.select();
	  DateField.focus();
   }
}
//************************************************************************************************

//***********************************************************************************
//verifica se il contenuto del campo è un indirizzo e-mail sintatticamente corretto *
//il formato è del tipo user@domain2.domain1                                        *
//ritorna true seè un indirizzo e-mail, altrimenti ritorna false                    *
//***********************************************************************************
function isEmail(campo) {
	var email = campo.value;
	var at=false;
	var dot=0;
	var ok = true;
	var i;
	
	if (email=='') return true;
	
	for(i=0;i<email.length&&ok;i++) {
		if (email.charAt(i)=='@') {
			if (!at)
				at=true;
			else
				ok=false;
		};
		if (email.charAt(i)=='.') 
			dot++
	}
	if (dot==0||!ok) {
		campo.focus();
		return false;
	}
	else
		return true;
}
//***********************************************************************************
//			verifica se un testo è una partita IVA ammissibile			            *
//***********************************************************************************
function checkPIva(value) {
	if (value.length != 11) 
		return 1; // errore su lunghezza
	
	if (isNaN(value))
		return 2; // errore su non numerico

	if (value.substring(0,7)=='0000000')
		return 3; // errore su troppi zeri

	//algoritmo di validazione
	somma=0;
	checkDigit = value.substring(10,11);
	for (i=0;i<10;i++) {
		car=value.substring(i,i+1);
		if (((i+1) % 2) == 0) {
		//posizione pari
			car = car * 2;
			if (car>9) car = (car+'').substring(0,1)*1 + (car+'').substring(1,2)*1;
		}
		somma+=car*1;
	}
	somma = somma + '';
	if (somma.length >1 ) 
		digit = somma.substring((somma.length) - 1,(somma.length))
	else
		digit =somma;
	if (digit != 0) digit = 10 - digit;
	if (checkDigit==digit)
		return 0
	else
		return 4
}

//******************************************************************************************
//date due date (data1 e data2) entrambe nel formato gg/mm/aaaa, verifica che data2 sia    *
//più recente di data1, altrimenti da errore e ritorna false							   *
//data1 = data iniziale																	   *
//data2 = data finale																	   *
//label_data1 = label del campo che contiene data1										   *
//label_data2 = label del campo che contiene data2								     	   *
//******************************************************************************************
function confronta_date (data1, data2, label_data1, label_data2){
	var anno1 = data1.substring(6,10);
	var anno2 = data2.substring(6,10);
	if (anno1 > anno2) {
		window.alert(label_data2+' deve essere più recente di '+label_data1);
		return false;
	}
	if (anno1 < anno2) {
		return true;
	}
	var mese1 = data1.substring(3,5);
	var mese2 = data2.substring(3,5);
	if (mese1 > mese2) {
		window.alert(label_data2+' deve essere più recente di '+label_data1);
		return false;
	}
	if (mese1 < mese2) {
		return true;
	}
	var giorno1 = data1.substring(0,2);
	var giorno2 = data2.substring(0,2);
	if (giorno1 > giorno2) {
		window.alert(label_data2+' deve essere più recente di '+label_data1);
		return false;
	}
	return true;
}
//************************************************************************************************

// -->
