//*************************************************************************
//*************************************************************************
//CODICE DI PROPRIETA' DE ILCODICEFISCALE.IT
//E' VIETATO QUALSIASI UTILIZZO E/O RIPRODUZIONE TOTALE O PARZIALE
//
//
//
//THIS CODE IS OWNED BY ILCODICEFISCALE.IT
//IT IS PROHIBITED ANY USE AND/OR REPRODUCTION TOTAL OR PARTIAL
//*************************************************************************
//*************************************************************************
//


var XMLHTTP;

var strCodFis="";
var strNome="";
var strCognome="";
var chrControllo='';
var strGiornoSesso="";
var strAnno="";
var strMese="";
var strLastCoceChecked="";

var SELECT_COMPONENT="<select name='selectcomune' id='selectcomune' align='center' size=3 onChange='updateCountry()' onblur='' style='width:330px;font-size: 12px;'></select>";	

var IMG_BALL_RED="/images/red-ball-small.gif";
var IMG_BALL_GREEN="/images/green-ball-small.gif";

var language="it";
var hostroot="";

/*
it
en
fr
es
de
nl
pt
pl
ro
*/

function addBookmarks(){
  var url   = location.href;
  var title = "IlCodiceFiscale.it";
  if (document.all){
	window.external.AddFavorite(url, title)
  } else if (window.sidebar) {// firefox
	window.sidebar.addPanel(title, url, "");
  }
}


function setLanguage(lingua){
//alert("BN: "+navigator.appName+"\nCN:"+navigator.appCodeName+"\nUA:"+navigator.userAgent);
	if (lingua==""){
		language="it"
	}
	else {
		language=lingua;
	}
}

function cambiaLingua(target){
	this.location.href=target;
}

function setHostRoot(hostrootlocal){
//alert("setHR: "+hostrootlocal);
	hostroot=hostrootlocal;
	IMG_BALL_RED=hostroot+IMG_BALL_RED;
	IMG_BALL_GREEN=hostroot+IMG_BALL_GREEN;
}

function getMsg(msgCode){
	//alert("language: "+language);
	if (language==""){
	language="it"
	}
	if (language=="it"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Attenzione:\n\nDevi abilitare i POPUP nel tuo browser";
				   case "MSG_NOMI": return "Possibili Nomi per il Codice: ";
				   case "MSG_COGNOMI": return "Possibili Cognomi per il Codice: ";
				   case "MSG_CODICE_NON_VALIDO": return "Il Codice Fiscale inserito non è nel formato corretto.\n\nIl Formato corretto prevede questo schema:\n\nAAA.AAA.00.A.00.A000.A\n\nA è un carattere alfabetico\n0 è un carattere numerico oppure L,M,N,P,Q,R,S,T,U,V in caso di omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "Il codice fiscale inserito è omocodico.\n\nSignifica che al momento della registrazione di questo codice fiscale già era presente un'altra persona con lo stesso codice.\n\nPer differenziare i due codici sono state inseriti caratterici alfabetici al posto dei caratteri numerici.";
				   case "MSG_COMUNE_NON_TROVATO": return "COMUNE NON TROVATO";
				   default: return "";
		}
	} else if (language=="en"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Attention:\n\nYou need to turn on the POPUP on your browser";
				   case "MSG_NOMI": return "Possible Names for the Code: ";
				   case "MSG_COGNOMI": return "Possible Surnames for the Code: ";
				   case "MSG_CODICE_NON_VALIDO": return "The Tax Code entered is not in the proper format.\n\nThe correct format if provides with this pattern: \n\nAAA.AAA.00.A.00.A000.A\n\nA is an alphabetic character \n0 is a numeric character or L, M, N, P, Q, R, S, T, U, V for omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "The tax code inserted is omocodico.\n\n This means that when the person register for this tax code already there was another person with the same code.\n\n To differentiate the two codes have been inserted in place of alphabetic characters numeric characters.";
				   case "MSG_COMUNE_NON_TROVATO": return "PLACE NOT FOUND";
				   default: return "";
		}
	} else if (language=="fr"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Attention:\n\nVous devrez peut-etre autoriser les pop-ups sur votre navigateur";
				   case "MSG_NOMI": return "Les noms possibles pour le code: ";
				   case "MSG_COGNOMI": return "Noms de famille possible pour le Code: ";
				   case "MSG_CODICE_NON_VALIDO": return "Le Code fiscal italien entré n'est pas dans le bon format\n\nLe ce régime prévoit le format correct:.\n\nAAA.AAA.00.A.00.A000.A\n\nA est un caractère alphabétique \n0 est un personnage numérique ou L, M, N, P, Q, R, S, T, U, V où omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "Le code des impôts est inséré omocodico.\n\n Cela signifie que lorsque vous vous inscrivez à ce code fiscal déjà il y avait une autre personne avec le même code.\n\n Pour différencier les deux codes ont été inséré à la place des caractères alphabétiques caractères numériques.";
				   case "MSG_COMUNE_NON_TROVATO": return "LIEU NOT FOUND";
				   default: return "";
		}
	} else if (language=="es"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Advertencia:\n\nNo puede ser necesario para permitir los pop-ups en su navegador";
				   case "MSG_NOMI": return "Posibles nombres para el código: ";
				   case "MSG_COGNOMI": return "Apellidos posible que el Código: ";
				   case "MSG_CODICE_NON_VALIDO": return "El Italiano Código Tributario que introdujo no es en el formato correcto\n\nEl este sistema proporciona el formato correcto:.\n\nAAA.AAA.00.A.00.A000.A\n\nA es un carácter alfabético \n0 es un personaje numéricos o de L, M, N, P, Q, R, S, T, U, V donde omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "El código tributario se inserta omocodico.\n\n Esto significa que cuando usted se registra en el código fiscal que ya había otra persona con el mismo código.\n\n Para diferenciar los dos códigos se han insertado en el lugar de los caracteres alfabéticos caracteres numéricos.";
				   case "MSG_COMUNE_NON_TROVATO": return "LUGAR NO SE ENCUENTRA";
				   default: return "";
		}
	} else if (language=="de"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Warnung:\n\nSie können müssen Pop-Ups in Ihrem Browser zulassen";
				   case "MSG_NOMI": return "Mögliche Namen für den Code: ";
				   case "MSG_COGNOMI": return "Familiennamen möglich, dass der Code: ";
				   case "MSG_CODICE_NON_VALIDO": return "Die italienische Abgabenordnung getreten ist nicht im richtigen Format\n\nDie diese Regelung sieht das richtige Format.\n\nAAA.AAA.00.A.00.A000.A\n\nEs ist ein alphabetisches Zeichen \n0 ist ein Zeichen numerischen oder L, M, N, P, Q, R, S, T, U, V wo omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "Die Steuer-Code ist omocodico eingefügt.\n\n Dies bedeutet, dass wenn Sie sich für diese Steuer-Register schon da war eine andere Person mit dem gleichen Code.\n\n Um die beiden Codes unterscheiden haben an Stelle von Buchstaben eingefügt numerische Zeichen.";
				   case "MSG_COMUNE_NON_TROVATO": return "NICHT GEFUNDEN PLACE";
				   default: return "";
		}
	} else if (language=="nl"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Waarschuwing:\n\nU kan nodig zijn om pop-ups toe te staan op uw browser";
				   case "MSG_NOMI": return "Mogelijke namen voor de Code: ";
				   case "MSG_COGNOMI": return "Achternamen mogelijk voor de Code: ";
				   case "MSG_CODICE_NON_VALIDO": return "De Italiaanse CGI ingevoerd, is niet in het juiste formaat\n\nDe deze regeling voorziet in het juiste formaat:.\n\nAAA.AAA.00.A.00.A000.A\n\nEen is een alfabetisch teken \n0 is een teken numerieke of L, M, N, P, Q, R, S, T, U, V indien omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "De belasting-code is ingevoegd omocodico.\n\n Dit betekent dat wanneer u zich inschrijft voor deze belasting code al was er een ander persoon met dezelfde code.\n\n Om de twee codes onderscheiden zijn ingevoegd in plaats van letters numerieke tekens.";
				   case "MSG_COMUNE_NON_TROVATO": return "PLAATS NIET GEVONDEN";
				   default: return "";
		}
	} else if (language=="pt"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Atenção:\n\nVocê pode precisar para permitir pop-ups no seu navegador";
				   case "MSG_NOMI": return "Os nomes possíveis para o código: ";
				   case "MSG_COGNOMI": return "Sobrenomes possível para o código: ";
				   case "MSG_CODICE_NON_VALIDO": return "O italiano entrou Código Tributário não está no formato correto\n\nO este regime prevê o formato correto:.\n\n \nAAA.AAA.00.A.00.A000.A \nA é um caractere alfabético \n0 é um personagem numérico ou L, M, N, P, Q, R, S, U, V onde omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "O código de imposto é inserido omocodico.\n\n Isto significa que quando você se registra para esse código fiscal já havia outra pessoa com o mesmo código.\n\n Para diferenciar os dois códigos foram inseridos no lugar dos caracteres alfabéticos caracteres numéricos.";
				   case "MSG_COMUNE_NON_TROVATO": return "LOCAL NÃO ENCONTRADO";
				   default: return "";
		}
	} else if (language=="pl"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Uwaga:\n\n moze byc konieczne w celu umozliwienia pop-upy w przegladarce";
				   case "MSG_NOMI": return "Mozliwe Nazwy Kod: ";
				   case "MSG_COGNOMI": return "Nazwisko mozliwosc Kod:";
				   case "MSG_CODICE_NON_VALIDO": return "Nazwisko mozliwosc Kod: ";
				   case "MSG_CODICE_OMOCODICO": return "Wloski KP nie jest wpisane w odpowiednim formacie\n\nW tym systemie zapewnia prawidlowy format:.\n\nAAA.AAA.00.A.00.A000.A\n\nA jest znakiem alfabetu \n0 jest znakiem numeryczne lub L, M, N, P, Q, R, S, T, U, V gdzie omocodia)";
				   case "MSG_COMUNE_NON_TROVATO": return "Kodeks podatkowy wprowadza omocodico.\n\n Oznacza to, ze podczas rejestracji ten kod podatku juz nie bylo innej osoby z tego samego kodu.\n\n Aby odróznic dwa kody zostaly wstawione w miejsce liter alfabetu znaków numerycznych.";
				   default: return "";
		}
	} else if (language=="ro"){
		switch (msgCode) {
				   case "MSG_POP_UP": return "Atentie:\n\nEste posibil necesitatea de a permite ferestre pop-up pe browser-ul dvs.";
				   case "MSG_NOMI": return "Nume posibile pentru Cod: ";
				   case "MSG_COGNOMI": return "Numele de familie este posibil pentru a Codului: ";
				   case "MSG_CODICE_NON_VALIDO": return "Italian Codul fiscal a intrat nu este în formatul adecvat\n\nThe acest sistem prevede formatul corect:\n\nAAA.AAA.00.A.00.A000.A\n\nSe este un caracter alfabetic \n0 este un caracter numeric sau L, M, N, P, Q, R, S, T, U, V în cazul în care omocodia)";
				   case "MSG_CODICE_OMOCODICO": return "Codul fiscal se introduce omocodico \n.\nAceasta înseamna ca, atunci când va înregistrati pentru acest cod fiscal deja acolo a fost o alta persoana cu acelasi cod.\n\n Pentru a diferentia cele doua coduri au fost introduse în loc de caractere alfabetice caractere numerice.";
				   case "MSG_COMUNE_NON_TROVATO": return "LOCUL NU GASIT";
				   default: return "";
		}
	}
	
}


function initField(clearTxtCF){
	clearField(clearTxtCF);
	
}

function clearField(clearTxtCF){
	strLastCoceChecked="";
	document.formDatiAnagrafici.txtcognome.value="";
	document.formDatiAnagrafici.txtnome.value="";
	document.formDatiAnagrafici.txtday.selectedIndex=0; 
	document.formDatiAnagrafici.txtmonth.selectedIndex=0; 
	document.formDatiAnagrafici.txtyear.selectedIndex=0;
	document.formDatiAnagrafici.comuneName.value=""; 
	document.formDatiAnagrafici.txtsex[0].checked=false;
	document.formDatiAnagrafici.txtsex[1].checked=false;	
	if (clearTxtCF==1) {
		document.formDatiAnagrafici.txtcodicefiscale.value = "????????????????";
		document.formDatiAnagrafici.txtcognome.focus();
	} else if (clearTxtCF==2) {
		document.formDatiAnagrafici.txtcodicefiscale.value = "";
		document.formDatiAnagrafici.txtcodicefiscale.focus();
	}
	
	updateBtnStatus();
	setImgBall("imgCountry",IMG_BALL_RED);
	
	selComune=document.getElementById("listaComuni");
	if (selComune!=null){
		selComune.innerHTML = SELECT_COMPONENT;
	}
	
	setImageVisible("imgattesa","hidden");
	updateBallColor();
	
	return;
}

function updateBtnStatus(){
	cfnome=document.formDatiAnagrafici.txtnome.value;
	btnNomi=document.getElementById("btnNomi");
	if (cfnome==null || cfnome.length<3){
		//setBtnEnable(btnNomi,"disabled");
		setBtnVisible(btnNomi,"hidden");
	} else {
		//setBtnEnable(btnNomi,"");
		setBtnVisible(btnNomi,"");
	}

	cfcognome=document.formDatiAnagrafici.txtcognome.value;
	btnCognomi=document.getElementById("btnCognomi");
	if (cfcognome==null || cfcognome.length<3){
		//setBtnEnable(btnCognomi,"disabled");
		setBtnVisible(btnCognomi,"hidden");
	} else {
		//setBtnEnable(btnCognomi,"");
		setBtnVisible(btnCognomi,"");
	}
	
	btnCopia=document.getElementById("btnCopy");
	if (navigator.userAgent.indexOf("MSIE")==-1){
		hideBtn(btnCopia);
	}
	
}

function setImageVisible(imgid,visible){
	img=document.images[imgid];
	if (img==null){
		return;
	}
	img.style.visibility = visible; 
}


function hideBtn(btn){
	if (btn==null) {
		return;
	}
	btn.style.display= 'none'
}


function setBtnVisible(btn,visible){
	if (btn==null) {
		return;
	}
	if (btn.style.visibility!=visible){
		btn.style.visibility= visible;
	}
}

function setBtnEnable(btn,disable){
	if (btn==null) {
		return;
	}
	btn.disabled=disable
}



function copyToClipboard(){
	clipboardData.setData('Text',document.formDatiAnagrafici.txtcodicefiscale.value);
	return;
}

function mostraPopUp(w,h,link){
	
   //var w = 420;
   //var h = 600;
   var l = Math.floor((screen.width-w)/2);
   var t = Math.floor((screen.height-h)/2);
   
   var myWin=window.open(link,"","modal=yes,width=" + w + ",height=" + h + ",top=" + t + ",left=" + l);
   if (!myWin) {
		alert(getMsg("MSG_POP_UP"));
   }
        

}

 function trovaDatiAnagrafici(tipo) {
   var w = 420;
   var h = 580;
   var l = Math.floor((screen.width-w)/2);
   var t = Math.floor((screen.height-h)/2);
   var link=hostroot+"/"+language+"/trova_dati_anagrafici.asp?";
   var titolo="";
   
   if (tipo=="nome"){
   	link=link+"cfnome="+document.formDatiAnagrafici.txtnome.value;
 	if (document.formDatiAnagrafici.txtsex[0].checked) {
 		link=link+"&cfsex=M";
 	} else {
 		link=link+"&cfsex=F";
 	}
 	titolo=getMsg("MSG_NOMI")+document.formDatiAnagrafici.txtnome.value;

   }
   else if (tipo=="cognome"){
   	link=link+"cfcognome="+document.formDatiAnagrafici.txtcognome.value;
 	titolo=getMsg("MSG_COGNOMI")+document.formDatiAnagrafici.txtcognome.value;
   }
   var myWin=window.open(link,"","modal=yes,width=" + w + ",height=" + h + ",top=" + t + ",left=" + l);
   if (!myWin) {
	alert(getMsg("MSG_POP_UP"));
   }

 }


function getNameCode(nome){
    for (i=0; i<nome.length; i++) 
       {
        switch (nome.charAt(i)) 
              {
               case 'A':
               case 'E':
               case 'I':
               case 'O':
               case 'U': break;
               default:
		    if((nome.charAt(i)<='Z')&& (nome.charAt(i)>='A'))
		                  strNome = strNome + nome.charAt(i);
                    }
       }
    if (strNome.length > 3) 
      {
        strNome = strNome.substring(0,1) + strNome.substring(2,4);
      } 
    else {
          if (strNome.length < 3) 
            {
             for (i=0; i<nome.length; i++) 
                {
                  switch (nome.charAt(i)) 
                        {
                         case 'A':
                         case 'E':
                         case 'I':
                         case 'O':
                         case 'U': strNome = strNome + nome.charAt(i);
                        }
                }
             if (strNome.length < 3) 
               {
                for (i=strNome.length; i<=3; i++) 
                   {strNome = strNome + 'X';}
               }
            }
          strNome = strNome.substring(0,3);
         }
         
   return strNome;
}


function getSurnameCode(cognome){
    for (i=0; i<cognome.length; i++) 
        {
         switch (cognome.charAt(i)) 
                {
                  case 'A':
                  case 'E':
                  case 'I':
                  case 'O':
                  case 'U': break;            
                  default : 
                  if((cognome.charAt(i)<='Z')&& (cognome.charAt(i)>'A'))
                   strCognome = strCognome + cognome.charAt(i);
                }
        }
    if (strCognome.length < 3) 
      {
       for (i=0; i<cognome.length; i++) 
          {
           switch (cognome.charAt(i)) 
                 {
                  case 'A':
                  case 'E':
                  case 'I':
                  case 'O':
                  case 'U': strCognome = strCognome + cognome.charAt(i);
                 }
          }
       if (strCognome.length < 3) 
         {
          for (i=strCognome.length; i<=3; i++) 
             { strCognome = strCognome + 'X'; }
         }
      }
   strCognome = strCognome.substring(0,3);
   
   return strCognome;	
}

function getDaySexCode(giorno,sesso){
	if (sesso==-1){
		return '??';
	}
	intGiornoSesso = parseInt(giorno) + parseInt((40 * sesso)) ;
	if(intGiornoSesso<10) strGiornoSesso = "0" + intGiornoSesso;
	else strGiornoSesso =  intGiornoSesso;
	
	return strGiornoSesso;
}

function getControlChar(codiceFiscale){
    var somma=0;
    for (i=0; i<15; i++) 
       {
        if (((i+1) % 2) != 0)
          {
           switch (codiceFiscale.charAt(i)) 
                 {
                  case '0':
                  case 'A':{ somma = somma + 1; break;}
                  case '1':
                  case 'B':{ break;}
                  case '2':
                  case 'C':{ somma = somma +  5; break;}
                  case '3':
                  case 'D':{ somma = somma +  7; break;}
                  case '4':
                  case 'E':{ somma = somma +  9; break;}
                  case '5':
                  case 'F':{ somma = somma +  13; break;}
                  case '6':
                  case 'G':{ somma = somma +  15; break;}
                  case '7':
                  case 'H':{ somma = somma +  17; break;}
                  case '8':
                  case 'I':{ somma = somma +  19; break;}
                  case '9':
                  case 'J':{ somma = somma +  21; break;}
                  case 'K':{ somma = somma +  2; break;}
                  case 'L':{ somma = somma +  4; break;}
                  case 'M':{ somma = somma +  18; break;}
                  case 'N':{ somma = somma +  20; break;}
                  case 'O':{ somma = somma +  11; break;}
                  case 'P':{ somma = somma +  3; break;}
                  case 'Q':{ somma = somma +  6; break;}
                  case 'R':{ somma = somma +  8; break;}
                  case 'S':{ somma = somma +  12; break;}
                  case 'T':{ somma = somma +  14; break;}
                  case 'U':{ somma = somma +  16; break;}
                  case 'V':{ somma = somma +  10; break;}
                  case 'W':{ somma = somma +  22; break;}
                  case 'X':{ somma = somma +  25; break;}
                  case 'Y':{ somma = somma +  24; break;}
                  case 'Z':{ somma = somma +  23; break;}
                 }
          } 
        else 
            {
            	if (codiceFiscale.charAt(i)>='0' && codiceFiscale.charAt(i)<='9'){
            		somma=somma+parseInt(codiceFiscale.charAt(i));
        	}
        	if (codiceFiscale.charAt(i)>='A' && codiceFiscale.charAt(i)<='Z'){
        		somma=somma+parseInt(codiceFiscale.charAt(i).charCodeAt(0)-65);
        	}
       
            }
    }
   
   if (somma>0) {
	somma %= 26;
   	chrControllo=String.fromCharCode(65+somma);
   } else {
   	chrControllo='?'
   }
         
   return chrControllo;         	
}

function updateColor(){
	txtCodiceFiscale=document.getElementById("txtcodicefiscale");
	for (i=0; i<16; i++) {
		txtCodiceFiscale.write(txtCodiceFiscale.value.charAt(i).fontcolor("green"));
	}

}

// --------------------------------------------------------------------------
function selectOptionByValue (select, optionValue) {
	for (var i = 0; i < select.options.length; i++) {
		if (select.options[i].value == optionValue) {
			select.options[i].selected=true;
			return;
		}
	}
}

function subStringCf(strSource,from,ncar){
	if (strSource==null){
		return "";
	}
	l=strSource.length;
	if (from>l) {
		return "";
	} else {
		if ((from+ncar)>l){
			return strSource.substring(from);
		} else {
			return strSource.substring(from,from+ncar);
		}
	}
	
}

function hasOmocodeChar(stringa){
	if (stringa.indexOf("L")>-1) return true;
	if (stringa.indexOf("M")>-1) return true;
	if (stringa.indexOf("N")>-1) return true;
	if (stringa.indexOf("P")>-1) return true;
	if (stringa.indexOf("Q")>-1) return true;
	if (stringa.indexOf("R")>-1) return true;
	if (stringa.indexOf("S")>-1) return true;
	if (stringa.indexOf("T")>-1) return true;
	if (stringa.indexOf("U")>-1) return true;
	if (stringa.indexOf("V")>-1) return true;
	
	return false;
}

function replaceOmocodeChar(stringa){
	//0 = L,1 = M,2 = N,3 = P,4 = Q,5 = R,6 = S,7 = T,8 = U,9 = V	
	var result=stringa;
	result=result.replace("L",0);
	result=result.replace("M",1);
	result=result.replace("N",2);
	result=result.replace("P",3);
	result=result.replace("Q",4);
	result=result.replace("R",5);
	result=result.replace("S",6);
	result=result.replace("T",7);
	result=result.replace("U",8);
	result=result.replace("V",9);
	
	return result;
}


function getFiscalData(cf,e){
	clearField(0);

	if (cf==null) {
		return;
	}
	
	cf=cf.toUpperCase();

	if (cf==strLastCoceChecked){
		return;
	} else {
		strLastCoceChecked=cf;
	}
	
	l=cf.length;
	
	
	//alert("GET FISCAL DATA: "+cf+" L:"+l);
	if (l==16) {
		for (var i=0;i<l;i++){
			carattere=subStringCf(cf,i,1);
			codCarattere=carattere.charCodeAt(0);
			//alert("p: "+(i+1)+" carattere: "+carattere+" codice: "+codCarattere+" right: "+isCharOnRightPositionChar(codCarattere,i+1));
			if (!isCharOnRightPositionChar(codCarattere,i+1)){
				alert(getMsg("MSG_CODICE_NON_VALIDO"));
				return;
			}
		}

		omocod_year=cf.substring(6,8);
		omocod_day=cf.substring(9,11);
		omocod_country=cf.substring(12,15);//tralascio la lettera
		if (hasOmocodeChar(omocod_year)||hasOmocodeChar(omocod_day)||hasOmocodeChar(omocod_country)){
			alert(getMsg("MSG_CODICE_OMOCODICO"));
		}
	}


	
	if (l>0){
		//fromCodeSurname=cf.substring(0,3);
		fromCodeSurname=subStringCf(cf,0,3);
		document.formDatiAnagrafici.txtcognome.value=fromCodeSurname;
	}
	if (l>=3){
		//fromCodeName=cf.substring(3,6);
		fromCodeName=subStringCf(cf,3,3);
		document.formDatiAnagrafici.txtnome.value=fromCodeName;
	}
	if (l>=8){
		var data = new Date();
		yearNow=data.getYear().toString();
		yearNow=yearNow.substring(yearNow.length-2);
		
		fromCodeYear=replaceOmocodeChar(cf.substring(6,8));
		
		yearCF="";
		if (parseInt(fromCodeYear)<parseInt(yearNow)){
			yearCF="20"+fromCodeYear;
		} else {
			yearCF="19"+fromCodeYear;
		}
		if (yearCF!="") {
			selectOptionByValue(document.formDatiAnagrafici.txtyear,yearCF);
		}
	}
	if (l>=9){
		fromCodeMonth=cf.substring(8,9).toUpperCase();
		selectOptionByValue(document.formDatiAnagrafici.txtmonth,fromCodeMonth);
	}
	if (l>=11){
		//alert("prima: "+cf.substring(9,11));
		fromCodeDaySex=replaceOmocodeChar(cf.substring(9,11));
		//alert("dopo: "+fromCodeDaySex);
		intCode=parseInt(fromCodeDaySex);
		if (intCode>=40){
			selectOptionByValue(document.formDatiAnagrafici.txtday,intCode-40);
			document.formDatiAnagrafici.txtsex[1].checked=true;
		} else {
			selectOptionByValue(document.formDatiAnagrafici.txtday,intCode);
			document.formDatiAnagrafici.txtsex[0].checked=true;
		}
	}
	if (l>=15){
		fromCodeCountry=cf.substring(11,15);
		handleCountryCode(fromCodeCountry);
	}
	if (l=16){
		fromCodeCheck=cf.substring(16);
	}
	
	updateBtnStatus();
	updateBallColor();

}



function handleCountryCode(countryCode){
	setImageVisible("imgattesa","");
	var url = hostroot+"/ajaxserver.asp?countrycode=" + countryCode.toUpperCase();

	XMLHTTP = initAjax(updateCountryCode);
	XMLHTTP.open("GET", url, true);
	XMLHTTP.send(null);
}

function updateCountryCode()
{
	var COMUNE_NON_TROVATO=getMsg("MSG_COMUNE_NON_TROVATO");
    if (XMLHTTP.readyState == 4)
    {
		risposta=XMLHTTP.responseText;
		indexStart=risposta.indexOf("###");
		indexEnd=risposta.lastIndexOf("###");
		setImageVisible("imgattesa","hidden");
		comune="";

		//alert("indexStart: "+indexStart+" indexEnd: "+indexEnd);
		if (indexStart==-1 || indexEnd==-1){
			comune=COMUNE_NON_TROVATO;
			document.formDatiAnagrafici.comuneName.value=comune;
		}
		else if (indexStart>=0 && indexEnd>=0) {
			comune=risposta.substring(indexStart+3,indexEnd);
			document.formDatiAnagrafici.comuneName.value=comune;
		}
		
		if (comune=="" || comune==COMUNE_NON_TROVATO){
			setImgBall("imgCountry",IMG_BALL_RED);
		} else {
			setImgBall("imgCountry",IMG_BALL_GREEN);
		}

    }
}

function initAjax(functionToCallAfter)
{
    if (navigator.userAgent.indexOf("MSIE") != (-1))
    {
        var Classe = "Msxml2.XMLHTTP";
        if (navigator.appVersion.indexOf("MSIE 5.5") != (-1));
        {
            Classe = "Microsoft.XMLHTTP";
        } 
        try
        {
            OggettoXMLHTTP = new ActiveXObject(Classe);
            OggettoXMLHTTP.onreadystatechange = functionToCallAfter;
            return OggettoXMLHTTP;
        }
        catch(e)
        {
            alert("Errore: l'ActiveX non verrà eseguito!");
        }
    }
    else if (navigator.userAgent.indexOf("Mozilla") != (-1))
    {
        OggettoXMLHTTP = new XMLHttpRequest();
        OggettoXMLHTTP.onload = functionToCallAfter;
        OggettoXMLHTTP.onerror = functionToCallAfter;
        return OggettoXMLHTTP;
    }
    
}

function isCharOnRightPositionChar(keyCode,actualPosition){
	isKeyOk=true;
	switch (actualPosition){
		//Alphabetical
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 9:
		case 12:
		case 16: isKeyOk=isKeyLiteral(keyCode);
				 break;
		
		//Numerical (L,M,N,P,Q,R,S,T,U,V omocodia)
		case 7:
		case 8:
		case 10:
		case 11:
		case 13:
		case 14:
		case 15: isKeyOk=isKeyLiteralOmocodia(keyCode)||isKeyNumeric(keyCode);
				 break;
		
	}
	
	return isKeyOk;
}


function isCharOnRightPosition(e){
	if (isKeyService(e.keyCode)){
		return true;
	} 
	
	if (true){
		return isKeyLiteral(e.keyCode)||isKeyNumeric(e.keyCode);
	}
	
	//alert("CP:"+document.selection.createRange().duplicate());
	//alert("CP: "+document.formDatiAnagrafici.txtcodicefiscale.caretPos);
	
	var actualCf="";
	var actualPosition=0;
	if (document.formDatiAnagrafici.txtcodicefiscale!=null){
		actualCf=document.formDatiAnagrafici.txtcodicefiscale.value;
		actualPosition=actualCf.length;
	}

	actualPosition++;
	
	//alert("actual position: "+actualPosition+" e.keyCode: "+e.keyCode)
	
	return isCharOnRightPositionChar(e.keyCode,actualPosition);
}

function isKeyService(keyCode){
	//alert(keyCode);
	return (keyCode == 8) || (keyCode == 9) || (keyCode == 13) || (keyCode == 46) || (keyCode == 32) || (keyCode == 39) || (keyCode == 219);
}

function isKeyLiteralOmocodia(keyCode) {
	//alert(e.keyCode);
	//L,M,N,P,Q,R,S,T,U,V
	switch (keyCode){
		case 76:
		case 77:
		case 78:
		case 80:
		case 81:
		case 82:
		case 83:
		case 84:
		case 85:
		case 86:
			return true;
	}
	
	return false;
}

function isKeyLiteralEvent(event){
	//alert(event.keyCode);
	return isKeyLiteral(event.keyCode);
}

function isSpace(event){
	return (event.keyCode==32);
}

function isKeyLiteral(keyCode) {
	if ( ((keyCode >= 65) && (keyCode <= 90)) || isKeyService(keyCode)) {
		return true;
	} else {
		return false;
	}
}

function isKeyNumericEvent(event){
	return isKeyNumeric(event.keyCode);
}

function isKeyNumeric(keyCode) {
	// Accetto solo numeri e backspace <-
	//alert(keyCode);
	if ( ((keyCode >= 48) && (keyCode <= 57)) || ((keyCode >= 96) && (keyCode <= 105)) || isKeyService(keyCode)) {
		return true;
	} else {
		return false;
	}
}

function getCountry(patternCountry,e)
{
    setImgBall("imgCountry",IMG_BALL_RED);
    key = getkey(e);
    //38 SU - 40 GIU - 13 INVIO
    //alert(key);
    sel=document.getElementById("selectcomune");
    
    
    if (key==40) {//GIU
    	//sel.options[0].selected=true;
	var selIndex = sel.selectedIndex;
	sel.options[selIndex+1].selected=true;
	updateCountry();
    	sel.focus();

	return;
    } else if (key==38) {//SU
    	if (sel!=null) {
    		si=sel.selectedIndex
    		if (si==0){
    			txtcomune=document.getElementById("comuneName");
    			txtcomune.focus;
    			
    		}
    		//sel.options[si+1].selected=true;
	    	//sel.selectIndex=document.getElementById("selectcomune").selectIndex+1
    	}
    	return;
    } else if (key==13){
    	updateCountry();
//	var selIndex = sel.selectedIndex;
//	if (selIndex>=0) {
//		document.formDatiAnagrafici.comuneName.value=sel.options[selIndex].text;
//		updateCountry();
//	} else {
//		document.formDatiAnagrafici.comuneName.value="";
//	}
	    	
    }
    
    
    if (patternCountry.length > 0)
    {
	setImageVisible("imgattesa","");
	var url = hostroot+"/ajaxserver.asp?countryname=" + patternCountry.toUpperCase();
	XMLHTTP = initAjax(updateCountryList);
	XMLHTTP.open("GET", url, true);
	XMLHTTP.send(null);

    }
    else
    {
    	
    	getFiscalCode();
        document.getElementById("listaComuni").innerHTML = SELECT_COMPONENT;
        
    } 
}

function getCountryWithoutProv(countryname){
	if (countryname==null || countryname=="") return "";
	
	index=countryname.indexOf("(");
	if (index<0) return countryname;
	
	return countryname.substring(0,index-1);
	
}

function updateCountryList()
{
    if (XMLHTTP.readyState == 4)
    {
        var R = document.getElementById("listaComuni");
        R.innerHTML = XMLHTTP.responseText;
	setImageVisible("imgattesa","hidden");

    	sel=document.getElementById("selectcomune");
	if (sel!=null) {
		n=sel.options.length;
		//alert("nn:"+n);
		if (n>0) {
			sel.options[0].selected=true;
			//alert("["+getCountryWithoutProv(sel.options[0].text)+"]");
			//alert(document.formDatiAnagrafici.comuneName.value);
			if (getCountryWithoutProv(sel.options[0].text)==document.formDatiAnagrafici.comuneName.value.toUpperCase()){
				setImgBall("imgCountry",IMG_BALL_GREEN);
			} else {
				setImgBall("imgCountry",IMG_BALL_RED);
			}
			
			//alert("sel.options[0]:"+sel.options[0].value);
		} 
		getFiscalCode();
	} 
        
    }
}

function setImgPreferred(imgid,imgsource){
	setImgBall(imgid,imgsource);
	return;

	var ua="";
	ua=navigator.userAgent;
	ua=ua.toLowerCase();
	//alert("ua: "+ua);
	if (ua.indexOf("chrome")>-1){
		document.removeChild(imgid);
	} else {
		setImgBall(imgid,imgsource);
	}
}

function setImgBall(imgid,imgsource){
	img=document.images[imgid];
	if (img==null){
		return;
	}
	
	//img.src=hostroot+imgsource;
	img.src=imgsource;
	//alert("img: "+(hostroot+imgsource));
}

function updateCountry(){
	sel=document.getElementById("selectcomune");
	if (sel==null) return;
	
	var selIndex = sel.selectedIndex;
	if (selIndex>=0) {
		document.formDatiAnagrafici.comuneName.value=getCountryWithoutProv(sel.options[selIndex].text);
		setImgBall("imgCountry",IMG_BALL_GREEN);
	} else {
		document.formDatiAnagrafici.comuneName.value="";
		setImgBall("imgCountry",IMG_BALL_RED);
	}
	getFiscalCode();
}

function getkey(e){
	if (window.event)
	   return window.event.keyCode;
	else if (e)
	   return e.which;
	else
	   return null;
}


function updateBallColor(){
	if (document.formDatiAnagrafici.txtcognome.value.length>0){
		setImgBall("imgSurname",IMG_BALL_GREEN);
	} else {
		setImgBall("imgSurname",IMG_BALL_RED);
	}

	if (document.formDatiAnagrafici.txtnome.value.length>0){
		setImgBall("imgName",IMG_BALL_GREEN);
	} else {
		setImgBall("imgName",IMG_BALL_RED);
	}
	
	giorno=document.formDatiAnagrafici.txtday.options[document.formDatiAnagrafici.txtday.selectedIndex].value; 
	mese=document.formDatiAnagrafici.txtmonth.options[document.formDatiAnagrafici.txtmonth.selectedIndex].value;
	anno=document.formDatiAnagrafici.txtyear.options[document.formDatiAnagrafici.txtyear.selectedIndex].value; 

	if (giorno!="" && mese!="" && anno!=""){
		setImgBall("imgDate",IMG_BALL_GREEN);
	} else {
		setImgBall("imgDate",IMG_BALL_RED);
	}

	if (document.formDatiAnagrafici.txtsex[0].checked||document.formDatiAnagrafici.txtsex[1].checked){
		setImgBall("imgSex",IMG_BALL_GREEN);
	} else {
		setImgBall("imgSex",IMG_BALL_RED);
	}
	

}

function getFiscalCode()
{
 var intGiornoSesso=0;
 var i=0;
 

 strCodFis="";
 strCognome="";
 strNome="";
 strGiornoSesso="";
 chrControllo='';
 
var _nome='???';
var _cognome='???';
var _giorno='??';
var _mese='?';
var _anno='??';
var _comune='????';
 
 
_nome=document.formDatiAnagrafici.txtnome.value.toUpperCase();
_cognome=document.formDatiAnagrafici.txtcognome.value.toUpperCase();
_giorno=document.formDatiAnagrafici.txtday.options[document.formDatiAnagrafici.txtday.selectedIndex].value; 
_mese=document.formDatiAnagrafici.txtmonth.options[document.formDatiAnagrafici.txtmonth.selectedIndex].value;
_anno=document.formDatiAnagrafici.txtyear.options[document.formDatiAnagrafici.txtyear.selectedIndex].value; 
//_comune=document.formDatiAnagrafici.comuneCode.value; 
   
	if (document.formDatiAnagrafici.txtsex[0].checked){
		_sesso=0
	} else if (document.formDatiAnagrafici.txtsex[1].checked){
		_sesso=1
	} else {
		_sesso=-1
	}
	
	
	if (_cognome==""){
		strCognome='???';
	} else {
		strCognome=getSurnameCode(_cognome);
	}
	
	if (_nome==""){
		strNome='???';
	} else {
		strNome=getNameCode(_nome);
	}   
	
	if (_giorno==Number.NaN || _giorno==""){
		strGiornoSesso='??';
	} else {
		strGiornoSesso=getDaySexCode(_giorno,_sesso);
	}
	
	if (_anno==Number.NaN || _anno==""){
		strAnno='??';
	} else {
		strAnno=_anno.substring(2,4);
	}
	
	if (_mese==Number.NaN || _mese==""){
		strMese='?';
	} else {
		strMese=_mese;
	}
   
	sel=document.getElementById("selectcomune");
	var selIndex = sel.selectedIndex;
	if (selIndex>=0 && document.formDatiAnagrafici.comuneName.value!="") {
		strComune=sel.options[selIndex].value;  
	} else {
		strComune='????';
	}

//   alert("strCognome: "+strCognome+"\n"+"strNome: "+strNome+"\n"+"strAnno: "+strAnno+"\n"+"strMese: "+strMese+"\n"+"strGiornoSesso: "+strGiornoSesso+"\n"+"strComune: "+strComune);
   
   strCodFis = strCognome + strNome + strAnno+ strMese + strGiornoSesso + strComune;
   chrControllo=getControlChar(strCodFis);

document.formDatiAnagrafici.txtcodicefiscale.value = strCodFis + chrControllo;

 updateBallColor();
 return; 
}


