﻿var char_indirizzo = "°()/.,-\ 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' \t\r\n\f";
var char_email = "@.-_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var char_codice_fiscale = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

function controllo_importo_intero_con_messaggio(importo, strNomeCampo, messaggio) {
    // Solo stringhe formate da: 
    // numeri interi
    // punti per separatore migliaia centinaia

    var espressione = new RegExp("(^($)|^([1-9]([0-9]*)$))|(^([1-9](|[0-9]|[0-9]{2})([.]([0-9]){3})+)$)");
    if (!espressione.test(importo.value)) {
        if (messaggio != null)
            alert(messaggio);
        else
            alert("Valore non ammesso nel campo " + strNomeCampo + "\nInserire un numero intero.");

        importo.focus();
        return false;
    }
    return true;
}

function controlla_campo(nomecampo, obbligatorio, descrizionecampo) {
    var checkOK = char_indirizzo;
    var checkStr = nomecampo.value;
    var allValid = true;
    if (nomecampo.value == "" && obbligatorio) {
        if (descrizionecampo == null)
            alert("Inserire un valore nel campo \"" + nomecampo.name + "\".")
        else
            alert("Inserire un valore nel campo \"" + descrizionecampo + "\".")
        nomecampo.focus();
        return false
    }
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length) {
            allValid = false;
            break
        }
    }
    if (!allValid) {
        if (descrizionecampo == null)
            alert("Caratteri non ammessi nel campo \"" + nomecampo.name + "\".")
        else
            alert("Caratteri non ammessi nel campo \"" + descrizionecampo + "\".")
        nomecampo.focus();
        return false
    }
    return true
}


function controlla_combo(nomecampo, descrizionecampo) {
    if (nomecampo.selectedIndex == 0) {
        if (descrizionecampo == null)
            alert("Selezionare un valore per il campo \"" + nomecampo.name + "\".")
        else
            alert("Selezionare un valore per il campo \"" + descrizionecampo + "\".")
        nomecampo.focus();
        return false;
    } else return true;
}

function check_integer(field, obbligatorio, nonzero, descrizioneCampo, messaggio) {
    var checkOK = "0123456789";
    var checkStr = field.value;
    var allValid = true;
    var decPoints = 0;
    var allNum = "";

    if (field.value == "" && obbligatorio) {
        if (messaggio == null)
            alert("Dati obbligatori nel campo \"" + descrizioneCampo + "\" ");
        else
            alert(messaggio);
        field.focus();
        return (false);
    }

    if (field.value == 0 && nonzero) {
        if (messaggio == null)
            alert("Il valore contenuto nel campo \"" + descrizioneCampo + "\" deve essere maggiore di zero");
        else
            alert(messaggio);
        field.focus();
        return (false);
    }

    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
        allNum += ch;
    }

    if (!allValid) {
        if (messaggio == null)
            alert("Il formato della cifra nel campo \"" + descrizioneCampo + "\" non è corretto");
        else
            alert(messaggio);

        field.focus();
        return (false);
    }

    return (true);
}

function check_integerNonMex(field, obbligatorio, nonzero) {
    var checkOK = "0123456789";
    var checkStr = field.value;
    var allValid = true;
    var decPoints = 0;
    var allNum = "";

    if (field.value == "" && obbligatorio) {
        field.focus();
        return (false);
    }

    if (field.value == 0 && nonzero) {
        field.focus();
        return (false);
    }

    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
        allNum += ch;
    }

    if (!allValid) {
        return (false);
    }

    return (true);
}

function sostituisci_carattere(field, ValDaCercare, ValDaSost) {
    var checkStr = field.value;
    var nvolte;
    var i;
    var nuovastr = new String();
    var ch = new String();

    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);

        if (ch != ValDaCercare)
            nuovastr = nuovastr + ch
        else
            nuovastr = nuovastr + ValDaSost
    }
    return (nuovastr);
}

function controlla_intervallo(nomecampo, valoreminimo, valoremassimo, obbligatorio, descrizionecampo, messaggio) {
    var checkStr = sostituisci_carattere(nomecampo, ".", "");
    var allValid = true;
    if (checkStr == "" && obbligatorio) {
        if (messaggio != null)
            alert(messaggio);
        else
            alert("Inserisci il valore del campo \"" + descrizionecampo + "\".")

        nomecampo.focus();
        return false;
    }

    if (valoreminimo != null) {
        if (!(controlla_minimo(nomecampo, valoreminimo, descrizionecampo, messaggio)))
            return false;
    }

    if (valoremassimo != null) {
        if (!(controlla_massimo(nomecampo, valoremassimo, descrizionecampo, messaggio)))
            return false;
    }
    return true;
}

function controlla_minimo(nomecampo, valoreminimo, descrizionecampo, messaggio) {
    var checkStr = sostituisci_carattere(nomecampo, ".", "");
    if (checkStr < valoreminimo) {
        if (messaggio != null) {
            alert(messaggio);
        } else {
            if (descrizionecampo != null) {
                alert("Il campo " + descrizionecampo + " deve essere maggiore di " + valoreminimo + ".");
            }
        }
        nomecampo.focus();
        return false;
    }
    return true;
}

function controlla_massimo(nomecampo, valoremassimo, descrizionecampo, messaggio) {
    var checkStr = sostituisci_carattere(nomecampo, ".", "");
    if (checkStr > valoremassimo) {
        if (messaggio != null) {
            alert(messaggio);
        } else {
            if (descrizionecampo != null) {
                alert("Il campo " + descrizionecampo + " deve essere minore di " + valoremassimo + ".");
            }
        }
        nomecampo.focus();
        return false;
    }
    return true;
}


function Verifica_DataConComboGiorniMesi(ctrlDateGiorno, ctrlDateMese, ctrlDateAnno, nomeCampo) {
    var valDateGiorno = ctrlDateGiorno.options[ctrlDateGiorno.selectedIndex].value;
    var valDateMese = ctrlDateMese.options[ctrlDateMese.selectedIndex].value;
    var valDateAnno = ctrlDateAnno.value;
    var dteDate;
    dteDate = new Date(valDateAnno, valDateMese - 1, valDateGiorno);

    if (ctrlDateGiorno.selectedIndex == 0) {
        alert("Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }
    if (!(valDateGiorno == dteDate.getDate())) {
        alert("Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }
    if (ctrlDateMese.selectedIndex == 0) {
        alert("Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }
    if (!(valDateMese == dteDate.getMonth() + 1)) {
        alert("Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateMese.focus();
        return false;
    }

    if (!(check_integer(ctrlDateAnno, true, true, "Data di nascita", "Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateAnno == dteDate.getFullYear())) {
        alert("Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateAnno.focus();
        return false;
    }
    return true;
}

function ValidateDate(idCtrlDateGiorno, idCtrlDateMese, idCtrlDateAnno, nomeCampo) {
    var ctrlDateGiorno = document.getElementById(idCtrlDateGiorno);
    var ctrlDateMese = document.getElementById(idCtrlDateMese);
    var ctrlDateAnno = document.getElementById(idCtrlDateAnno);
    var valDateGiorno = document.getElementById(idCtrlDateGiorno).value;
    var valDateMese = document.getElementById(idCtrlDateMese).value;
    var valDateAnno = document.getElementById(idCtrlDateAnno).value;
    var dteDate;
    dteDate = new Date(valDateAnno, valDateMese - 1, valDateGiorno);

    if (!(check_integer(ctrlDateGiorno, true, true, "Data di nascita", "Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateGiorno == dteDate.getDate())) {
        alert("Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }

    if (!(check_integer(ctrlDateMese, true, true, "Data di nascita", "Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateMese == dteDate.getMonth() + 1)) {
        alert("Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateMese.focus();
        return false;
    }

    if (!(check_integer(ctrlDateAnno, true, true, "Data di nascita", "Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateAnno == dteDate.getFullYear())) {
        alert("Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateAnno.focus();
        return false;
    }

    return true;
}

function Controllo_Data(ctrlDateGiorno, ctrlDateMese, ctrlDateAnno, nomeCampo) {
    var valDateGiorno = ctrlDateGiorno.value;
    var valDateMese = ctrlDateMese.value;
    var valDateAnno = ctrlDateAnno.value;
    var dteDate;
    dteDate = new Date(valDateAnno, valDateMese - 1, valDateGiorno);

    if (!(check_integer(ctrlDateGiorno, true, true, nomeCampo, "Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateGiorno == dteDate.getDate())) {
        alert("Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }

    if (!(check_integer(ctrlDateMese, true, true, nomeCampo, "Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateMese == dteDate.getMonth() + 1)) {
        alert("Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateMese.focus();
        return false;
    }

    if (!(check_integer(ctrlDateAnno, true, true, nomeCampo, "Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateAnno == dteDate.getFullYear())) {
        alert("Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateAnno.focus();
        return false;
    }

    return true;
}

function Controllo_DataNascita(ctrlDateGiorno, ctrlDateMese, ctrlDateAnno, nomeCampo) {
    var valDateGiorno = ctrlDateGiorno.value;
    var valDateMese = ctrlDateMese.value;
    var valDateAnno = ctrlDateAnno.value;
    var dteDate;
    dteDate = new Date(valDateAnno, valDateMese - 1, valDateGiorno);

    if (!(check_integer(ctrlDateGiorno, true, true, nomeCampo, "Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateGiorno == dteDate.getDate())) {
        alert("Il valore del giorno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateGiorno.focus();
        return false;
    }

    if (!(check_integer(ctrlDateMese, true, true, nomeCampo, "Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateMese == dteDate.getMonth() + 1)) {
        alert("Il valore del mese inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateMese.focus();
        return false;
    }

    if (!(check_integer(ctrlDateAnno, true, true, nomeCampo, "Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.")))
        return false;
    if (!(valDateAnno == dteDate.getFullYear())) {
        alert("Il valore dell'anno inserito nel campo '" + nomeCampo + "' non è in formato corretto.");
        ctrlDateAnno.focus();
        return false;
    }

    if (!Controllo_DataPassata(ctrlDateGiorno, ctrlDateMese, ctrlDateAnno, nomeCampo)) return false;
    
    return true;
}

function Controllo_DataPassata(ctrlDateGiorno, ctrlDateMese, ctrlDateAnno, nomeCampo) {
    var strData;
    var strOggi;
    var oggi;

    oggi = new Date();
    strData = ctrlDateAnno.value * 10000 + ctrlDateMese.value * 100 + ctrlDateGiorno.value * 1;
    strOggi = oggi.getFullYear() * 10000 + (oggi.getMonth() + 1) * 100 + oggi.getDate() * 1;

    if (strOggi < strData) {
        alert("Il valore nel campo '" + nomeCampo + "' è maggiore della data odierna.");
        ctrlDateGiorno.focus();
        return false;
    }
    return true;
}
    
    
function DataPassata(idCtrlDateGiorno, idCtrlDateMese, idCtrlDateAnno, nomeCampo) {
    var ctrlDateGiorno = document.getElementById(idCtrlDateGiorno);
    var ctrlDateMese = document.getElementById(idCtrlDateMese);
    var ctrlDateAnno = document.getElementById(idCtrlDateAnno);
    var strData;
    var strOggi;
    var oggi;
 
    oggi = new Date();
    strData = document.getElementById(idCtrlDateAnno).value * 10000 + document.getElementById(idCtrlDateMese).value *100 + document.getElementById(idCtrlDateGiorno).value * 1 ;
    strOggi = oggi.getFullYear() * 10000 + (oggi.getMonth() + 1) * 100 + oggi.getDate() *1 ;

    if (strOggi < strData) {
        alert("Il valore nel campo '" + nomeCampo + "' è maggiore della data odierna.");
        ctrlDateGiorno.focus();
        return false;
    }
    
    return true;
}

function ValidateConRegularExpression(valore) {
    var espressione = new RegExp("^\-?[0-9]{1,3}(\.[0-9]{3})*(\,[0-9]+)?$|^[0-9]+(\,[0-9]+)?$");
    return espressione.test(valore);
}

function ValidateInteroConRegularExpression(valore) {
    var espressione = new RegExp("^[0-9]*$");
    return espressione.test(valore);
}

function ValidaPercentuale(idCampoPercentuale) {
    var ctrlCampoPercentuale = document.getElementById(idCampoPercentuale);
    var valuePercentuale = ctrlCampoPercentuale.value;
    var valoreInformatoIT = replace_carattere(replace_carattere(valuePercentuale, ".", ""), ",", ".");
    if (!ValidateConRegularExpression(valuePercentuale) || valoreInformatoIT < 0 || valoreInformatoIT > 100) {
        ctrlCampoPercentuale.focus();
        return false;
    }

    return true;
}

function replace_carattere(valore, valDaCercare, valDaSost) {

    var checkStr = valore;
    var i;
    var nuovastr = new String();
    var ch = new String();

    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);

        if (ch != valDaCercare)
            nuovastr = nuovastr + ch;
        else
            nuovastr = nuovastr + valDaSost;
    }
    
    return nuovastr;
}


function controlla_email(nomecampo) {
    var emailStr = nomecampo.value;

    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */

    var checkTLD = 1;

    /* The following is the list of known TLDs that an e-mail address must end with. */

    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */

    var emailPat = /^(.+)@(.+)$/;

    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address. 
    These characters include ( ) < ' > @ , ; : \ " . [ ] */

    var specialChars = "\\(\\)><@',;:\\\\\\\"\\.\\[\\]";

    /* The following string represents the range of characters allowed in a 
    username or domainname.  It really states which chars aren't allowed.*/

    var validChars = "\[^\\s" + specialChars + "\]";

    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */

    var quotedUser = "(\"[^\"]*\")";

    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */

    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

    /* The following string represents an atom (basically a series of non-special characters.) */

    var atom = validChars + '+';

    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */

    var word = "(" + atom + "|" + quotedUser + ")";

    // The following pattern describes the structure of the user

    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");

    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */

    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

    /* Finally, let's start trying to figure out if the supplied address is valid. */

    /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */

    var matchArray = emailStr.match(emailPat);

    if (matchArray == null) {

        /* Too many/few @'s or something; basically, this address doesn't
        even fit the general mould of a valid e-mail address. */

        nomecampo.focus();
        alert("E' necessario inserire un indirizzo e-mail corretto (controllare @ e i punti) per poter procedere.");
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    // Start by checking that only basic ASCII characters are in the strings (0-127).

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            nomecampo.focus();
            alert("Il nome utente dell'email contiene dei caratteri scorretti.");
            return false;
        }
    }
    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            nomecampo.focus();
            alert("Il dominio dell'email contiene dei caratteri scorretti.");
            return false;
        }
    }

    // See if "user" is valid 

    if (user.match(userPat) == null) {

        // user is not valid
        nomecampo.focus();
        alert("Il nome utente dell'email contiene dei caratteri scorretti.");
        return false;
    }

    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {

        // this is an IP address

        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                nomecampo.focus();
                alert("L'indirizzo IP della email non è corretto.");
                return false;
            }
        }
        return true;
    }

    // Domain is symbolic name.  Check if it's valid.

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            nomecampo.focus();
            alert("Il dominio dell'email non è valido.");
            return false;
        }
    }

    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */

    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
	domArr[domArr.length - 1].toLowerCase().search(knownDomsPat) == -1) {
        nomecampo.focus();
        alert("L'indirizzo email deve terminare con un dominio conosciuto o un codice internazionale di 2 lettere.");
        return false;
    }

    // Make sure there's a host name preceding the domain.

    if (len < 2) {
        nomecampo.focus();
        alert("Nell'email manca la parte tra la @ e il punto.");
        return false;
    }

    // to do verify if domain exist else suggest 
    var domains = "libero.it,tiscali.it,virgilio.it,yahoo.it,alice.it,hotmail.com,hotmail.it,inwind.it,fastwebnet.it,gmail.com,tiscalinet.it,email.it,tele2.it,interfree.it,katamail.com,aliceposta.it,yahoo.com,poste.it,msn.com,live.it,infinito.it,jumpy.it,supereva.it";
    domainArray = domains.split(",");

    if (domain != domainArray[0] &&
				domain != domainArray[1] &&
				domain != domainArray[2] &&
			    domain != domainArray[3] &&
			    domain != domainArray[4] &&
			    domain != domainArray[5] &&
			    domain != domainArray[6] &&
			    domain != domainArray[7] &&
			    domain != domainArray[8] &&
			    domain != domainArray[9] &&
			    domain != domainArray[10] &&
			    domain != domainArray[11] &&
			    domain != domainArray[12] &&
			    domain != domainArray[13] &&
				domain != domainArray[14] &&
				domain != domainArray[15] &&
				domain != domainArray[16] &&
				domain != domainArray[17] &&
				domain != domainArray[18] &&
				domain != domainArray[19] &&
				domain != domainArray[20] &&
			    domain != domainArray[21] &&
			    domain != domainArray[23]) {
        suggestThis = suggest_another(domain, domainArray);

        if (suggestThis != "")
            if (confirm("Hai inserito l' indirizzo email: " + emailStr + " \nDesideri che venga modificato in: " + user + "@" + suggestThis + " ?")) {
            nomecampo.value = user + "@" + suggestThis;
        }

    }

    // If we've gotten this far, everything's valid!
    return true;

}

function suggest_another(wrong_domain, array) {
    for (j = 0; j < array.length; j++) {
        if (differences(wrong_domain, array[j]) <= 1)
            return array[j];
    }
    return "";
}

function differences(wrongDomain, item) {
    noOfDiferences = 0;

    charLengthDif = wrongDomain.length - item.length;


    switch (charLengthDif) {
        case 0:
            for (i = 0; i < wrongDomain.length; i++) {
                if (noOfDiferences < 2) {
                    if (wrongDomain.substr(i, 1) != item.substr(i, 1))
                        noOfDiferences++;
                }
                else
                    return noOfDiferences;
            }
            return noOfDiferences;

        case 1:
            for (i = 0; i < item.length; i++) {
                if (noOfDiferences < 2) {
                    if (item.substr(i, 1) != wrongDomain.substr(i + noOfDiferences, 1)) {
                        noOfDiferences++;
                        i--;
                    }
                }
                else
                    return noOfDiferences;
            }
            return noOfDiferences;

        case -1:
            for (i = 0; i < wrongDomain.length; i++) {
                if (noOfDiferences < 2) {
                    if (wrongDomain.substr(i, 1) != item.substr(i + noOfDiferences, 1)) {
                        noOfDiferences++;
                        i--;
                    }
                }
                else
                    return noOfDiferences;
            }
            return noOfDiferences;

        default:
            return 9;
    }
}


function check_indirizzo(field, obbligatorio, messaggio) {
    var checkOK = char_indirizzo;
    var checkStr = field.value;
    var allValid = true;

    if (field.value == "" && obbligatorio) {
        if (messaggio == null)
            alert("Dati obbligatori nel campo \"" + field.name + "\" ");
        else
            alert(messaggio);
        field.focus();
        return (false);
    }
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length) {
            allValid = false;
            break;
        }
    }
    if (!allValid) {
        if (messaggio == null)
            alert("Ammesse solo lettere  e spazi nel campo \"" + field.name + "\" ");
        else
            alert(messaggio);
        field.focus();
        return (false);
    }
    return (true);
}


function non_soloInt(campo, descrizioneCampo, messaggio) {
    if (parseInt(campo.value) == campo.value) {
        if (messaggio != "") {
            alert(messaggio);
        } else {
            alert("Il campo \"" + descrizioneCampo + "\" non può essere formato solo da numeri.");
        }
        campo.focus();
        return true;
    }
    return false;
}

function check_fiscale(campo, obbligatorio, messaggio) {
    caratteri = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")
    pari = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25)
    dispari = new Array(1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23)
    cod = campo.value.toLowerCase(); check = true; if (cod.length != 16) { check = false } else {
        lettere = cod.substr(0, 6) + cod.substr(8, 1) + cod.substr(11, 1) + cod.substr(15); numeri = cod.substr(6, 2) + cod.substr(9, 2) + cod.substr(12, 3); for (i = 0; i < 10; i++) { if (lettere.charCodeAt(i) < 97 || lettere.charCodeAt(i) > 122) { check = false; } }
        for (i = 0; i < 8; i++) { if (numeri.charCodeAt(i) < 48 || numeri.charCodeAt(i) > 57) { check = false; } }
    }
    test = cod.substr(15, 1); var somma = 0
    for (i = 0; i < 16; i = i + 2) {
        carattere = cod.substr(i, 1)
        for (k = 0; k < 36; k++) {
            if (carattere == caratteri[k]) {
                somma = somma + dispari[k]
                break
            }
        }
    }
    for (i = 1; i < 15; i = i + 2) {
        carattere = cod.substr(i, 1)
        for (k = 0; k < 36; k++) {
            if (carattere == caratteri[k]) {
                somma = somma + pari[k]
                break
            }
        }
    }
    resto = somma % 26; var lettera = String.fromCharCode(97 + resto); if (test != lettera) { check = false; }
    if (check == false) { if (obbligatorio) { alert("Il codice fiscale contenuto nel campo \"" + messaggio + "\" è errato"); campo.focus(); return (false); } else { return (confirm("Il codice fiscale contenuto nel campo \"" + messaggio + "\" è errato; Proseguo?")); } }
    return true;
}

function check_fiscale_annonascita(campo, obbligatorio, messaggio, anno_nascita) {
    if (check_fiscale(campo, obbligatorio, messaggio)) {
        if (campo.value.substr(6, 2) != (anno_nascita + "").substr(2, 2)) {
            alert("Il codice fiscale contenuto nel campo \"" + messaggio + "\" è errato; controlla l'anno di nascita.");
            return false;
        }
        return true;
    }
    else {
        return false;
    }
}

function controlla_campo_lunghezza(nomecampo, caratterivalidi, lunghezza, obbligatorio, descrizionecampo) {
    var checkOK = caratterivalidi;
    var checkStr = nomecampo.value;
    var allValid = true;
    if (nomecampo.value == "" && obbligatorio) {
        if (descrizionecampo == null)
            alert("Inserire un valore nel campo \"" + nomecampo.name + "\".")
        else
            alert("Inserire un valore nel campo \"" + descrizionecampo + "\".")
        nomecampo.focus();
        return false
    }
    return true;
}

// ********** funzioni per la correzione dinamica mentre si scrive ***********

var os = -1
var oe = -1
var posizioneCursore;
function getPosition(o) {
    var t = o.value, s = getSelectionStart(o), e = getSelectionEnd(o)
    if (s == os && e == oe) return
    posizioneCursore = s;
}

function getSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart
}

function getSelectionEnd(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveStart('character', -o.value.length)
        return r.text.length
    } else return o.selectionEnd
}

function onblur_percentuale(field) {
    if (field.value.length == 0) return;

    //Per una percentuale non è possibile iniziare con una virgola, aggiungo lo zero
    while (field.value.substr(0, 1) == ",") {
        if (field.value.length > 1) {
            field.value = "0" + field.value;
        } else {
            field.value = "";
        }
    }

    // per una percentuale non è possibile terminare con una virgola
    while (field.value.substr(field.value.length - 1, 1) == ",") {
        field.value = field.value.substr(0, field.value.length - 1);
    }
}

function onblur_importointero(field) {
    //Per un numero intero non è possibile iniziare con zero o punto
    while (field.value.substr(0, 1) == "0" || field.value.substr(0, 1) == ".") {
        if (field.value.length > 1) {
            field.value = field.value.substr(1, field.value.length - 1)
        } else {
            field.value = "";
        }
    }
}

function onkeyup_percentuale(field, event) {

    // Per alcuni casi non sistemo la punteggiatura: Windows Mobile - Android 
    if (!(detectAndroid() || detectWindowMobile())) {

        // Memorizzo posizione cursore
        getPosition(field);

        // Se uso le frecce direzionali la text non viene modificata
        if (event.keyCode != "37" && event.keyCode != "38" && event.keyCode != "39" && event.keyCode != "40") {
            var v1 = field.value;
            var v2;
            v2 = formatta_percentuale(field.value);
            if (v1 != v2) {
                field.value = v2;
            }

            // Calcolo prossima posizione
            switch (event.keyCode) {
                case 46: // Seleziono Canc 
                    if (v2.length * 1 + 1 == v1.length * 1)
                        posizioneCursore = posizioneCursore - 1;
                    break;
                case 8: // Seleziono la freccia che cancella
                    if (v2.length * 1 + 1 == v1.length * 1)
                        posizioneCursore = posizioneCursore - 1;
                    break;
                default:
                    if (v2.length > v1.length)
                        posizioneCursore = posizioneCursore + 1;
                    break;
            }

            // Se inserisco un carattere non numero resetto la posizione
            if (!((event.keyCode >= "48" && event.keyCode <= "57") || (event.keyCode >= "96" && event.keyCode <= "105") || event.keyCode == "8" || event.keyCode == "46" || event.keyCode == "190" || event.keyCode == "188" || field.value.length == 6)) {
                posizioneCursore = posizioneCursore - 1;
            }

            // Metto il cursore nella sua posizione 
            if (document.selection) {
                // IE
                var FieldRange = field.createTextRange();
                FieldRange.move("character", posizioneCursore);
                FieldRange.select();
            } else {
                // No IE
                field.selectionEnd = posizioneCursore;
                field.selectionStart = posizioneCursore;
            }
        }

        return v1 != v2;
    }
}

function onkeyup_importointero(field, event) {

    // Per alcuni casi non sistemo la punteggiatura: Windows Mobile - Android 
    if (!(detectAndroid() || detectWindowMobile())) {

        // Memorizzo posizione cursore
        getPosition(field);

        // Se uso le frecce direzionali la text non viene modificata
        if (event.keyCode != "37" && event.keyCode != "38" && event.keyCode != "39" && event.keyCode != "40") {
            var v1 = field.value;
            var v2;
            v2 = formatta_importointero(field.value);
            if (v1 != v2) {
                field.value = v2;
            }

            // Calcolo prossima posizione
            switch (event.keyCode) {
                case 46: // Seleziono Canc 
                    if (v2.length * 1 + 1 == v1.length * 1)
                        posizioneCursore = posizioneCursore - 1;
                    break;
                case 8: // Seleziono la freccia che cancella
                    if (v2.length * 1 + 1 == v1.length * 1)
                        posizioneCursore = posizioneCursore - 1;
                    break;
                default:
                    if (v2.length > v1.length)
                        posizioneCursore = posizioneCursore + 1;
                    break;
            }

            // Se inserisco un carattere non numero resetto la posizione
            if (!((event.keyCode >= "48" && event.keyCode <= "57") || (event.keyCode >= "96" && event.keyCode <= "105") || event.keyCode == "8" || event.keyCode == "46" || field.value.length == 10)) {
                posizioneCursore = posizioneCursore - 1;
            }

            // Metto il cursore nella sua posizione 
            if (document.selection) {
                // IE
                var FieldRange = field.createTextRange();
                FieldRange.move("character", posizioneCursore);
                FieldRange.select();
            } else {
                // No IE
                field.selectionEnd = posizioneCursore;
                field.selectionStart = posizioneCursore;
            }
        }

        return v1 != v2;
    }
}

function formatta_importointero(str) {
    var separator = '.';
    var i, char, out = '', decimalPosition = -1, isNegative = false, isValid = true;

    for (i = 0; i < str.length; i++) {
        char = str.substr(i, 1);
        if ((char >= '0') && (char <= '9')) {
            out += char;
        }
        if ((char == '-') && (i == 0)) {
            out += char;
            isNegative = true;
        }
    }

    if (separator) {
        if (decimalPosition == -1) {
            decimalPosition = out.length;
        } else {
            decimalPosition -= 1;
        }
        for (i = decimalPosition - 3; i > 0; i -= 3) {
            if (((i == 1) && (isNegative)) || (i == decimalPosition)) break;
            out = out.substr(0, i) + separator + out.substr(i);
        }
    }

    if (!out) {
        out = "";
    }

    return out;
}

// ********** Funzioni per SmartPhone *************

function detectAndroid() {
    if (navigator.userAgent.toLowerCase().search("android") > -1)
        return true;
    return false;
}

function detectIPhone() {
    if (navigator.userAgent.toLowerCase().search("iphone") > -1)
        return true;
    return false;
}

function detectIPod() {
    if (navigator.userAgent.toLowerCase().search("ipod") > -1)
        return true;
    return false;
}

function detectSeries60() {
    if (navigator.userAgent.toLowerCase().search("series60") > -1)
        return true;
    return false;
}

function detectSymbian() {
    if (navigator.userAgent.toLowerCase().search("symbian") > -1)
        return true;
    return false;
}

function detectWebkit() {
    if (navigator.userAgent.toLowerCase().search("webkit") > -1)
        return true;
    return false;
}

function detectWindowMobile() {
    if (navigator.userAgent.toLowerCase().search("windows phone") > -1)
        return true;
    return false;
}

function detectBlackBerry() {
    if (navigator.userAgent.toLowerCase().search("blackberry") > -1)
        return true;
    return false;
}

function detectPalm() {
    if (navigator.userAgent.toLowerCase().search("palm") > -1)
        return true;
    return false;
}

// ********** Termine Funzioni per SmartPhone *************
