// JS Common
// *******************  INDEX  ************************
// checkDateBefore(strDay,strMonth,strYear,monthsToCheck) 									 Funzione che controlla che la data inserita sia inferiore alla data odierna + monthsToCheck
// checkDateAfter(strDay,strMonth,strYear,monthsToCheck)									 Funzione che controlla che la data inserita sia superiore alla data odierna + monthsToCheck
// checkDateRange(strDay,strMonth,strYear,minMonthsToCheck,maxMonthsToCheck)				 Funzione che controlla che la data inserita sia compresa nel range di mesi specificati (valori negativi nel caso di mesi precedenti alla data odierna)
// checkDateNotAfterToday(comboDaysId,comboMonthsId,comboYearsId)							 Controlla che la data settata nelle combo indicate non sia superiore a quella odierna. In caso contrario, setta la data odierna.
// checkBirthDate(strBirthDay,strBirthMonth,strBirthYear,yearToCheck)       				 Funzione che controlla che l'età corrispondente alla data di nascita inserita siamo maggiore o uguale all'età da controllare (yearToCheck)
// checkBirthDateBefore(strBirthDay,strBirthMonth,strBirthYear,yearToCheck)					 Funzione che controlla che l'età corrispondente alla data di nascita inserita sia minore all'età da controllare (yearToCheck)
// checkBirthDateRange(strBirthDay,strBirthMonth,strBirthYear,minYearToCheck,maxYearToCheck) Funzione che controlla che l'età corrispondente alla data di nascita inserita siamo compresa tra le età inserite
// isDateAfter(strDateToCheck,strRefDate) 													 Funzione che controlla che la data strDateToCheck sia successiva alla data strRefDate
// highlightError(errorId)																	 Funzione per la visualizzazione del div contenente il messaggio di errore e per evidenziare il campo relativo
// hideError(errorId)																		 Funzione per nascondere il div contenente il messaggio di errore
// isMandatory(propertyName, errorId, fillOnChange, noSelectionValue)						 Controlla la presenza di valori per i campi obbligatori
// isDateMandatory(strDay, strMonth, strYear, error1,error2, fillOnChange)					 Controlla l'obbligatorietà della data
// changeDateStyle(errorId,fillOnChange)													 Cambia lo stile della data
// isAlphabetic(propertyName, errorId)														 Controlla che il valore della proprietà sia alfabetico (a-z oppure A-Z) o un apice
// isNumeric(propertyName, errorId)															 Controlla che il valore della proprietà sia numerico (0-9)
// isEmail(propertyName, errorId)															 Controlla che il valore della proprietà rappresenti un indirizzo e-mail valido
// lengthConstraints(propertyName, errorId, minLength, maxLength)							 Controlla che il valore assunto dalla proprietà rispetti i limiti specificati sulla lunghezza
// changeSelectStyle(errorId,fillOnChange)													 Modifica lo stile della select su un change (da error ritorna normale)
// showError(errorId,value1,value2,value3)											 		 Visualizza in popup il messaggio dell'errore bloccante errorId specificato nel WarningResources con gli eventuali parametri specificati
// showWarning(warningId,value1,value2,value3)												 Visualizza in popup il messaggio del warning warningId specificato nel WarningResources con gli eventuali parametri specificati
// locValid(searchLoc, sessionId, defaultValue)												 Ricerca località in base alla stringa di ricerca 'searchLoc', l'id della sessione 'sessionId', e il valore opzionale 'defaultValue' per settare un'opzione di default nella combo
// loadLoc(x,t,idSess,defaultValue)															 Funzione per la ricerca della località invocata dalla funzione 'locValid'
// displayLoc()
// hideLoc()
// ricercaProfessioni(searchJob, sessionId, loadingImgId,defaultValue)      				 Ricerca professione in base alla stringa di ricerca 'searchJob', l'id della sessione 'sessionId', e il valore opzionale 'defaultValue' per settare un'opzione di default nella combo. 'loadingImgId' è l'id dell'immagine da visualizzare quando il servizio è in esecuzione.
// loadProfessioni(descrProf,idSession,loadingImgId,defaultValue)           				 Funzione per la ricerca della professione invocata dalla funzione 'loadProfessioni'
// updateSelectList(selectList)																 Rimuove il campo 'seleziona' da una lista di select se queste sono già state selezionate
// isNumberKey(evt)																			 Funzione per disabilitare l'inserimento di caratteri non numerici in un input text
// cleanErrorInPage()																		 Funzione per rimuovere gli stili e i div di errore nelle pagine con varianti
// classe CustomSlide()																		 Wrapper della classe Fx.Slide per correggere il problema di sovrapposizione dei div di errore con i div sottostanti nelle pagine che utilizzano gli effetti di slide
// disableControls(root)																	 Funzione per disabilitare i controlli di input in pagina (link e submit) per evitare il doppio submit. La root rappresenta la radice da cui iniziare la ricerca	
// ****************************************************


// Funzione per la visualizzazione degli errori bloccanti
function showError(errorId,value1,value2,value3){
	var basePath = '..';
	if ($defined(document.getElementById('magnoliaContextPathID'))) {
    	basePath = document.getElementById('magnoliaContextPathID').value;
	}
	var link = basePath + "/error/error.jsp?bundleKey="+errorId+"&value1="+value1+"&value2="+value2+"&value3="+value3;
	MOOdalBox.open(link, "", "594 306");
}

// Funzione per la visualizzazione dei warning
function showWarning(warningId,value1,value2,value3){
	var basePath = '..';
	if ($defined(document.getElementById('magnoliaContextPathID'))) {
    	basePath = document.getElementById('magnoliaContextPathID').value;
	}
	var link = basePath + "/error/warning.jsp?bundleKey="+warningId+"&value1="+value1+"&value2="+value2+"&value3="+value3+"&twoWay=false&twoButton=true";
	MOOdalBox.open(link, "", "594 306");
}

// Funzione per la visualizzazione dei warning
function showWarningTwoWay(warningId,value1,value2,value3){
	var basePath = '..';
	if ($defined(document.getElementById('magnoliaContextPathID'))) {
    	basePath = document.getElementById('magnoliaContextPathID').value;
	}
	var link = basePath + "/error/warning.jsp?bundleKey="+warningId+"&value1="+value1+"&value2="+value2+"&value3="+value3+"&twoWay=true";
	MOOdalBox.open(link, "", "594 306");
}

// Funzione per la visualizzazione dei warning
function showWarningOneButton(warningId,value1,value2,value3){
	var basePath = '..';
	if ($defined(document.getElementById('magnoliaContextPathID'))) {
    	basePath = document.getElementById('magnoliaContextPathID').value;
	}
	var link = basePath + "/error/warning.jsp?bundleKey="+warningId+"&value1="+value1+"&value2="+value2+"&value3="+value3+"&twoWay=false&twoButton=false";
	MOOdalBox.open(link, "", "594 306");
}

// Funzione che controlla che la data settata nelle combo indicate non sia superiore a quella odierna
// In caso contrario, setta la data odierna
function checkDateNotAfterToday(comboDaysId,comboMonthsId,comboYearsId) {
	if ($(comboYearsId).value!=null && $(comboYearsId).value!="" && $(comboMonthsId).value!=null && $(comboMonthsId).value!="" && $(comboDaysId).value!=null && $(comboDaysId).value!="") {
			var dateStr =  $(comboYearsId).get('value') + "/" + $(comboMonthsId).get('value') + "/" + $(comboDaysId).get('value');
			var date = new Date(Date.parse(dateStr));
			var today = new Date();
		
			if(date>today) {		
				var day = today.getDate();
				if(day<10)
					day = '0'+day;
				var month = today.getMonth()+1;
				if(month<10)
					month = '0'+month;
				var year = today.getFullYear();
				if(year<1900)
					year = 1900+year;
				$(comboDaysId).value = day;
				$(comboMonthsId).value = month;
				$(comboYearsId).value = year;
			}
	}
}

// Funzione che controlla che l'età corrispondente alla data di nascita inserita siamo maggiore o uguale all'età da controllare (yearToCheck)
function checkBirthDate(strBirthDay,strBirthMonth,strBirthYear,yearToCheck){
	var check = true;
	
	var birthDate = new Date(Date.parse(strBirthYear + "/" + strBirthMonth + "/" + strBirthDay));
	
	var minDateToCheck = new Date();
	
	minDateToCheck.setHours(0);
	minDateToCheck.setMinutes(0);
	minDateToCheck.setSeconds(0);
	minDateToCheck.setMilliseconds(0);
	minDateToCheck.setFullYear(minDateToCheck.getFullYear()-yearToCheck);
	
	if(birthDate > minDateToCheck)	// Se la data di nascita è maggiore di questa data limite, allora l'età corrispondente è minore di 'yearToCheck'
		check=false;
	
	return check;
}

// Funzione che controlla che l'età corrispondente alla data di nascita inserita sia minore all'età da controllare (yearToCheck)
function checkBirthDateBefore(strBirthDay,strBirthMonth,strBirthYear,yearToCheck){
	var check = true;
	
	var birthDate = new Date(Date.parse(strBirthYear + "/" + strBirthMonth + "/" + strBirthDay));
	
	var minDateToCheck = new Date();
	
	minDateToCheck.setHours(0);
	minDateToCheck.setMinutes(0);
	minDateToCheck.setSeconds(0);
	minDateToCheck.setMilliseconds(0);
	minDateToCheck.setFullYear(minDateToCheck.getFullYear()-yearToCheck);
	
	if(birthDate <= minDateToCheck)	// Se la data di nascita è minore o uguale a questa data limite, allora l'età corrispondente è maggiore o uguale a 'yearToCheck'
		check=false;
	
	return check;
}

// Funzione che controlla che l'età corrispondente alla data di nascita inserita siamo compresa tra le età inserite
function checkBirthDateRange(strBirthDay,strBirthMonth,strBirthYear,minYearToCheck,maxYearToCheck){
	var check = true;
	
	var birthDate = new Date(Date.parse(strBirthYear + "/" + strBirthMonth + "/" + strBirthDay));
	
	var minDateToCheck = new Date();
	var maxDateToCheck = new Date();
	
	minDateToCheck.setHours(0);
	minDateToCheck.setMinutes(0);
	minDateToCheck.setSeconds(0);
	minDateToCheck.setMilliseconds(0);
	minDateToCheck.setFullYear(minDateToCheck.getFullYear()-minYearToCheck);
	
	maxDateToCheck.setHours(0);
	maxDateToCheck.setMinutes(0);
	maxDateToCheck.setSeconds(0);
	maxDateToCheck.setMilliseconds(0);
	maxDateToCheck.setFullYear(maxDateToCheck.getFullYear()-maxYearToCheck-1);
	
	if(birthDate > minDateToCheck || birthDate <= maxDateToCheck)	// Se la data di nascita è maggiore di 'minDateToCheck', allora l'età corrispondente è minore di 'minYearToCheck', 
		check=false;												// mentre se la data di nascita è minore o uguale di 'maxDateToCheck', allora l'età corrispondente è maggiore di 'maxYearToCheck', 
	
	return check;
}


function checkDateString(dataStr, validationErrorId, fillOnChange) {
	var espressione = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;	
	if (!espressione.test(dataStr))	{	    
		$(validationErrorId).style.display = 'inline';
		changeDateStyle(validationErrorId,fillOnChange);
		return 1;
	}else {		
		anno = parseInt(dataStr.substr(6),10);		
		mese = parseInt(dataStr.substr(3, 2),10);		
		giorno = parseInt(dataStr.substr(0, 2),10);				
		var data = new Date(anno, mese-1, giorno);		
		if (data.getFullYear() == anno && data.getMonth() + 1 == mese && data.getDate() == giorno) {			
			return 0;		
		} else {			
			$(validationErrorId).style.display = 'inline';
			changeDateStyle(validationErrorId,fillOnChange);
			return 1;		
		}	
	}
}



// Funzione che controlla che la data inserita sia compresa nel range di mesi specificati 
// (valori negativi nel caso di mesi precedenti alla data odierna)
function checkDateRange(strDay,strMonth,strYear,minMonthsToCheck,maxMonthsToCheck){
	var check = true;
	
	var dateToCheck = new Date(Date.parse(strYear + "/" + strMonth + "/" + strDay));
	
	var minYears = parseInt(minMonthsToCheck/12);
	var minMonths = minMonthsToCheck%12;
	var maxYears = parseInt(maxMonthsToCheck/12);
	var maxMonths = maxMonthsToCheck%12;
	
	var minDate = new Date();
	
	minDate.setHours(0);
	minDate.setMinutes(0);
	minDate.setSeconds(0);
	minDate.setMilliseconds(0);
	minDate.setFullYear(minDate.getFullYear()+minYears);
	minDate.setMonth(minDate.getMonth()+minMonths);
	//alert(minDate);
	var maxDate = new Date();
	
	maxDate.setHours(0);
	maxDate.setMinutes(0);
	maxDate.setSeconds(0);
	maxDate.setMilliseconds(0);
	maxDate.setFullYear(maxDate.getFullYear()+maxYears);
	maxDate.setMonth(maxDate.getMonth()+maxMonths);
	//alert(maxDate);
	
	if(dateToCheck>maxDate || dateToCheck<minDate)	
		check=false;
	
	//alert(check);
	
	return check;
}

// Funzione che controlla che la data inserita sia superiore alla data odierna + monthsToCheck
function checkDateAfter(strDay,strMonth,strYear,monthsToCheck){
	var check = false;
	
	var dateToCheck = new Date(Date.parse(strYear + "/" + strMonth + "/" + strDay));
	
	var maxYears = parseInt(monthsToCheck/12);
	var maxMonths = monthsToCheck%12;
	
	var maxDate = new Date();
	
	maxDate.setHours(0);
	maxDate.setMinutes(0);
	maxDate.setSeconds(0);
	maxDate.setMilliseconds(0);
	maxDate.setFullYear(maxDate.getFullYear()+maxYears);
	maxDate.setMonth(maxDate.getMonth()+maxMonths);
	
	if(dateToCheck>maxDate)	
		check=true;
	
	return check;
}

// Funzione che controlla che la data inserita sia inferiore alla data odierna + monthsToCheck
function checkDateBefore(strDay,strMonth,strYear,monthsToCheck){
	var check = false;
	
	var dateToCheck = new Date(Date.parse(strYear + "/" + strMonth + "/" + strDay));
	
	var minYears = parseInt(monthsToCheck/12);
	var minMonths = monthsToCheck%12;
	
	var minDate = new Date();
	
	minDate.setHours(0);
	minDate.setMinutes(0);
	minDate.setSeconds(0);
	minDate.setMilliseconds(0);
	minDate.setFullYear(minDate.getFullYear()+minYears);
	minDate.setMonth(minDate.getMonth()+minMonths);
	
	if(dateToCheck<minDate)	
		check=true;
	
	return check;
}

function isDateAfter(strDateToCheck,strRefDate)
{
	var check = false;
	var dateToCheck = string2date(strDateToCheck);
	var refDate = string2date(strRefDate);
	if (dateToCheck!=null && refDate!=null) {
		if(dateToCheck>refDate)	
			check=true;
	}
	return check;
}


// Funzione che trasforma una stringa (in formato 'gg/mm/aaaa') in data 
function string2date(date_str) {

	try {
		var date_result = null;
		var date2check_str = date_str.split('/');
		if (date2check_str.length==3) {
			var date2check_day = date2check_str[0].toInt();
			var date2check_month = date2check_str[1].toInt();
			var date2check_year = date2check_str[2].toInt();
	
			date_result = new Date();
			date_result.setDate(date2check_day);
			date_result.setMonth(date2check_month-1);
			date_result.setFullYear(date2check_year);
		}
	} catch(e) {}
	
	return date_result;
}

// Funzione per la visualizzazione del div contenente il messaggio di errore e per evidenziare il campo relativo (select)
function highlightError(errorId,fillOnChange) {
	$(errorId).style.display = 'inline';
	highlightField(errorId);
	changeSelectStyle(errorId,fillOnChange);
	changeTextStyle(errorId,fillOnChange);
}

// Funzione per la visualizzazione del div contenente il messaggio di errore e per evidenziare il campo relativo (textfield)
function highlightTextError(errorId,fillOnChange) {
	if(fillOnChange == null)
		fillOnChange = true;
	$(errorId).style.display = 'inline';
	highlightField(errorId);
	changeTextStyle(errorId,fillOnChange);
}

// Funzione per nascondere il div contenente il messaggio di errore
function hideError(errorId) {
	$(errorId).style.display = 'none';
}

//Start common toggle radio function
function toggleRadio(x, radioBox, show, divId) {
    if (!x.getElementsByTagName('input')[0].checked) {
    	if (show){
    		if(divId != null)
	    		$(divId).style.display = 'inline';
    		radioBox.slideIn();
    	}else
    		radioBox.slideOut();
    	return void(0);
    }
}
//End common toggle radio function


function Netscape2()
{
	return((self.navigator.appName=='Netscape')&&(parseInt(self.navigator.appVersion,10)<3))
}
	
function Explorer2()
{
	return((self.navigator.appName=='Explorer')&&(parseInt(self.navigator.appVersion,10)<3))
}
	
function sendInfoPage(infoPage, infoPageName, width, height)
{
	if ((Netscape2()) || (Explorer2())) return;
	//var sessionid = ';$sessionid$PWX5CVXNNAAVBQFIA3DSGWY';
	//popWindow_=window.open(infoPage + sessionid, infoPageName, "toolbar= no,status=yes,scrollbars=yes,alwaysLowered=0,alwaysRaised=1,directories=no,resizable=yes,resize=yes,menubar=no,height="+height+",width="+width);
	popWindow_=window.open(infoPage, infoPageName, "toolbar= no,status=yes,scrollbars=yes,alwaysLowered=0,alwaysRaised=1,directories=no,resizable=yes,resize=yes,menubar=no,height="+height+",width="+width);
	popWindow_.focus();
}


function popUp(url){
	sealWin=window.open(url,"win",'toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=500,height=450');
	self.name = "mainWin";
}

function checkData(dataStr){
	var espressione = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;	
	if (!espressione.test(dataStr))	{	    
		return false;	
	}else {		
		anno = parseInt(dataStr.substr(6),10);		
		mese = parseInt(dataStr.substr(3, 2),10);		
		giorno = parseInt(dataStr.substr(0, 2),10);				
		var data = new Date(anno, mese-1, giorno);		
		if (data.getFullYear() == anno && data.getMonth() + 1 == mese && data.getDate() == giorno){			
			return true;		
		}else {			
			return false;		
		}	
	}
}


// Funzione interna di servizio che evidenzia il campo in cui è presente il div di errore passato
function highlightField(errorId) {
	var allInps = $(errorId).parentNode.getElementsByTagName('input');
    for (var i = 0; i < allInps.length; i++) {
    	allInps[i].className += ' error_inp';
    }
}

// Funzione interna di servizio che evidenzia i radio in cui è presente il div di errore passato
function highlightRadio(errorId) {
	var allLabels = $(errorId).parentNode.getElementsByTagName('label');
	for (var i = 0; i < allLabels.length; i++) {
		allLabels[i].className += ' error_radio';

	}
}


// ---------------------------------------
// Controllo di validazione per i campi obbligatori.
// Questa funzione restituisce 0 se la proprietà è avvalorata, 1 altrimenti.
// Funziona anche con i gruppi di controlli (nel caso di check-boxes o radio-buttons).
// Sintassi: isMandatory(<proprieta>, <id_div_errore>, <fillOnChange>, <noSelectionValue>)
// dove    : <proprieta> è l'id del controllo associato alla proprietà di cui si vuole controllare l'obbligatorietà
//           (nel caso di check-boxes o radio-button si passa l'array degli id che identificano ciascun elemento)
//           <id_div_errore> è l'id del div di errore utilizzato per la visualizzazione dei messaggi
//			 <fillOnChange> è un valore booleano (OPZIONALE) che indica se la proprietà onChange del controllo può
//			 essere modificata dalla funzione (TRUE) oppure no
//			 <noSelectionValue> è un valore stringa (OPZIONALE) da utilizzare nel caso di combo boxes e che indica 
//			 il value della proprietà nel caso di mancata selezione; nel caso in cui tale proprietà non viene impostata
//			 si assume che il valore della proprietà in caso di mancata selezione sia ''
//			 NOTA: SE VIENE SPECIFICATO IL PARAMETRO 'noSelectionValue', IL PARAMETRO 'fillOnChange' DIVENTA OBBLIGATORIO
// Es.: errore += isMandatory('ownerName', 'ownerNameErr');
//      errore += isMandatory(new Array('ownerSexMale','ownerSexFemale'), 'ownerSexErr');
//		errore += isMandatory('ownerName', 'ownerNameErr', false, '0');
// ---------------------------------------
function isMandatory(propertyId, errorId, fillOnChange, noSelectionValue) {
	if(fillOnChange==null)
		fillOnChange = true;
	if (noSelectionValue==null)
		noSelectionValue = '';
	var errore = 0;
	var groupbuttons = 0;
	var counter = 0;
	if ( $type(propertyId) != 'array' ) {
		// property is not an array
		$(errorId).style.display = 'none';
		if ($(propertyId).value==noSelectionValue) {
			$(errorId).style.display = 'inline';
			errore++;
			highlightField(errorId);
			if($(propertyId).type=='select-one'){
				changeSelectStyle(errorId,fillOnChange);               	
			} else if($(propertyId).type=='text'){
				changeTextStyle(errorId,fillOnChange); 
			}
        }
	} else {
		// property is an array, so it is either a check box or a radio button collection
		errore++;
		$(errorId).style.display = 'none';
		for (counter=0; counter<propertyId.length; counter++) {
			if ($(propertyId[counter]).checked==true) {
				groupbuttons=1;
			}
		}
		errore -= groupbuttons;
		if (errore>0) {
			$(errorId).style.display = 'inline';
			highlightRadio(errorId);
 		}
	}
		
	return errore;
}

function isDateMandatory(strDay, strMonth, strYear, mandatoryErrorId, validationErrorId, minMonthsToCheck, maxMonthsToCheck, fillOnChange) {
		
		if(fillOnChange==null)
			fillOnChange = true;

		var x = 0;

		if(strDay==null || strDay=='' || strMonth==null || strMonth=='' || strYear==null || strYear==''){
			x++;
			changeDateStyle(mandatoryErrorId,fillOnChange);
			$(mandatoryErrorId).style.display = 'inline';
		}

		if(x==0){
			var today = new Date(); 
			var currentYear = today.getFullYear(); 
			var minYear = currentYear - 100;
			var maxYear = currentYear + 100;
			if (strYear.length < 4 || strYear<minYear || strYear>maxYear){
				x++;
				changeDateStyle(validationErrorId,fillOnChange);
				$(validationErrorId).style.display = 'inline';
			}
		}
		if(x==0){
			if(minMonthsToCheck != null && maxMonthsToCheck != null){
				if(!checkDateRange(strDay,strMonth,strYear,minMonthsToCheck,maxMonthsToCheck)){
					x++;
					changeDateStyle(validationErrorId,fillOnChange);
					$(validationErrorId).style.display = 'inline';
				}
			}else if(minMonthsToCheck != null){
				if(checkDateBefore(strDay,strMonth,strYear,minMonthsToCheck)){
					x++;
					changeDateStyle(validationErrorId,fillOnChange);
					$(validationErrorId).style.display = 'inline';
				}
			}else if(maxMonthsToCheck != null){
				if(checkDateAfter(strDay,strMonth,strYear,maxMonthsToCheck)){
					x++;
					changeDateStyle(validationErrorId,fillOnChange);
					$(validationErrorId).style.display = 'inline';
				}
			}
		}
   		return x;
}

// ---------------------------------------------------------------------------------------------------------------
// Funzione che imposta lo stile ad error sulle select ed eventuali input presenti nello stesso div.
// Inoltre imposta una funzione sul change delle select e di eventuali input presenti nello stesso div
// in modo da ripristinare lo stile da error a normal.
// ----------------------------------------------------------------------------------------------------------------
function changeDateStyle(errorId,fillOnChange){
	var allSelects = $(errorId).parentNode.getElementsByTagName('select');
	var allInput = $(errorId).parentNode.getElementsByTagName('input');
    for (var i = 0; i < allSelects.length; i++) {
    	allSelects[i].className += ' error_select';
    	if(fillOnChange){
	        allSelects[i].onchange = function() {
		    	removeClass('error_select', this);
				document.getElementById(errorId).style.display = 'none';
		        for (var j = 0; j < allSelects.length; j++) {
		        	removeClass('error_select', allSelects[j]);
		            allSelects[j].onchange = null;
		        }
		        for (var j = 0; j < allInput.length; j++) {
		        	removeClass('error_inp', allInput[j]);
		            allInput[j].onchange = null;
		        }
	        }
        }
	}
	for (var i = 0; i < allInput.length; i++) {
    	allInput[i].className += ' error_inp';
    	if(fillOnChange){
	        allInput[i].onchange = function() {
		    	removeClass('error_inp', this);
				document.getElementById(errorId).style.display = 'none';
		        for (var j = 0; j < allSelects.length; j++) {
		        	removeClass('error_select', allSelects[j]);
		            allSelects[j].onchange = null;
		        }
		        for (var j = 0; j < allInput.length; j++) {
		        	removeClass('error_inp', allInput[j]);
		            allInput[j].onchange = null;
		        }
	        }
        }
	}
}

// ---------------------------------------
// Controllo di validazione per i campi alfabetici (a-z oppure A-Z).
// Questa funzione restituisce 0 se il campo contiene solo caratteri alfabetici e l'apice, 1 altrimenti.
// ---------------------------------------
function isAlphabetic(propertyName, errorId) {
	$(errorId).style.display = 'none';
	if (!(/^[a-zA-Z' ]*$/.test($(propertyName).value))) {
		$(errorId).style.display = 'inline';
		highlightField(errorId);
		return 1;
	} else {
		return 0;
	}
}

// ---------------------------------------
// Controllo di validazione per i campi numerici (0-9).
// Questa funzione restituisce 0 se il campo contiene solo caratteri numerici, 1 altrimenti.
// ---------------------------------------
function isNumeric(propertyName, errorId) {
	$(errorId).style.display = 'none';
	if (!(/^[0-9]*$/.test($(propertyName).value))) {
		$(errorId).style.display = 'inline';
		highlightField(errorId);
		return 1;
	} else {
		return 0;
	}
}

// ---------------------------------------
// Controllo di validazione per i campi destinati a contenere indirizzi e-mail.
// Questa funzione restituisce 0 se il campo contiene un indirizzo e-mail valido, 1 altrimenti.
// ---------------------------------------
function isEmail(propertyName, errorId) {
	$(errorId).style.display = 'none';
	if ($(propertyName).value!='' && !(/^[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/.test($(propertyName).value))) {
		$(errorId).style.display = 'inline';
		highlightField(errorId);
		return 1;
	} else {
		return 0;
	}
}

// ---------------------------------------
// Controllo sulla lunghezza del valore inserito
// Questa funzione verifica che il valore della proprietà specificata sia compreso negli intervalli consentiti.
// Restituisce 0 se il valore della proprietà rispetta i limiti specificati, 1 altrimenti.
// Sintassi: lengthConstraints(<proprieta>, <id_div_errore>, <minLength>, <maxLength>)
// dove    : <proprieta> è il nome della proprietà di cui si vuole controllare la lunghezza del valore
//           <id_div_errore> è l'id del div di errore utilizzato per la visualizzazione dei messaggi
//			 <minLength> è la lunghezza minima che il valore deve assumere (-1: nessun limite inferiore)
//			 <maxLength> è la lunghezza massima che il valore deve assumere (-1: nessun limite superiore)
// Es.: errore += lengthConstraints('ownerName', 'ownerNameErr',3,30);
// ---------------------------------------
function lengthConstraints(propertyName, errorId, minLength, maxLength) {
	var errore = 0;
	if ($(propertyName).value!='' && (minLength!=-1) && ($(propertyName).value.length < minLength)) {
		$(errorId).style.display = 'inline';
		highlightField(errorId);
		errore = 1;
	}
	if ($(propertyName).value!='' && (maxLength!=-1) && ($(propertyName).value.length > maxLength)) {
		$(errorId).style.display = 'inline';
		highlightField(errorId);
		errore = 1;
	}
	
	return errore;
}

// ---------------------------------------
//funzione che modifica lo stile della select su un change (da error ritorna normale)
// ---------------------------------------
function changeSelectStyle(errorId,fillOnChange){
	var allSelects = $(errorId).parentNode.getElementsByTagName('select');
    for (var i = 0; i < allSelects.length; i++) {
    	allSelects[i].className += ' error_select';
    	if(fillOnChange){
	        allSelects[i].onchange = function() {
		    	//removeClass('error_select', this);
				//document.getElementById(errorId).style.display = 'none';
		        //var allSelects2 = this.parentNode.getElementsByTagName('select');
		        //for (var j = 0; j < allSelects2.length; j++) {
		        //	removeClass('error_select', allSelects2[j]);
		        //    allSelects2[j].onchange = null;
		        //}
		        normalStyle(errorId);
	        }
        }
	}
}

// ---------------------------------------
//funzione che modifica lo stile della textbox su un change (da error ritorna normale)
// ---------------------------------------
function changeTextStyle(errorId,fillOnChange){
	var textBox = $(errorId).parentNode.getElementsByTagName('input');
    if(fillOnChange){
        textBox[0].addEvent("change", function() {
    		//removeClass('error_inp', this);
    		//document.getElementById(errorId).style.display = 'none';
    		normalStyle(errorId);
        });
    }
}

function normalStyle(errorId1,errorId2) {	
    $(errorId1).style.display = 'none';
    if(errorId2 != null)
	    $(errorId2).style.display = 'none';
    var allSelects = $(errorId1).parentNode.getElementsByTagName('select');
   	var allInput = $(errorId1).parentNode.getElementsByTagName('input');
    for (var j = 0; j < allSelects.length; j++) {
       	removeClass('error_select', allSelects[j]);
    }
     for (var j = 0; j < allInput.length; j++) {
       	removeClass('error_inp', allInput[j]);
    }
}

var validi = new Array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
function isNum(str) {
	for (var i = 0; i < str.length; i++) {
		var c = str.charAt(i);
		var valido = false;
		for (var j = 0; j < validi.length && !valido; j++) {
			if (validi[j] == c)
				valido = true;
		}
		if (!valido)
			return false;
	}
	return true;
}
            
function isWord(str) {
	for (var i = 0; i < str.length; i++) {
		var c = str.charAt(i);
		var valido = false;
		for (var j = 0; j < validi.length && !valido; j++) {
			if (validi[j] == c)
				return false;
		}
		return true;
	}
}

var sla;

// ---------------------------------------
//funzioni per la ricerca località
// ---------------------------------------
function locValid(searchLoc, sessionId, defaultValue,modalitySearch) {
	if(defaultValue==null)
		defaultValue = '';
//	var delay = 2000; // impostato a 2 secondi per simulare il caricamento, nel caso reale andrebbe impostato a 300-500 millisecondi per evitare di inviare troppe chiamate al server digitando tanti caratteri di seguito.
	var delay = 500;
    var s1;
    var locVL = $('loc').length;
    sla = $('sel_loc');
    if (s1) clearTimeout(s1);
    if (modalitySearch == null ||  modalitySearch == ''){
 		modalitySearch = 'L';
 	}
	locVL = searchLoc.length;
	if (isNum(searchLoc)) {
        if (searchLoc.length == 5) {
           	if (/^\d{2}[01589]\d{2}$/.test(searchLoc)) {
               	document.getElementById('loading').style.visibility = 'visible';
                s1 = setTimeout('loadLoc("'+searchLoc+'", "cap","'+sessionId+'","'+defaultValue+'","'+modalitySearch+'")', delay); 
                //s1 = loadLoc(searchLoc, "cap", sessionId, defaultValue, modalitySearch); 
            } else {
                $('loading').style.visibility = 'hidden';
                $('sel_loc').disabled = 'disabled';
                s1 = setTimeout('hideLoc()', 500);
            }
        } else {
      		$('loading').style.visibility = 'hidden'; 
    		$('sel_loc').disabled = 'disabled'; 
    		s1 = setTimeout('hideLoc()', 500);
		}
   	} else if(isWord(searchLoc)){
       	$('loading').style.visibility = 'visible';
        s1 = setTimeout('loadLoc("'+searchLoc+'", "loc","'+sessionId+'","'+defaultValue+'","'+modalitySearch+'")', delay);
   	    $('loading').style.visibility = 'visible';
       	$('sel_loc').disabled = 'disabled';
       
   	} else {
       	$('loading').style.visibility = 'hidden'; 
       	$('sel_loc').disabled = 'disabled'; 
       	s1 = setTimeout('hideLoc()', 500);
   	}
}
            
function displayLoc() {
    removeClass( 'error_select', $('sel_loc') );
	$('loc').removeProperty( 'disabled');
	$('loc').addClass( 'text' );
    //$('error2').style.display = 'none';
    $('comboLocalitaError').setStyle( 'display' , 'none' );
    $('loading').setStyle( 'visibility' , 'hidden' );
    $('sel_loc').removeProperty( 'disabled' );
}
            
function hideLoc() {
    $('loading').style.visibility = 'hidden';
    if($('sel_loc').value==null || $('sel_loc').value=='-1' || $('sel_loc').value=='')
	    $('sel_loc').disabled = 'disabled';
/*    var opt = document.createElement('option');
    opt.value = '';
    opt.innerHTML = 'Nessun risultato trovato';
    sla.appendChild(opt);
*/
}

/*
function loadLoc(x,t,idSess,defaultValue) {
	if(t == 'cap'){
		var call = "jsonFactory.searchLocalityByZipCode";
	} else {
		var call = "jsonFactory.searchLocalityByDescription";
	}
    sla.innerHTML = '';
    // Richiesta Ajax ad-hoc per JSON , info -> http://docs.mootools.net/Request/Request.JSON
                
/*
ELIMINARE IL COMMENTO SUPERIORE E INFERIORE PER ATTIVARE LA CHIAMATA REALE 
*/
/*
//	var jsonRequest = new Request.JSON({url: "http://localhost:9081/GlfeWeb/JSON-RPC", 
	var jsonRequest = new Request.JSON({url: host, 
		data: JSON.encode({"id":2,"method":call,"params":[x,idSess]}),
		                        
		onRequest: function() {
//			alert("request: " + JSON.encode({"id":2,"method":call,"params":[x,idSess]}));
			$('loading').style.visibility = 'visible';						
			$('loc').disabled = 'true';
	    },
	    onLoading: function() {
	        $('loading').style.visibility = 'visible';
	        $('sel_loc').disabled = 'true';
	    },
	    onComplete: function(jsonItem){
	    	var i = 0;
	    	sla.innerHTML = '';
	        jsonLoc = JSON.decode(jsonItem.result.locs);
	        var opt = document.createElement('option');
	        opt.value = '';
	        opt.innerHTML = selLocalita;
	        sla.appendChild(opt);
	        jsonLoc.each(function(item) {
	            //if ((item.loc).toUpperCase().match(x.toUpperCase())) {
	            if(t == 'loc'){
	                var opt = document.createElement('option');
	                opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
	                if(item.capVis!="")
		                opt.innerHTML = item.loc+', '+item.capVis;
		            else
		            	opt.innerHTML = item.loc;
	            } else 
	            //if ((item.cap).toUpperCase().match(x.toUpperCase())) 
	            {
	            	var opt = document.createElement('option');
	            	//ATTENZIONE! modificare anche CarInsuranceEstimatePrepareAction se si modifica questa parte
			        opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
			        if(item.capVis!="")
	        			opt.innerHTML = item.capVis+', '+item.loc;
	        		else
	        			opt.innerHTML = item.loc;
	    		}
	    		if(defaultValue == opt.value)
					opt.selected = 'selected';
					
	    		sla.appendChild(opt);
	            i++;
				displayLoc();
	        });
	        if(i==0) {
	        	sla.innerHTML = '';
				var opt = document.createElement('option');
				opt.value = '';
				opt.innerHTML = locNotFound;
				sla.appendChild(opt);
				$('loading').style.visibility = 'hidden';
				$('sel_loc').disabled = 'disabled';
				$('loc').disabled = '';
				$('loc').styleClass = 'text';
			} else { 
				displayLoc(); 
			} 
	 //     showLocs();
                            
	}}).send();
/*
ELIMINARE IL COMMENTO SUPERIORE E INFERIORE PER ATTIVARE LA CHIAMATA REALE 


 DA ELIMINARE: JSON SIMULATO: 
punto di partenza 

						jsonLoc = '{ "locs":['+
                            '{"loc" : "Roncade", "cap" : "31056","pr" : "PR", "codLoc" : "E001", "key" : "3608"},'+
                            '{"loc" : "Treviso", "cap" : "31100","pr" : "TV", "codLoc" : "E002", "key" : "3608"},'+
                            '{"loc" : "Cimadolmo", "cap" : "31010","pr" : "RM", "codLoc" : "E003", "key" : "3608"},'+
                            '{"loc" : "Fonte", "cap" : "31010","pr" : "TV", "codLoc" : "E004", "key" : "3608"},'+
                            '{"loc" : "Zenson di Piave", "cap" : "31050","pr" : "PD", "codLoc" : "E005", "key" : "3608"},'+
                            '{"loc" : "Maserada sul Piave", "cap" : "31052","pr" : "PD", "codLoc" : "E006", "key" : "3608"},'+
                            '{"loc" : "Quinto di Treviso", "cap" : "31055","pr" : "TV", "codLoc" : "E007", "key" : "3608"},'+
                            '{"loc" : "Asolo", "cap" : "31010","pr" : "PE", "codLoc" : "E008", "key" : "3608"}]}';
                         jsonLoc = JSON.decode(jsonLoc);
 
                            jsonLoc.locs.each(function(item) {
                                if ((item.loc).toUpperCase().match(x.toUpperCase())) {
                                    var opt = document.createElement('option');
                                    opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
                                    opt.innerHTML = item.loc+', '+item.cap;
                                    sla.appendChild(opt);
                                } else 
 			                     if ((item.cap).toUpperCase().match(x.toUpperCase())) {
            		                var opt = document.createElement('option');
                    		        opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
                            		opt.innerHTML = item.cap+', '+item.loc;
                            		sla.appendChild(opt);
                        		}
								 displayLoc();
                            });
                            if(sla.innerHTML == "") {
			                    var opt = document.createElement('option');
			                    opt.value = '';
			                    opt.innerHTML = 'Nessun risultato trovato';
			                    sla.appendChild(opt);
			                    $('loading').style.visibility = 'hidden';
			                    $('sel_loc').disabled = 'disabled';
			                } else { displayLoc(); } 
                            showLocs();

 /*punto di arrivo 
DA ELIMINARE: JSON SIMULATO: 
*/
/*
}
*/

    var indMap = {
		set : function(key,value) {this[key] = value;},
		get : function(key) {return this[key];},
		isEmpty : function (){
			c=0;
   			for(var i in this){c++;}
  			if (c > 3) return false;
  				return true;
			}
		}

function loadLoc(x,t,idSess,defaultValue,modalitySearch) {
	//alert('loadLocNew');
	if(t == 'cap'){
		var call = "jsonFactory.searchLocalityByZipCode";
	} else {
		var call = "jsonFactory.searchLocalityByDescription";
	}
    sla.empty();
	
	/* TODO: remove session id */
	var jsonRequest = new Request.JSON({url: host, 
		data: JSON.encode({"id":2,"method":call,"params":[x,idSess,modalitySearch]}),
		                        
		onRequest: function() {
//			alert("request: " + JSON.encode({"id":2,"method":call,"params":[x,idSess]}));
			$('loading').setStyle( 'visibility' , 'visible' );
			$('loc').setProperty( 'disabled' , 'disabled');
	    },
	    onLoading: function() {
	    	$('loading').setStyle( 'visibility' , 'visible' );
			$('loc').setProperty( 'disabled' , 'disabled');
	    },
	    onComplete: function(jsonItem){
	    	var i = 0;
	    	sla.empty();
	        jsonLoc = JSON.decode(jsonItem.result.locs);
	        
	        var sel_localita_option = new Element('option', {
	        	'value':''
	        }).set('html' , selLocalita ).inject( sla , 'top' ) ;
	        
	        jsonLoc.each(function(item) {
	        	var opt = new Element('option');
	        	
	            if( t == 'loc' ){
	                if( item.capVis )
		                opt.set( 'html' , item.loc + ', ' + item.capVis );
		            else
		            	opt.set( 'html' , item.loc );
	            } else {
	            	//ATTENZIONE! modificare anche CarInsuranceEstimatePrepareAction se si modifica questa parte
			       	// opt.value = item.loc+', '+item.cap+', '+item.pr+', '+item.codLoc+', '+item.key;
			        if( item.capVis )
	        			opt.set( 'html' , item.capVis + ', ' + item.loc );
	        		else
	        			opt.set( 'html' , item.loc );
	    		}
	    		
	    		
             	opt.setProperty( 'value' , item.loc );
	            
	            valoreOpt = item.loc + ', ' + item.cap + ', ' + item.pr + ', ' + item.codLoc + ', ' + item.key;
	            
	            indMap.set( item.loc , valoreOpt );
	    		
	    		if( defaultValue == opt.value )
					opt.setProperty( 'selected' , 'selected' );
					
	    		opt.inject( sla );
	            i++;
	        });

	        if ( !i ) {	// i == 0
	        	sla.empty();
				var opt = new Element('option', {
					'value': ''
				}).set( 'html' , locNotFound ).inject( sla );
				
				$('loading').setStyle('visibility' , 'hidden' );
				$('sel_loc').setProperty( 'disabled' , 'disabled' );
				$('loc').removeProperty( 'disabled' );
				$('loc').addClass( 'text' );
			} else if ( i == 1 ){
	        	sel_localita_option.dispose();
	        }
	        	
			displayLoc(); 
	}}).send();
}

var charCount, oldCharCount, newCharCount;

function checkPasteFF(x,method) {
    newCharCount = x;
    oldCharCount = charCount;
    charCount = newCharCount;
    if(newCharCount != oldCharCount) {
        setTimeout(method,1);
    }
}
function pasteEvent(method) {
    if (navigator.userAgent.match('MSIE')) {
        setTimeout(method,1);
    }
}

// ---------------------------------------
//fine funzioni per la ricerca località
// ---------------------------------------


// ---------------------------------------
//  funzioni per la ricerca professione
// ---------------------------------------
function ricercaProfessioni(searchJob, sessionId, loadingImgId,defaultValue) {
//	var delay = 2000; // impostato a 2 secondi per simulare il caricamento, nel caso reale andrebbe impostato a 300-500 millisecondi per evitare di inviare troppe chiamate al server digitando tanti caratteri di seguito.
	var delay = 500;
    var s1;
    if (s1) clearTimeout(s1);
	if (searchJob.length > 2) {
		if(defaultValue == null)
	 		defaultValue = '';
		s1 = setTimeout('loadProfessioni("'+searchJob+'", "'+sessionId+'", "'+loadingImgId+'", "'+defaultValue+'")', delay);
    } 
}


function loadProfessioni(descrProf,idSession,loadingImgId,defaultValue){
	var jsonRequest = new Request.JSON({url: host, 
					data: JSON.encode({"id":2,"method":"jsonFactory.searchProfessioni","params":[descrProf,idSession]}),
					
					onRequest: function() {
//                        	alert("request: " + JSON.encode({"id":2,"method":"jsonFactory.searchModelsCar","params":[e.value,'dfs',dataImmatricolazione]}));
                            $(loadingImgId).style.visibility = 'visible';
							$('professione').disabled = 'true';
                    },
                    
                    onLoading: function() {
                          //  $('loading').style.visibility = 'visible';
                          $('professione').disabled = 'true';
                    },
                     onComplete: function(jsonItem){                     
                   			$(loadingImgId).style.visibility = 'hidden';
                   			$('professione').innerHTML = '';
							
		                    objson = (JSON.decode(jsonItem.result.jobs));
		                    objson.each(function(item) {	                          
	                            var opt = document.createElement('option');
	                            opt.value = item.codProfess+'#'+item.descrProfess+"#"+item.codGruppoProfess;
	                            opt.innerHTML = item.descrProfess;
	                            if(opt.value == defaultValue){
		                        	opt.selected = 'selected';
	                            }
	                            $('professione').appendChild(opt);
	                            $('professione').disabled = null;                   
		            		});
		            		if($('professione').options.length==0){
			            		var optNothing = document.createElement('option');
								optNothing.value = '';
								optNothing.innerHTML = 'Nessun risultato trovato';
								$('professione').appendChild(optNothing);
								$('professione').disabled = 'disabled';  
		            		}
		            		else{
		            			var optSelect = document.createElement('option');
								optSelect.value = '';
								optSelect.text = 'Seleziona';
								var firstOpt = $('professione').options[0];	
								try {
									$('professione').add(optSelect, firstOpt); 	// standards compliant; doesn't work in IE
								}
								catch(ex) {
									$('professione').add(optSelect, 0); 		// IE only
								}
								//$('professione').selectedIndex	= 0;
								$('professione').disabled = '';
								$('professione').value = defaultValue; 		
		            		}
            		}
	}).send();
}

// ---------------------------------------
//  Fine funzioni per la ricerca professione
// ---------------------------------------



// ---------------------------------------
//  Funzioni per la ricerca indirizzo
// ---------------------------------------
 var oldCivicNumber
 function getAddress(x, defaultValue,autoSelect) {
 	if (oldCivicNumber != x.value){
 		oldCivicNumber = x.value;
	 	$('inpCap').value = '';
	    if(defaultValue == null)
	   		defaultValue = '';
	 	//var oggi = new Date();
	 	//var oggi_str = oggi.getDate() + '/' + (oggi.getMonth()+1) + '/' + oggi.getFullYear();
	 	var s1;
	 	var indirizzo = $('address').value;
	 	var loading_div = $('loadingAddress');
	    if (x.value.length > 0 && indirizzo.length > 0) 
	    {
	    	locVL = indirizzo.length;
	        locV = indirizzo;
	        locAdv.slideIn();
	        showLoading();
	        (s1) ? clearTimeout(s1):void(0);
	                    
	        var pt = $('placeType');
	                    
	        $$('#selLocAdvanced option').each(function(item) {
	        	if(item.value != 0 && item.value != -1) {
	            item.parentNode.removeChild(item);
	            }
	        });
	        
	        //s1 = setTimeout('retriveLocs("'+e.value+'")', 300); // impostato a 3 secondi per simulare il caricamento, nel caso reale andrebbe impostato a 300-500 millisecondi per evitare di inviare troppe chiamate al server digitando tanti caratteri di seguito.
	        s1 = setTimeout('searchAddress("", "' + indirizzo + '", "' + search_provincia + '", "' + search_cap + '", "' + 
	            							search_descloc + '", "' + search_codloc + '", "' + session_id + '", "' + 
	            							loading_div + '", "' +defaultValue + '", "' + autoSelect + '")', 500);
	                    
	    } else if(indirizzo.length <= 1) {
	         return false;
	    }
    }
}            

function showLocs() {
	$('loadingAddress').fade('out');
    $('locAdvanced').fade('in');
}

function showLoading() {
	$('loadingAddress').fade('in');
    $('locAdvanced').fade('out');
    locAdv.slideIn();
    
}



/** old management */

function searchAddress(dataDecorrenza, searchAddress, provincia, zipCode, localityDesc, localityCode, sessionId, loadingImgId, defaultValue,autoSelect){
   var jsonRequest = new Request.JSON({url: host, async: false,
					data: JSON.encode({"id":2,"method":"jsonFactory.searchAddress","params":[dataDecorrenza, searchAddress, provincia, zipCode, localityDesc, localityCode, sessionId]}),
					
					onRequest: function() {
						showLoading();
                    },
                    
                    onLoading: function() {
                    	showLoading();
                    },
                     onComplete: function(jsonItem){
                     	
                     	$('selLocAdvanced').innerHTML = ''; 
                     	var opt0 = document.createElement('option');
		                opt0.value = "0";
		                opt0.innerHTML = selAddress;
		                $('selLocAdvanced').appendChild(opt0);
		                
		                var opt1 = document.createElement('option');
		                opt1.value = "-1";
		                opt1.innerHTML = addrNotFound;
		                $('selLocAdvanced').appendChild(opt1);
                     
	                    objson = (JSON.decode(jsonItem.result.indirizzi));
	                    k = 1;
	                    if(objson!=null && objson != '') {
		                    objson.each(function(item) {	                          
		                        var opt = document.createElement('option');
		                        opt.value = item.address+'#'+item.addressSpec+'#'+item.addressZipCode;
								opt.innerHTML = item.addressSpecDesc + ' ' + item.address + ' ' + item.addressZipCode + ' ' + item.positionDesc;
		                        $('selLocAdvanced').appendChild(opt);
		                        $('selLocAdvanced').disabled = null;

		                     	showLocs();
		                     	if(defaultValue!='')
		                     	{
		                     		var addrSel = $('selLocAdvanced').options;
									for (var j = 0; j < addrSel.length; j++) 
									{
								        if(addrSel[j].value == defaultValue) 
								        {
								          	addrSel[j].setAttribute('selected',true);
								          	
								        }
								    }
							        if(addrSel.value=="")
									{
									    for (var j = 0; j < addrSel.length; j++) {
								        	if(addrSel[j].value == '-1') 
								        	{
								          		addrSel[j].setAttribute('selected',true);
									       	}
								        
								    	}
									}
		                     	}
		                     	if (autoSelect == '1' && item.selected == '1')
		                     	{
		                     		//$('selLocAdvanced').selectedIndex = k
		                     		opt.setAttribute('selected',true);
		                     	}	
		                     		//$('selLocAdvanced').value = defaultValue;
		                     		setTimeout('checkCap($("selLocAdvanced"))',1);
		                    });
                       } else {
	                       	$('selLocAdvanced').disabled = null;
	                       	showLocs();
                       }
            		}
	}).send();
}













// Scope chain
(function(){
/*[
	dataDecorrenza, 
	searchAddress, 
	provincia, 
	zipCode, 
	localityDesc, 
	localityCode, 
	sessionId
]*/	
	//function searchAddress(dataDecorrenza, searchAddress, provincia, zipCode, localityDesc, localityCode, sessionId, loadingImgId, defaultValue,autoSelect){
	
	// private function
	function _searchLocality( combo , params , method, finish /*date, address, prov, zip, desc, code*/ ){ //, defaultValue, autoSelect){
		combo = $(combo); // force: combo extends mootools functions
		params.type = params.type || 'LOC';
		return new Request.JSON({ //async: false,
	   		url: host,
			data: JSON.encode({
				id:2, method: method || "jsonFactory.searchAddress", params: params.data
			}),
					
			onRequest: function() {
				/* empties combo and insert default options */
				var info_address = new Element('option',{value:''}).set('html', ( params.type == 'CAP' ) ? selLocalita : selAddress );
				combo.empty().adopt([
					info_address
				]).setProperty('disabled','disabled');
				
				/* binding */
				combo._info_address = info_address;
				
				/* Show the 'loading' image */
				$( 'loading_' + combo.id ).setStyle('visibility', 'visible');
				
			},
	        onCancel: function(){
	        	/* Hide the 'loading' image */
				$( 'loading_' + combo.id ).setStyle('visibility', 'hidden');
	        },
	        onFailure: function(){
	        	/* Hide the 'loading' image */
				$( 'loading_' + combo.id ).setStyle('visibility', 'hidden');
	        },
	        onComplete: function(rsp){
				
				/*$('selLocAdvanced').innerHTML = ''; 
	            var opt0 = document.createElement('option');
				opt0.value = "0";
		        opt0.innerHTML = selAddress;
		        $('selLocAdvanced').appendChild(opt0);
		          
		        var opt1 = document.createElement('option');
		        opt1.value = "-1";
		        opt1.innerHTML = addrNotFound;
		        $('selLocAdvanced').appendChild(opt1);*/
	             
	            /* compatibility */
				var objson = JSON.decode(rsp.result.indirizzi || rsp.result.locs);	// force: returned string become an object
				
				combo.erase('disabled');	// enable combobox
				
				if( objson.length ){
	            	// inject new options into combo
					objson.each(function(item){
						var opt = new Element('option',{}).inject( combo );
						switch(params.type){
							case 'CAP':
								opt.set({
									value: [ item.loc , item.cap , item.pr , /*item.codLoc*/ '#' , item.key ].join(','),
									html: item.capVis ?  item.capVis + ', ' + item.loc : item.loc
								});
								break;
							case 'LOC':
								opt.set({
									value: [item.address, item.addressSpec, item.addressZipCode].join('#'),
									html: [item.addressSpecDesc,item.address,item.addressZipCode,item.positionDesc].join(' ')
								});
								break;
						}
					});
					
					/*var opt = document.createElement('option');
	                opt.value = item.address+'#'+item.addressSpec+'#'+item.addressZipCode;
					opt.innerHTML = item.addressSpecDesc + ' ' + item.address + ' ' + item.addressZipCode + ' ' + item.positionDesc;
	                $('selLocAdvanced').appendChild(opt);*/
					
					
				} else {
					// no address found, autoselect
					var no_address = new Element('option',{value:'-1',selected:true}).set('html',( params.type == 'CAP' ) ? locNotFound : addrNotFound );
					combo.adopt( no_address )._no_address = no_address;
					
					// show only one option
					if ( params.type !== 'LOC' )
						combo._info_address.dispose();
				}
				(finish || function(){})(objson,this);	// callback
				/* Hide the 'loading' image */
				$( 'loading_' + combo.id ).setStyle('visibility', 'hidden');
			}
		}).send();
	}


	// public function
	function searchLocality(combo, params, defaultValue, finish){
	
		combo = $(combo); // force: combo extends mootools functions
			
		$clear(combo._timer);	//	clear old thread
		
		combo._timer = (function(){
			if ( combo._ajax )	// cancel older ajax request
				combo._ajax.cancel();

			combo._ajax = _searchLocality(combo, params, params.method, function(rsp,xhr){
			
				try{delete combo._ajax;}catch(e){combo._ajax=undefined;}	// delete previous ajax object, leak memory
				
				defaultValue = defaultValue || '0';	// default: 'choose_an_address'
				
				// force: stop if at least one of options satisfies the condition
				var result = combo.getElements('option').some(function(opt, i, arr){
					if ( defaultValue.toLowerCase() === opt.value.toLowerCase() )
						return !!opt.set('selected', true );	// force: return true, exit!
					return false;	// continue!
				});
				
				if ( (finish || function(){})(rsp,xhr) === false ) return;
			
				/*var addrSel = $('selLocAdvanced').options;
				for (var j = 0; j < addrSel.length; j++) {
					if(addrSel[j].value == defaultValue){
						addrSel[j].setAttribute('selected',true);
					}
	 			}
				if(addrSel.value==""){
					for (var j = 0; j < addrSel.length; j++) {
						if(addrSel[j].value == '-1'){
							addrSel[j].setAttribute('selected',true);
						}
					}
				}*/
	
				/*if (autoSelect == '1' && item.selected == '1'){
		        	//$('selLocAdvanced').selectedIndex = k
					opt.setAttribute('selected',true);
				}
		        //$('selLocAdvanced').value = defaultValue;*/
		        
		        // TODO: check if required
		        //setTimeout('checkCap($("selLocAdvanced"))',1);
			});
		}).delay(100);	// TODO: check if required
	};
	
	
	
	window.localities_by_zipcode = function(cap,combo,type,defaultValue,finish){
		cap = $(cap) || cap;
		cap = cap.value || cap;
		combo = $(combo);
		if ( /^\d{2}[01589]\d{2}$/.test(cap) ) {
			searchLocality(combo,{
				method: 'jsonFactory.searchLocalityByZipCode',
				data:[ cap , "" ,  type ],  // Compatibility: second parameter is not used
				type: 'CAP'
			},defaultValue,function(rsp,xhr){
				// autoselect locality if only one was found
				if ( combo.getElements('option').length == 2 )
					combo._info_address.dispose();
					
				(finish||function(){})(rsp,xhr);
			});
		} else {
			// disable combobox
			combo.set('disabled','disabled');
		}
		return true;
	};
	
	
	/*
		String address, String prov, String zipCode, String localityDesc, String localityCode
	*/
	
	window.localities_by_address = function(combo,address,prov,cap,localityDesc,localityCode,defaultValue,finish){
            address = $(address) || address;
            address = address.value || address;
            combo = $(combo);
            
            if ( !$('inpNCivico').value ) return;
            
            if ( address ){
                  searchLocality(combo,{
                        data:[ "", address, prov, cap, localityDesc, localityCode, "" ],
                        type: 'LOC'
                  },defaultValue,function(rsp,xhr){
                        // binding
                        if (  !(combo._no_address && combo._no_address.getParent() ) ){
	                        var no_address = new Element('option',{value:'-1'}).set('html',addrNotFound);
	                        combo._no_address = no_address.injectAfter( combo._info_address );
                        }
                        
                        (finish || function(){})(rsp,xhr);
                  });
            } else {
            
            }
      };
	
	window.select_address = function(combo,topon,address,cap,finish){
            combo = $(combo);
            topon = $(topon);
            address = $(address);
            cap = $(cap);
            var option = combo.options[ combo.selectedIndex ];
            if ( option.value && ( option !== combo._no_address ) ){
                  // an option is selected correctly
                  var values = option.value.split('#');
                  address.value = values[0];
                  topon.getElements('option').some(function(opt){
                        if ( opt.value == values[1] )
                              return !!opt.set('selected',true);  // break
                        return false;
                  });
                  cap.value = values[2];
            }
            (finish||function(){})( option.value && ( option !== combo._no_address ) , option ); // callback
      };
	
	

})();

             
 


// ---------------------------------------
//  Fine funzioni per la ricerca indirizzo
// ---------------------------------------

// ---------------------------------------
//  Funzione per l'aggiornamento delle select
//  Rimuove il campo 'seleziona' se la select è già stata selezionata
// ---------------------------------------
function updateSelectList(selectList) {
	for (i=0; i<selectList.length; i++) { 
		if($(selectList[i])!=null && $(selectList[i]).value!=''){
		$$('#'+selectList[i]+' option').each(function(item) {
    		if(item.value == '') {
        		item.parentNode.removeChild(item);
        	}
	    });
		} 
		
	}
}
// ---------------------------------------
//  Fine funzione per l'aggiornamento delle select
// ---------------------------------------

// ---------------------------------------
//  Funzione per disabilitare l'inserimento di caratteri 
//	non numerici in un input text
// ---------------------------------------
function isNumberKey(evt)
      {
        var charCode = (evt.which) ? evt.which : evt.keyCode
        return isNumberKeyBase(charCode);
      }
      
function isNumberKeyBase(charCode){
	if (charCode > 31 && (charCode < 48 || charCode > 57) && 
			charCode != 46 && charCode != 37 && charCode != 39)
	   return false;
	return true;
}

// ---------------------------------------
//  fine funzione 
// ---------------------------------------

// ---------------------------------------
//  Wrapper per la classe Fx.Slide di Mootools.
//	Risolvo il problema della sovrapposizione dei div di errore nelle pagine che 
//  utilizzano gli effetti di slide fra più div.
// ---------------------------------------
CustomSlide = new Class({

	Extends: Fx.Slide,
	
	/*initialize:function(element,options){
		this.parent(element,{link:'chain'});
	},*/
	
	onComplete: function(){
        if(this.wrapper.offsetHeight != 0)
        	this.wrapper.setStyle('height', 'auto');
	}, 

	slideIn: function(mode){
		this.element.style.display = 'inline';
		this.open = true;
		return this.start('in', mode);
	},
	
	slideOut: function(mode){
		this.open = false;
		return this.start('out', mode);
	},
	
	show: function(mode){
		this.element.style.display = 'inline';
		this[mode || this.options.mode]();
		this.open = true;
		return this.set([0, this.offset]);
	}
})
// ---------------------------------------
//  fine funzione 
// ---------------------------------------

// ---------------------------------------
//  Funzione per pulire gli errori (sia div che stili associati ai vari controlli) nelle pagine con varianti 
//	da richiamare nel checkForm prima di eseguire i controlli di validità
//	Per aggiungere altri stili da rimuovere modificare l'array errorStyles
// ---------------------------------------
function cleanErrorInPage(){
	var allErrors = $$('.error');
	var errorStyles = new Array('error_select', 'error_inp', 'error_radio');
	
	//nascondo i div di errore
	for (var i = 0; i < allErrors.length; i++) {
	    allErrors[i].style.display = 'none';
	}
	
	//elimino gli stili di errore
	for (var j = 0; j < errorStyles.length; j++){
		var styleName = errorStyles[j];
		var errorStyleObjects = $$('.' + styleName);
		for (var i = 0; i < errorStyleObjects.length; i++) {
		    removeClass(styleName, errorStyleObjects[i]);
		}
	}
}
// ---------------------------------------
//  fine funzione 
// ---------------------------------------


// ---------------------------------------
//  Funzione che controlla se il cap/zipcode passato come parametro è zonato (esempio 70100) 
//	avvalora la variabile checkZonato con il ritorno del controllo
// ---------------------------------------

var checkZonato = false;

function checkCapZonato(zip, sessionId)
{
	var jsonRequest = new Request.JSON({url: host, async:false,
		data: JSON.encode({"id":2,"method":"jsonFactory.isCapZonato","params":[zip, sessionId]}),
					
	onRequest: function() {
    },
                    
    onLoading: function() {
    },
                    
    onComplete: function(jsonItem){                     
               				                    
		objson = (JSON.decode(jsonItem.result.isZon));
		objson.each(function(item) {	 
	    	checkZonato = item.isZonato;
		});
	}
	}).send();
}
// ---------------------------------------
//  fine funzione 
// ---------------------------------------

// ---------------------------------------
//  Funzione che controlla se la partita IVA è in un formato valido 
//	restituisce un booleano
// ---------------------------------------

var validPIVA;

function checkPartitaIVA(partitaIVA, sessionId)
{
	var jsonRequest = new Request.JSON({url: host, async: false,
		data: JSON.encode({"id":2,"method":"jsonFactory.isValidPIVA","params":[partitaIVA, sessionId]}),
					
	onRequest: function() {
    },
                    
    onLoading: function() {
    },
                    
    onComplete: function(jsonItem){                     
               				                    
		objson = (JSON.decode(jsonItem.result.risultato));
		objson.each(function(item) {	 
	    	validPIVA = item.isValidIVA;
		});
	}
	}).send();
}
// ---------------------------------------
//  fine funzione 
// ---------------------------------------

// ---------------------------------------
//  Funzione che controlla se il valore Presso è accettabile 
//	restituisce un booleano
// ---------------------------------------

var validPresso;

function checkPresso(presso)
{
	var jsonRequest = new Request.JSON({url: host, async: false,
		data: JSON.encode({"id":2,"method":"jsonFactory.checkPresso","params":[presso]}),
					
	onRequest: function() {
    },
                    
    onLoading: function() {
    },
                    
    onComplete: function(jsonItem){                     
               				                    
		objson = (JSON.decode(jsonItem.result.risultato));
		objson.each(function(item) {	 
	    	validPresso = item.isValidPresso;
		});
	}
	}).send();
}
// ---------------------------------------
//  fine funzione 
// ---------------------------------------

// ---------------------------------------
//Funzione per la validazione del Codice Fiscale
// ---------------------------------------
var validCF;

function checkCF(cf,nome,cognome,sesso,tipoSoggetto,dataNascita,sessionId) {
	var call = "jsonFactory.checkCF";
    // Richiesta Ajax ad-hoc per JSON , info -> http://docs.mootools.net/Request/Request.JSON
                
/*
ELIMINARE IL COMMENTO SUPERIORE E INFERIORE PER ATTIVARE LA CHIAMATA REALE 
*/
//	var jsonRequest = new Request.JSON({url: "http://localhost:9081/GlfeWeb/JSON-RPC", 
	var jsonRequest = new Request.JSON({url: host, async:false,
		data: JSON.encode({"id":2,"method":call,"params":[cf,nome,cognome,sesso,tipoSoggetto,dataNascita,sessionId]}),
		                        
		onRequest: function() {
	    },
	                    
	    onLoading: function() {
	    },
    	onComplete: function(jsonItem){
			objson = (JSON.decode(jsonItem.result.risultato));
			objson.each(function(item) {	 
		    	validCF = item.isValidCF;
		});
                            
	}}).send();

}
// ---------------------------------------
//fine funzioni per la validazione del Codice Fiscale
// ---------------------------------------

/*
* Funzione per disabilitare i controlli di input in pagina (link e submit) per evitare il doppio submit. La root rappresenta la radice da cui iniziare la ricerca
*/
function disableControls(root){
	
	/*var tags = root.getElementsByTagName('A');
	for (var x = 0; x < tags.length; x++) {
		tags[x].setProperty('href','javascript:void(0)');
	}
	var mytag = "";
	tags = root.getElementsByTagName('INPUT');
	for (var x = 0; x < tags.length; x++) {
		mytag = tags[x].type;
		if (mytag == 'button' || mytag == 'submit') {
			tags[x].disabled = "disabled";
		}
	}*/
	
	var modalHeight = "";
	var modalWidth = "";
	
	if (!Browser.Engine.gecko) {
		position = 'absolute';
		modalHeight = document.getElementsByTagName('body').item(0).clientHeight * 2;
		modalWidth = document.getElementsByTagName('body').item(0).clientWidth;
	}
	else {
		position = 'fixed';
		modalHeight = window.innerHeight * 2;
		modalWidth = window.innerWidth;
	}

	var modal = new Element('div', {
	'styles': {
		'position': position,
		'top': '0px',
		'left': '0px',
		'background': '#ffffff',
		'z-index': '99999'
	}
	}).injectInside($(document.body));
	modal.id = 'mod';
	if (Explorer())
		modal.setStyle('opacity', 0.1);
	else modal.setStyle('background-color', 'transparent'); 
	
	//alert(modalHeight + " " + modalHeight);
	modal.setStyle('height', modalHeight);
	modal.setStyle('width', modalWidth);
}

function Explorer()
{
	return(self.navigator.appName.contains('Explorer', ' '));
}

//Funzione per google analitycs
function traccia(elemento,pagina,etichetta) {
 if(elemento.tagName=='LABEL')
 {
 		pageTracker._trackEvent(pagina, elemento.getElementsByTagName('input')[0].name+"_"+elemento.getElementsByTagName('input')[0].value, etichetta);
 		
 }
 else
 {
	 if(elemento.value!='')
	 {
	 	pageTracker._trackEvent(pagina, elemento.name+'_riempito',  etichetta);
	 	
	 }
	 else
	 {
	 	pageTracker._trackEvent(pagina, elemento.name+'_vuoto',  etichetta);
	 	
	 }
 
 }
}

function checkTarga(targaText) {
		
		var targa = targaText.value;
		var targa = targa.toLowerCase();
			
			if (targa.slice(0,3) == "rsm") {
			var targa = "RSM" + targa.substr(3);
			//document.getElementById('error_msg').style.display = 'none';
			document.getElementById('targa1').value = targa;
			document.getElementById('targa1').disabled = false;
			return true;
			}

			else if (targa.slice(0,3) == "scv") {
			var targa = "SCV" + targa.substr(3);
			//document.getElementById('error_msg').style.display = 'none';
			targaText.value = targa;
			targaText.disabled = false;
			return true;
			}
			
			else if (targa.slice(0,4) == "roma") {
			var targa = "RM" + targa.substr(4);
			//document.getElementById('error_msg').style.display = 'none';
			targaText.value = targa;
			targaText.disabled = false;
			return true;
			}
			
						
			//var pattern = /[A-Za-z]{2}[0-9]{3}[A-Za-z]{2}/;		
			var pattern = /[a-zA-Z]{2} *\d{6}|[a-zA-Z]{2} *\d{3} *[a-zA-Z]{2}|[a-zA-Z]{2}[a-zA-Z]{2}[0-9]{6}|[a-zA-Z]{2}[0-9]{1}[a-zA-Z]{5}|[a-zA-Z]{2}[a-zA-Z]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{1}[a-zA-Z]{1}[0-9]{4}|[a-zA-Z]{2}[0-9]{5}[a-zA-Z]{1}|[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{1}[0-9]{3}/;
			
			if (pattern.test(targa) == false) {
				
				function clear_input () {
				    this.value = "";
				    this.onfocus = null;
				    this.removeClass('error_msg');
            this.style.textTransform = 'uppercase';
				}

				//alert ("inserire il numero di targa corretto ed eliminare gli spazi");
        targaText.style.textTransform = 'none';
				targaText.value = "errore targa";
				targaText.addClass('error_msg');
				targaText.onfocus = clear_input;
				
				//document.getElementById('error_msg').style.display = 'block';
				//document.getElementById('targa1').disabled = false;
				return false;
			}
			
			else {				
				//document.getElementById('error_msg').style.display = 'none';
				targaText.value = targa;
				targaText.disabled = false;}
			//alert ("numero targa corretto");			
		//checkTarga ()
		}
		
		
function formatTarga(x) {
  if (x.value.length <= 2) {
    x.value = x.value.replace(/\d/,'');
  }
}