function isCodiceFiscale(cf){
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return false;
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return false;
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return false;
	}
	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) )
		return false;
	return true;
}

function isPartitaIva(pi){
	if( pi == '' )  return false;
	if( pi.length != 11 )
		return false;
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return false;
	}
	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) )
		return false;
	return true;
}

//numero con virgola
function isNumeric(sText){
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
   
   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
         }
      }
   return IsNumber;
}

//numero senza virgola
function isInteger(sText){
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   
   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
         }
      }
   return IsNumber;
}

//questa funzione elimina gli spazi bianchi all'inizio e alla fine di una stringa
function trim(stringa) {
	while (stringa.substring(0,1)==' '){
		stringa = stringa.substring(1, stringa.length);
	}
	while (stringa.substring(stringa.length-1, stringa.length)==' '){
		stringa = stringa.substring(0,stringa.length-1);
	}
	return stringa;
}

//Questa funzione controlla che l'input contenga caratteri:
function isBlank(s){
		s=trim(s);
		for(i=0;i<s.length;i++){
                c=s.charAt(i);
                if((c!=' ')&&(c!='\n')&&(c!='\t'))return false;
        }
        return true;
}

//Questa funzione resituisce true se il numero passato è negativo
function isNegInt(s){
        if (s<0)
                return true;
        else
                return false;
}

//Questa funzione verifica che la password immessa sia almeno 9 caretteri, abbia almeno una maiuscola, almeno un simbolo e almeno due numeri
function pswVerify(s){
	l=s.length;
	if(l<9)
		return false;
	maiu= new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	num=new String("0123456789");
	spec=new String("!$&%?-_:");
	count1=0;
	count2=0;
	count3=0;
	for(i=0;i<l;i++){
		c=s.charAt(i);
		if(maiu.indexOf(c)!=-1)
			count1++;
		if(num.indexOf(c)!=-1)
			count2++;
		if(spec.indexOf(c)!=-1)
			count3++;
	}
	if( (count1>0) && (count2>1) && (count3>0) )
		return true;
	return false;
}

//Questa funzione restituisce true se l'input contiene caratteri speciali.
function isSpecialChar(s) {
        var src = new String(s);
        var lst = new String("\\\"\'\/");
        var i, n;

        n = lst.length;
        for (i=0; i<n; i++) {
                var c = lst.charAt(i);
                var tmpS = new String(c);
                if (src.indexOf(tmpS) != -1) {
                        return true;
                }
        }
        return false;
}

//Questa funzione elimina i caratteri speciali in input
function removeSpecialChar(s,t) {
	for (i=0; i<s.length; i++) {
		s=s.replace("\\",t);
        	s=s.replace("\"",t);
        	s=s.replace("\'",t);
        	s=s.replace("\/",t);
	}
        return s;
}

//Questa funzione sostituisce tutti i caratteri di tipo t nella stringa s coi caratteri di tipo u
function substitute(s,t,u) {
	for (i=0; i<s.length; i++) {
		s=s.replace(t,u);
	}
        return s;
}

//Questa funzione  controlla che l'input non contenga spazi
function nospace(str){
   if (str != ""){
      var index = str.indexOf(" ", 0);
      if (index != -1){
         return false;
      }
   }
   return true;
}

//Questa funzione controlla l'esattezza di un campo mail
function isMail(pino){
   EmailAddr = pino;
   Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
   if (Filtro.test(EmailAddr))
      return true;
   else{
      return false;
      }
   }

function isDate(str) { // anno a 4 cifre !!!
	spz = str.split("/"); 
	dat = new Date(spz[2], spz[1]-1, spz[0]); 
	if	( 
		dat.getFullYear() == parseFloat(spz[2]) &&
		dat.getMonth() == (parseFloat(spz[1])-1) &&
		dat.getDate() == parseFloat(spz[0]) 
		) {
			return dat;
	}
	return false;
}

function controlladate(data1,data2){
 ok=true;
 if(isBlank(data1) && isBlank(data2)){
  ok=false;
  alert("Inserire almeno una data");
 }
 if(!isBlank(data1)&&!isBlank(data2)&&(isDate(data1)>isDate(data2))){
  ok=false;
  alert("Data finale precedente a quella iniziale");
 }
 return ok;
}

function setdate(campo,valore){
	campo.value=valore;
	campo.style.backgroundColor="white";
	document.getElementById("caldiv").style.visibility="hidden";
	document.getElementById("pageblur").style.visibility="hidden";
	e=document.filtro.elements;
	for(var i=0;i<e.length;i++){
		if(e[i].getAttribute("tabindice")!=undefined){
			//alert("tabindice "+e[i].getAttribute("tabindice")+" "+campo.getAttribute("tabindice"));
			if(e[i].getAttribute("tabindice")>campo.getAttribute("tabindice")){
				document.getElementById(e[i].getAttribute("ancid")).focus();
				return;
			}
		}else{
			//alert("tabindex "+e[i].tabIndex+" "+campo.getAttribute("tabindice"));
			if(e[i].tabIndex>campo.getAttribute("tabindice")){
				//alert(e[i]);
				e[i].focus();
				return;
			}
		}
	}
	return;
}

function closedate(campo){
	document.getElementById("caldiv").innerHTML="";
	document.getElementById("caldiv").style.visibility="hidden";
	document.getElementById("pageblur").style.visibility="hidden";
	e=document.filtro.elements;
	for(var i=0;i<e.length;i++){
		if(e[i].getAttribute("tabindice")!=undefined){
			//alert("tabindice "+e[i].getAttribute("tabindice")+" "+campo.getAttribute("tabindice"));
			if(e[i].getAttribute("tabindice")>campo.getAttribute("tabindice")){
				document.getElementById(e[i].getAttribute("ancid")).focus();
				return;
			}
		}else{
			//alert("tabindex "+e[i].tabIndex+" "+campo.getAttribute("tabindice"));
			if(e[i].tabIndex>campo.getAttribute("tabindice")){
				//alert(e[i]);
				e[i].focus();
				return;
			}
		}
	}
	return;
}

//------------------------------------------------------------------------------------------------------------------------------
//suggerimenti
var optionDiv = false;
var optionDiv_iframe = false;
var isMSIE = false;
var posEvid = 0;
var lenEvid = 0;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
document.documentElement.onclick = nascondiOptions;

function posizioneV(campo){
  var returnVal = campo.offsetTop;
  while((campo = campo.offsetParent) != null){
	returnVal += campo.offsetTop;
  }
  return returnVal;
}

function posizioneL(campo){
  var returnVal = campo.offsetLeft;
  while((campo = campo.offsetParent) != null){
	returnVal += campo.offsetLeft;
  }
  return returnVal;
}

function nascondiOptions(){
	if(optionDiv)optionDiv.style.visibility='hidden';	
	if(optionDiv_iframe)optionDiv_iframe.style.visibility='hidden';
	posEvid=0;
	lenEvid=0;
}

function suggerimentoText(campo,tabella,colonna,ordine,lminima,e){
	if(e.keyCode==9){ //tab
		//campo.value=document.getElementById("evid"+posEvid).innerHTML;
		nascondiOptions();
		return;
	}
	if(e.keyCode==13){ //invio
		if(document.getElementById("evid"+posEvid)!=null){
			campo.value=document.getElementById("evid"+posEvid).innerHTML;
			nascondiOptions();
		}
		return;
	}
	if(e.keyCode==39){ //freccia destra
		//campo.value=document.getElementById("evid"+posEvid).innerHTML;
		//nascondiOptions();
		return;
	}
	if(!optionDiv){ //se il div non c'è
		optionDiv = document.createElement('DIV');
		optionDiv.id = 'suggerimento';	
		document.body.appendChild(optionDiv);
		
		if(isMSIE){
			optionDiv_iframe = document.createElement('IFRAME');
			optionDiv_iframe.border='0';
			optionDiv_iframe.style.width = optionDiv.clientWidth + 'px';
			optionDiv_iframe.style.height = optionDiv.clientHeight + 'px';
			optionDiv_iframe.id = 'suggerimento_iframe';
			document.body.appendChild(optionDiv_iframe);
		}
		
		var allInputs = document.getElementsByTagName('INPUT');
		for(var no=0;no<allInputs.length;no++){
			if(!allInputs[no].onkeyup)allInputs[no].onfocus = nascondiOptions;
		}			
		var allSelects = document.getElementsByTagName('SELECT');
		for(var no=0;no<allSelects.length;no++){
			allSelects[no].onfocus = nascondiOptions;
		}
	}else{ //se il div c'è già
		if(e.keyCode==40){posEvid+=1;} //freccia giù
		if(e.keyCode==38){posEvid-=1;} //freccia su
		if(optionDiv)optionDiv.style.visibility='visible';	
		if(optionDiv_iframe)optionDiv_iframe.style.visibility='visible';
	}
	if((campo.value.length<lminima)||(e.keyCode==27)||(campo.value.length==0)){ //stringa troppo corta o tab o campo vuoto
		nascondiOptions();
		return;
	}
	optionDiv.style.top = (posizioneV(campo) + campo.offsetHeight) + 'px';
	optionDiv.style.left = (posizioneL(campo)) + 'px';
	if(optionDiv_iframe){
		optionDiv_iframe.style.left = optionDiv.style.left;
		optionDiv_iframe.style.top = optionDiv.style.top;			
	}
	//alert(""+PATH_SUGGERIMENTI+"?t="+tabella+"&c="+colonna+"&o="+ordine+"&v="+campo.value+"&tar="+campo.name,"false","riempiOptions");
	chiamataAjax(""+PATH_SUGGERIMENTI+"?t="+tabella+"&c="+colonna+"&o="+ordine+"&v="+campo.value+"&tar="+campo.name,"false","riempiOptions");
}

function riempiOptions(){
	//alert(xmlhttp.responseText);
	var res = xmlhttp.responseText;
	var arrres = res.split("|#@");
	
	if(arrres[0]==""){
		document.getElementById("suggerimento").innerHTML="";
		nascondiOptions();
	}else{
		var strcont="<table class=\"sugg\" width=\"100%\">";
		lenEvid=arrres.length;
		if(posEvid<0){posEvid=0;}
		if(posEvid>=lenEvid){posEvid=lenEvid-1;}
		for(var i=0;i<arrres.length;i++){
			strcont+="<tr><td class=\"tdleft\">";
			if(i==posEvid){
				strcont+="<div class=\"suggevid\">";
			}
			strcont+=arrres[i];
			if(i==posEvid){
				strcont+="</div>";
			}
			strcont+="</td></tr>";
		}
		strcont+="</table>";
		//alert(strcont);
		document.getElementById("suggerimento").innerHTML=strcont;
	}
}
//fine suggerimenti
//------------------------------------------------------------------------------------------------------------------------------

function controllaForm(){
	var ok=true;
	var of=document.filtro.elements;
	for(var i=0;i<of.length;i++){
		if((of[i].getAttribute("tipologia")=="obbligatorio")||(of[i].getAttribute("tipologia")=="facoltativo")){
			var obblig=true;
			if(of[i].getAttribute("tipologia")=="facoltativo"){
				obblig=false;
			}
			switch(of[i].getAttribute("validazione")){
				
				case "tendina":
					if((of[i].selectedIndex==0)&&(obblig)){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "data":
					if((isBlank(of[i].value))&&(obblig)){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "testo":
					if((isBlank(of[i].value))&&(obblig)){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "numinteri":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isInteger(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "numvirgola":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isNumeric(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "valuta":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isNumeric(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "mail":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isMail(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "codfisc":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isCodiceFiscale(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				
				case "piva":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isPartitaIva(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
				case "cfpi":
					if( ( (isBlank(of[i].value)) && (obblig) ) || ( (!isBlank(of[i].value)) && (!isPartitaIva(of[i].value)) && (!isCodiceFiscale(of[i].value)) ) ){
						of[i].style.backgroundColor='tomato';
						ok=false;
					}
				break;
			}
		}
	}
	return ok;
}

function cambiopagina(quale){
	document.filtro.azione.value="pagina";
	document.filtro.dato1.value=quale;
	document.filtro.submit();
}

function ordina(percosa){
	document.filtro.azione.value="ordina";
	document.filtro.dato1.value=percosa;
	document.filtro.submit();
}

function cambiofiltro(){
	document.filtro.azione.value="filtro";
	document.filtro.submit();
}

function invia_form_login(){
 ok=1;
 if(isBlank(document.login.user.value)){
	alert("Il campo username è vuoto");
	ok=0;
 }
 if(isBlank(document.login.passw.value)){
	alert("Il campo password è vuoto");
	ok=0;
 }
 if(ok==1){
  document.login.action="login.php";
  document.login.submit();
 }
}

function inviaNewPassword(){
 ok=1;
 if(isBlank(document.login.old_psw.value)){
  alert("Il campo vecchia password è vuoto");
  ok=0;
 }
 if(isBlank(document.login.new_psw.value)){
  alert("Il campo nuova password è vuoto");
  ok=0;
 }
 if(isBlank(document.login.re_new_psw.value)){
  alert("Il campo ridigita nuova password è vuoto");
  ok=0;
 }
 if(document.login.old_psw.value==document.login.new_psw.value){
  alert("La nuova password è uguale a quella vecchia");
  ok=0;
 }
 if(document.login.new_psw.value != document.login.re_new_psw.value){
  alert("Le password inserite non corrispondono");
  ok=0;
 }
 if(isSpecialChar(document.login.new_psw.value)||!nospace(document.login.new_psw.value)||isSpecialChar(document.login.re_new_psw.value)||!nospace(document.login.re_new_psw.value)){
  alert("La password scelta contiene caratteri non ammessi o spazi");
  ok=0;
 }
 if(!pswVerify(document.login.new_psw.value)){
  alert("La password deve essere almeno 8 caratteri ed avere almeno una maiuscola e un numero");
  ok=0;
 }
 if(ok==1){
  document.login.action="rinnova.php";
  document.login.submit();
 }
}

function mostraDati(){
	document.getElementById("idati").height = document.documentElement.clientHeight*0.85;
	document.getElementById("idati").width = document.documentElement.clientWidth*0.85;
	document.getElementById("pageblur").style.visibility = "visible";
	document.getElementById("datipagina").style.visibility = "visible";
}

function mostraNewDati(){
	document.getElementById("datipagina").height = document.documentElement.clientHeight*0.85;
	document.getElementById("datipagina").width = document.documentElement.clientWidth*0.85;
	document.getElementById("pageblur").style.visibility = "visible";
	document.getElementById("datipagina").style.visibility = "visible";
}

function chiudiDati(dest){
	parent.location.href=dest;
}

function chprov(newprov,path_comuni){
	var sel=document.getElementById("id_comune");
	opts=sel.getElementsByTagName("option");
	for(i=opts.length-1;i>=0;i--){
		sel.removeChild(opts[i]);
	}
	chiamataAjax(""+path_comuni+"?p="+newprov,"false","cambiaComuni");
}
function cambiaComuni(){
	var risposta = xmlhttp.responseText;
	var sel=document.getElementById("id_comune");
	arrcomuni=risposta.split("*");
	opt=document.createElement("option");
	opt.setAttribute("value","");
	opt.setAttribute("selected","selected");
	opttxt=document.createTextNode("seleziona...");
	opt.appendChild(opttxt);
	sel.appendChild(opt);
	if(risposta!=""){
		for(i=0;i<arrcomuni.length;i++){
			valori=arrcomuni[i].split("#");
			opt=document.createElement("option");
			opt.setAttribute("value",valori[0]);
			opttxt=document.createTextNode(valori[1]);
			opt.appendChild(opttxt);
			sel.appendChild(opt);
		}
	}
}

/*------------------------------------menù ad albero js-----------------------------------------------*/
/*inizializzazione percorso immagini*/
var menualbero_path="";
function menualbero_init(path_img){
	menualbero_path=path_img;
}
/*menu js apre o chiude una voce*/
function menualbero_aprichiudi(item) {
	menualbero_aprichiudi_new(item,false);
}
function menualbero_aprichiudi_new(item,forzaApri) {
	var elem=document.getElementById(item);
	var visibile=(elem.style.display!="none")
	var spanicona=document.getElementById("ico" + item);
	if(!visibile || forzaApri){
		elem.style.display="block";
		spanicona.innerHTML="<img src='"+menualbero_path+"cartellaaperta.gif' />";
	}else{
		elem.style.display="none";
		spanicona.innerHTML="<img src='"+menualbero_path+"cartella.gif' />";
	}
}
/*menu js espande tutte le voci*/
function menualbero_espanditutto(){
	var divs=document.getElementsByTagName("div");
	for(var i=0;i<divs.length;i++){
		if (divs[i].id.substring(0,3)=='cat'){
			divs[i].style.display="block";
			var spanicona=document.getElementById("ico" + divs[i].id);
			spanicona.innerHTML="<img src='"+menualbero_path+"cartellaaperta.gif' />";
		}
	}
}
/*menu js collassa tutte le voci*/
function menualbero_chiuditutto(){
	var divs=document.getElementsByTagName("div");
	for(var i=0;i<divs.length;i++){
		if (divs[i].id.substring(0,3)=='cat'){
			divs[i].style.display="none";
			var spanicona=document.getElementById("ico" + divs[i].id);
			spanicona.innerHTML="<img src='"+menualbero_path+"cartella.gif' />";
		}
			
	}
}
/*------------------------------------fine menù ad albero js-----------------------------------------------*/