
var edit;

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Il formato della data deve essere : gg/mm/aaaa")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Prego inserire mese valido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Prego inserire giorno valido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Prego inserire anno a quattro cifre compreso tra "+minYear+" e "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Prego inserire data corretta")
		return false
	}
return true
}
var dit = null;

function validaData(dt) {
	if (dt.value == "") return; // vuota e' accettabile
	if (isDate(dt.value)==false){
		dit = dt;
		setTimeout('dit.focus()',100)
		// dt.select();
		// dt.focus();
	}
}

/* 
function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
*/



function indietro(from){
	document.forms[0].action=from;
	document.forms[0].submit();
}


function check(oggetto){
	if(oggetto.checked==true)
		{
		oggetto.checked==true;
		oggetto.value='true';
		}
	else
		{
		oggetto.checked==false;
		oggetto.value='false';
		}
		document.getElementsByName(oggetto.name).value = oggetto.value;
}

function abilitaCampi(){
	var test = document.forms[0].test;
	if(test.checked==true){
		test.checked=true;
		test.value=true;
		document.getElementById('dis1').disabled=false;
		document.getElementById('dis2').disabled=false;
		document.getElementById('dis3').disabled=false;
		document.getElementById('dis4').disabled=false;
		document.getElementById('dis5').disabled=false;
		document.getElementById('dis6').disabled=false;
		document.getElementById('dis7').disabled=false;
		document.getElementById('dis8').disabled=false;
		document.getElementById('dis9').disabled=false;
		document.getElementById('dis10').disabled=false;
		document.getElementById('dis11').disabled=false;
		document.getElementById("showCertificatoCciaa").style.display = 'block';
	}
	else{
		test.checked=false;
		test.value=false;
		document.getElementById('dis1').value="";
		document.getElementById('dis2').value="";
		document.getElementById('dis3').value="";
		document.getElementById('dis4').value="";
		document.getElementById('dis5').value="";
		document.getElementById('dis6').value="";
		document.getElementById('dis7').value="";
		document.getElementById('dis8').value="";
		document.getElementById('dis9').value="";
		document.getElementById('dis10').value="";
		document.getElementById('dis11').value="";
		document.getElementById('dis1').disabled=true;
		document.getElementById('dis2').disabled=true;
		document.getElementById('dis3').disabled=true;
		document.getElementById('dis4').disabled=true;
		document.getElementById('dis5').disabled=true;
		document.getElementById('dis6').disabled=true;
		document.getElementById('dis7').disabled=true;
		document.getElementById('dis8').disabled=true;
		document.getElementById('dis9').disabled=true;
		document.getElementById('dis10').disabled=true;
		document.getElementById('dis11').disabled=true;
		document.getElementById("showCertificatoCciaa").style.display = 'none';
	}
}





function naviga(arrivo,modificata){
	var navigazione=0;
	try{
	if(confronta_data(document.getElementById('dataCertificatoPresaCaricoVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataNascita(document.getElementById('dataNascitaRichiedenteVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataSuccessiva(document.getElementById('dataScadenzaRichiedenteVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataFattura(document.getElementById('dataFatturaVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			
	if(navigazione==0){
		document.forms[0].action = arrivo;
		document.forms[0].submit();
		
		
	}
}



function allarga(){
	document.getElementById('contentselect').style.width="200px";
		document.getElementById('selectname').style.width="200px";
		}
function stringi(){
	document.getElementById('contentselect').style.width="200px";	
	document.getElementById('selectname').style.width="200px";
	}


function showToolTip(e,text){ 
	var ToolTip = document.getElementById("ToolTip");
	var parteCentrale = document.getElementById("partecentrale");
	// alert(e.screenX + ' - ' + e.screenY);
	// alert(parteCentrale.offsetLeft + ' - ' + parteCentrale.offsetTop);
	ToolTip.innerHTML="<table><tr><td class=ToolTipTD align=\"right\"><img src=\"./img/close.gif\" onclick=\"javascript:hideToolTip();\"></td></tr><tr><td class=ToolTipTD>"+text+"</td></tr></table>"; 
	// ToolTip.style.pixelLeft=(e.x+110+parteCentrale.offsetLeft);
	// ToolTip.style.pixelTop=(e.y-5+parteCentrale.offsetTop);
	ToolTip.style.left=(e.screenX+160-parteCentrale.offsetLeft)+'px'; 
	ToolTip.style.top=(e.screenY+33-parteCentrale.offsetTop)+'px'; 
	ToolTip.style.visibility="visible"; 
} 




function hideToolTip(){ 
var ToolTip = document.getElementById("ToolTip");
ToolTip.style.visibility="hidden"; 
} 


function caricaComboComuni(form){
	var element = event.srcElement;
	form.action=context+"/caricaComuni.do?prov="+element.value;
	alert(form.action);
	form.submit();
}


function caricaComuni(form,ritorno){
	form.action=context+ritorno;
	form.submit();
}


function filtraAnniMesi(form){
	form.action=form.action+"?filtraMeseAnno=yes";
	form.submit();
}

function filtraProduttore(form){
	form.action=form.action+"?filtraProduttore=yes";
	form.submit();
}

function caricaModelli(form,ritorno){
try{
	form.prezzoListinoVis.value='';
	form.contributoVis.value='';
    form.modelloVeicoloNuovo.value='';
    form.omologazione.value='';
    }
    catch(exp){}
	form.action=context+ritorno;
	form.submit();
}

function caricaDatiModello(form,ritorno){
try{
	form.prezzoListinoVis.value='';
	form.contributoVis.value='';
	form.omologazione.value='';
	}
	catch(exp){}
	form.action=context+ritorno;
	form.submit();
}



function caricaDatiOM(form,ritorno){
	form.prezzoListinoVis.value='';
	form.contributoVis.value='';
	// alert(form.prezzoListinoVis.value);
	form.action=context+ritorno;
	form.submit();
}


function formattaNumero(campoImporto){
	var importo = document.getElementById(campoImporto);
	    numero = importo.value;
        if(numero!='Ind'){
	ind = numero.indexOf(",");
        if(numero.length==0){
            numero = "0";
        }
	if(ind==-1){
		numero = numero + ",00";
	}
	else{
	prima = numero.substring(0,ind);
	dopo = numero.substring(ind, numero.length);
	if(dopo.length - 1 == 1)
		{
		dopo = dopo + "0";
		
		}
	if(dopo.length-1 > 2)
		{
			dopo = dopo.substring(0,3);
		}
	
	numero = prima + dopo;
	}
	numero = numero.replace(".","");
        }
	importo.value = numero;
}


function FormatNumber(numero){
	var importo = document.getElementById(numero);
	var test=importo.value
	var strNumber = isNaN (test);
	if (strNumber == true) {
		alert (test+ " Non è un numero!");
		importo.value="";
		}
	else{
		formatCurrency(importo.value);
	}
}

function Trim(stringa){ // Levo eventuali spazi indesiderati
   reTrim=/\s+$|^\s+/g;
   return stringa.replace(reTrim,"");
}
function controlla(codicefiscale){  // Controllo correttezza codice fiscale
    var p=document.getElementById(codicefiscale).value;
    var re = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
    Codice=Trim(p.value.toUpperCase());
    if(!re.test(Codice))
    	alert("Codice Fiscale Non Valido");
}


function calcolaIncentivo(campoIncentivo,campoImporto){
	var incentivo = document.getElementById(campoIncentivo).value;
	var importo = document.getElementById(campoImporto).value;
	importotmp = document.getElementById(campoImporto).value.toString().replace(/\$|\./g,'');
	importotmp = importotmp.toString().replace(/\$|\,/g,'.');
	var totIncentivo = importotmp / 2;
	if(totIncentivo >= 15)
		{
		document.getElementById(campoIncentivo).value=15;
		document.getElementById(campoIncentivo).value=formatCurrency3(document.getElementById(campoIncentivo).value);
		document.getElementById(campoImporto).value=formatCurrency2(document.getElementById(campoImporto).value);
		}
	else
		{
		document.getElementById(campoIncentivo).value=totIncentivo.toString().replace(/\$|\./g,',');
		document.getElementById(campoIncentivo).value=formatCurrency3(document.getElementById(campoIncentivo).value);
		document.getElementById(campoImporto).value=formatCurrency2(document.getElementById(campoImporto).value);
		}
	
}



function formatCurrency(importo) {
	num = document.getElementById(importo).value;
	num = num.toString().replace(/\$|\,/g,'.');
	if(isNaN(num))
		{
		num = "0";
		alert("Importo inserito non numerico");
		}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') +  num + ',' + cents);
}

function formatCurrency2(importo) {
	num = importo.toString().replace(/\$|\./g,'');
	num = num.toString().replace(/\$|\,/g,'.');
	if(isNaN(num))
		{
		alert("Importo inserito non numerico \r\n Correggere tale valore");
		return importo;
		}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') +  num + ',' + cents);
}


function formatCurrency3(importo) {
	num = importo.toString().replace(/\$|\./g,'');
	num = num.toString().replace(/\$|\,/g,'.');
	if(isNaN(num))
		{
		num = "0";
		}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') +  num + ',' + cents);
}





function formatImporto(importo) {
	num = document.getElementById(importo).value;
	document.getElementById(importo).value = formatCurrency2(num)
}


function controllaNumero(campoNumero){
	var num = document.getElementById(campoNumero).value;
	if(isNaN(num))
		{
		alert("Numero non valido");
		document.getElementById(campoNumero).value='';
		}
}



function controllaCap(campoNumero){
	var num = document.getElementById(campoNumero).value;
	var show=0;
	if(isNaN(num))
		{
		alert("Cap non valido. Il cap deve essere di 5 numeri");
		show=1;
	// document.getElementById(campoNumero).value='';
		}
	if(num.length!=5 && show==0)
		alert("Cap non valido. Il cap deve essere di 5 numeri");
}



function confermaAnnulla(href){
	if(confirm("Annullare la  richiesta? \r\n Rispondendo si la richiesta non sarà più modificabile.")){
		document.forms[0].action = href;
		document.forms[0].submit();
	}
}

function salva(href){
	document.forms[0].action = href;
	document.forms[0].submit();
}



function controllaImportoFattura(importoFattura,prezzoListino){
	var fattura = document.getElementById(importoFattura).value;
	fattura = fattura.toString().replace(/\$|\./g,'');
	fattura = fattura.toString().replace(/\$|\,/g,'.');
	var listino = document.getElementById(prezzoListino).value;
	listino = listino.toString().replace(/\$|\./g,'');
	listino = listino.toString().replace(/\$|\,/g,'.');
	if(parseFloat(listino) < parseFloat(fattura))
		{
			alert('Il Prezzo di vendita non può essere maggiore del prezzo di listino');
			// document.getElementById(importoFattura).value='';
		}
}


  function controllasalva(salvata,href){
  	
 	try{
 	if(document.forms[0].modificata.value==1){
 		if(confirm("Uscire dalla richiesta senza salvare?")){
 				document.location.href=href;
 			}
 	}
 	else{
 		document.location.href=href;
 	}
 	}
 	catch(exc){
 		document.location.href=href;
 	}
 }
 
 
 
 
 function navigaValida(arrivo,modificata){
	var navigazione=0;
	try{
	if(confronta_data(document.getElementById('dataCertificatoPresaCaricoVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataNascita(document.getElementById('dataNascitaRichiedenteVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataSuccessiva(document.getElementById('dataScadenzaRichiedenteVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			try{
	if(confronta_dataFattura(document.getElementById('dataFatturaVis').value)==false){
				navigazione = 1;
			}
			}
			catch(exc){}
			
	if(navigazione==0 && controllaInvia(0,arrivo)){
		document.forms[0].action = arrivo;
		document.forms[0].submit();
	}
}
 
 
 
 function controllaInvia(salvata,href){
  	try{
 		if(document.forms[0].modificata.value==0){
 		if(confirm("Non sono state apporate modifiche alla richiesta inviarla comunque?")){
 				return true;
 			}
 		}
 		else{
 			return true;
 		}
 	 }
 	catch(exc){
 		document.location.href=href;
 	}
 }


function settaEdit(){
	edit=1;
	try{
		document.forms[0].modificata.value = edit;
		}
	catch(exc){
	}
	
}


function ControllaCF(cf)
{
	CalcolaCodiceFiscale();
	/*
	var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return '';
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        alert("La lunghezza del codice fiscale non \n"
        +"corretta: il codice fiscale dovrebbe essere lungo\n"
        +"esattamente 16 caratteri.\n");
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
        alert("Il codice fiscale non  corretto:\n"+
            "il codice di controllo non corrisponde.\n");
    */
  }


function controllaPIVA(pi)

{

  if( pi == '' ) return '';

   if( pi.length != 11 )

     alert('La lunghezza della partita IVA non è \r\n' +

     'corretta: la partita IVA dovrebbe essere lunga \r\n' +

     'esattamente 11 caratteri');

   validi = '0123456789';

  
   s = 0;

   for( i = 0; i <= 9; i += 2 )

     s += pi.charCodeAt(i) - '0'.charCodeAt(0);

   for( i = 1; i <= 9; i += 2 ){

     c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );

     if( c > 9 ) c = c - 9;

     s += c;

   }

   if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )

     alert('La partita IVA non è valida \r\n' +

     'il codice di controllo non corrisponde');
}




function controllacfSocieta(pi)

{

  if( pi == '' ) return '';

   if( pi.length != 11 )

     alert('La lunghezza del codice fiscale non è \r\n' +

     'corretta: il codice fiscale dovrebbe essere lungo \r\n' +

     'esattamente 11 caratteri');

   validi = '0123456789';

  

   s = 0;

   for( i = 0; i <= 9; i += 2 )

     s += pi.charCodeAt(i) - '0'.charCodeAt(0);

   for( i = 1; i <= 9; i += 2 ){

     c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );

     if( c > 9 ) c = c - 9;

     s += c;

   }

   if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )

     alert('Il codice fiscale non è valido \r\n' +

     'il codice di controllo non corrisponde');
}

function controllo_data(stringa){
    var espressione = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
          if (!espressione.test(stringa))    {  
              return false;
                  }else{  
                     anno = parseInt(stringa.substr(6),10);
			         mese = parseInt(stringa.substr(3, 2),10);
			         giorno = parseInt(stringa.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;
			                 } 
			        }
	 
 }
 
 function confronta_dataSuccessiva(data1){
 	var currentTime = new Date()
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	if(day<=10)
		day = "0"+day;
	if(month<=10)
		month = "0"+month;	
	var year = currentTime.getFullYear();
	data2 = day + "/" + month + "/" + year;
  	// controllo validità formato data
 	   if(controllo_data(data1) &&controllo_data(data2)){
 	   		// trasformo le date nel formato aaaammgg (es. 20081103)
 	   		data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
 	   		data2str = data2.substr(6)+data2.substr(3, 2)+data2.substr(0, 2);
 	   		// controllo se la seconda data è successiva alla prima
 	   		if (data2str-data1str>0) {
 	   		      alert("La data inserita deve essere maggiore o uguale di quella odierna");
 	   		      return false;
 	        }
 	        else{
 	        	return true;
 	        }
 	   }else{
 	      return true;
 }
}


function confronta_data(data1){
 	var currentTime = new Date()
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	if(day<=10)
		day = "0"+day;
	if(month<=10)
		month = "0"+month;	
	var year = currentTime.getFullYear();
	data2 = day + "/" + month + "/" + year;
  	// controllo validità formato data
 	   if(controllo_data(data1) &&controllo_data(data2)){
 	   		// trasformo le date nel formato aaaammgg (es. 20081103)
 	   		data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
 	   		data2str = data2.substr(6)+data2.substr(3, 2)+data2.substr(0, 2);
 	   		// controllo se la seconda data è successiva alla prima
 	   		if (data2str-data1str<0) {
 	   		      alert("La data inserita deve essere minore o uguale della data odierna");
 	   		       return false;
 	        }
 	        else{
 	        	return true;
 	        }
 	   }else{
 	      return true;
 }
}



function confronta_dataFattura(data1){
 
	// controllo validità formato data
 	   if(controllo_data(data1)){
 	   		// trasformo le date nel formato aaaammgg (es. 20081103)
 	   		data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
 	   		dataMessaEserciziostr = "20090422";
 	   		dataMassimastr = "20090513";
 	   		// controllo se la seconda data è successiva alla prima
 	   		if (data1str<dataMessaEserciziostr || data1str >dataMassimastr) {
 	   		      alert("La data inserita deve essere maggiore del 22-04-2009 e minore del 14-05-2009");
 	   		       return false;
 	        }
 	        else{
 	        	return true;
 	        }
 	   }else{
 	      return true;
 }
}


 function confronta_dataNascita(data1){
 	var currentTime = new Date()
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	if(day<=10)
		day = "0"+day;
	if(month<=10)
		month = "0"+month;	
	var year = currentTime.getFullYear();
	data2 = day + "/" + month + "/" + year;
 	// controllo validità formato data
 	   if(controllo_data(data1) &&controllo_data(data2)){
 	   		// trasformo le date nel formato aaaammgg (es. 20081103)
 	   		oggiNascita = parseInt(data2.substr(6),10)-14;
 	   		data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
 	   		data2str = oggiNascita+data2.substr(3, 2)+data2.substr(0, 2);
 	   		// controllo se la seconda data è successiva alla prima
 	   		if (data2str-data1str<=14) {
 	   		      alert("Il Richiedente deve avere almeno 14 anni");
 	   		      return false;
 	        }else{
 	        	return true;
 	         }
 	   }else{
 	   return true;
 }
}

function resettaMsg(){
	var form = document.getElementById('messaggioForm');
	form.action=context+'/messaggio.do?reset=true';
	form.submit();
}


var comunecorrente = "";
var consonanti =  "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
var numeri = "0123456789";
var arrMesi = new Array("A","B","C","D","E","H","L","M","P","R","S","T");


function CalcolaCodiceFiscale()
	{
	var Cognome = "";
	var Nome = "";
	var GiornoNascita = "";
	var MeseNascita = "";
	var AnnoNascita = "";
	var Comune = "";
	var Sesso = "";
	var datanascita = "";
	
	Cognome = document.getElementById('cognome').value;
	Nome = document.getElementById('nome').value;
	datanascita = document.getElementById('dataNascitaRichiedenteVis').value;
	GiornoNascita = datanascita.substring(0,2);
	MeseNascita =arrMesi[Number(datanascita.substr(3,2))-1];
	AnnoNascita = datanascita.substr(6,4);
	Comune = document.getElementById('comune').value;
	Sesso = getCheckedValue(document.forms['RichiestaForm'].elements['sessoRichiedente']);
	codicefiscaleInserito = document.getElementById('codiceFiscale').value;
	// alert(codicefiscaleInserito);
		
   if (Cognome != "" && Nome != "" && Comune != "")
   {
      ComuneCalcolato=CalcolaComune(Comune);
      rc = CalcolaCognome(Cognome);
	  rn = CalcolaNome(Nome)
	  rN = CalcolaNascita(GiornoNascita, MeseNascita, AnnoNascita, Sesso);

      var cf = rc+rn+rN+ComuneCalcolato;

      cf += CalcolaK(rc+rn+rN+ComuneCalcolato);
      if (cf.trim() != codicefiscaleInserito.toUpperCase().trim()) {
    	  alert("ATTENZIONE Il codice fiscale non e' corretto.");
      }

   }
}

function CalcolaCognome(Cognome)
{
   var code = "";
   code = GetConsonanti(Cognome);
   if (code.length >= 3)
      code = code.substring(0, 3);
   else
   {
      code += GetVocali(Cognome).substring(0, 3 - code.length)
      if (code.length < 3)
         for (i = code.length; i < 3; i++)
            code += "X";
   }
   return code;
}

function CalcolaNome(Nome)
{
   var code = "";
   cons = GetConsonanti(Nome);
   if (cons.length > 3)
      code = cons.substring(0, 1) + cons.substring(2, 3) + cons.substring(3, 4);
   else if (cons.length == 3)
      code = cons;
   else
   {
      code = cons + GetVocali(Nome).substring(0, 3 - cons.length);
      if (code.length < 3)
         for (i = code.length; i < 3; i++)
            code += "X";
   }
   return code;
}

function GetConsonanti(Stringa)
{
   var cns = "";
   for (i = 0; i < Stringa.length; i++)
      if (consonanti.indexOf(Stringa.substring(i, i + 1)) != -1)
         cns += Stringa.substring(i, i + 1);
   return cns.toUpperCase();
}

function GetVocali(Stringa)
{
   var voc = "";
   for (i = 0; i < Stringa.length; i++)
      if (consonanti.indexOf(Stringa.substring(i, i + 1)) == -1 && Stringa.substring(i, i + 1) != " ")
         voc += Stringa.substring(i, i + 1);
   return voc.toUpperCase();
}

function CalcolaNascita(Giorno, Mese, Anno, Sesso)
{
   var code = "";
   code += Anno.substring(2, 4) + Mese;
   if (Sesso == "M")
      code += Giorno;
   else
      code += parseInt(40, 10) + parseInt(Giorno, 10);
   return code;
}

function CalcolaComune(comune)
{
		  url = "RicercaCodiceCatastale.do?comune="+comune;
		  if (window.XMLHttpRequest) {              
		    AJAX=new XMLHttpRequest();              
		  } else {                                  
		    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		  if (AJAX) {
		     AJAX.open("GET", url, false);                             
		     AJAX.send(null);
		     return AJAX.responseText;                                         
		  } else {
		     return false;
		  }                                             
 }

function CalcolaK(Stringa)
{
   var somma = 0, k;
   var arrPari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var arrDispari = new Array(
      Array(0,1),
      Array(1,0),
      Array(2,5),
      Array(3,7),
      Array(4,9),
      Array(5,13),
      Array(6,15),
      Array(7,17),
      Array(8,19),
      Array(9,21),
      Array("A",1),
      Array("B",0),
      Array("C",5),
      Array("D",7),
      Array("E",9),
      Array("F",13),
      Array("G",15),
      Array("H",17),
      Array("I",19),
      Array("J",21),
      Array("K",2),
      Array("L",4),
      Array("M",18),
      Array("N",20),
      Array("O",11),
      Array("P",3),
      Array("Q",6),
      Array("R",8),
      Array("S",12),
      Array("T",14),
      Array("U",16),
      Array("V",10),
      Array("W",22),
      Array("X",25),
      Array("Y",24),
      Array("Z",23)
   );
   for (i = 0; i < Stringa.length; i += 2)
   {
      for (j = 0; j < arrDispari.length; j++)
      {
         if (Stringa.substring(i, i + 1).toUpperCase() == arrDispari[j][0])
         {
            somma += parseInt(arrDispari[j][1], 10);
            break;
         }
      }
   }
   for (i = 1; i < Stringa.length; i += 2)
   {
      if (isNaN(Stringa.substring(i, i + 1)))
         somma += parseInt(arrPari.indexOf(Stringa.substring(i, i + 1)), 10);
      else
         somma += parseInt(Stringa.substring(i, i + 1), 10);
   }
   k = somma % 26;
   k = arrPari.charAt(k);
   return k;
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function checkEsistenzaPratica(marca,codicefiscalerivenditore)
{
		  url = "ControlloPraticaMarcaRivenditoreAjaxAction.do?marca="+marca+"&partitaIvaRivenditore="+codicefiscalerivenditore;
		  
		  if (window.XMLHttpRequest) {              
		    AJAX=new XMLHttpRequest();              
		  } else {                                  
		    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		  if (AJAX) {
		     AJAX.open("GET", url, false);                             
		     AJAX.send(null);
		     return AJAX.responseText;                                         
		  } else {
		     return false;
		  }                                             
 }


