var consonanti =  "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
var numeri = "0123456789";

function ControllaCodiceFiscale(cf){
    var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return true;
    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 verificaCorrispondenza(cf,Cognome,Nome){
	if(cf && Cognome && Nome){
	      if( cf != "" && Cognome!= "" &&  Nome!= ""){
	        rc = CalcolaCognome(Cognome);
	  	    rn = CalcolaNome(Nome)
	        if(cf.substring(0,6)==rc+rn)return true;
	     }
	}
    return false
}

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 (var 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 (var 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();
}
