//Configuration Variables
//var culture = "it-IT"; 		//Format Date Type
var validateOnBlur = true; 	//Change the Style of control onBlur
var divErrorCont = "errContenuto";  //Control where the errors message print out

var styleError = "InputError"; 	//Style Errore
var styleOK = "InputText"; 		//Style Normal
var styleReq = "InputReq";      //Style Requested

var minYear = 1900; 			//Min year validation
var maxYear = 2100; 			//Max year validation

//var valoreNumber = /^[-]?\d*\,?\d*$/;
//var valoreMoney = /^[-]?\d*\,?\d*$/;
//var valoreInteger = /^[-]?\d*\d*$/;
//var valoreEmail = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
//var valoreDate = /^[-]?\d*\/?\d*$/;

//var errorMail = "Il campo @ non e` una mail valida";
//var errorNumber = "Il campo @ non e` un numero valido";
//var errorMoney = "Il campo @ non e` un importo valido";
//var errorInteger = "Il campo @ non e` un numero valido";
//var errorDate = "Il campo @ non e` una data valida";
//var errorCombo = "Selezionare almeno un valore di @";
//var errorCheck = "Selezionare obbligatoriamente @";
//var errorRadio = "Selezionare almeno un valore di @";
//var errorCF = "Il codice fiscale inserito non è valido";
//var errorPI = "La partita IVA inserita non è valida";
//var errorMinValue = "Il valore di @ deve essere maggiore di #";
//var errorMaxValue = "Il valore di @ deve essere minore di #";
//var errorMinChar = "@ deve essere di minimo # caratteri";
//var errorMaxChar = "@ deve essere di massimo # caratteri";
//var errorObbligatorio = "@ e` un campo obbligatorio";
//var errorEqualTo = "Il campo @ non rispetta la condizione di eguaglianza";

//Variables
var errorMessage = "";
var validationForm = false;

//Esegue la validazione dell'intero form dell'anagrafica clienti
function validateAnagrafica(formID, group) {
    var controlla;
    var ritorno;
    var errori;

    var formElement = document.getElementById(formID);

    validationForm = true;

    ritorno = true;
    esecuzioneOk = true;

    for (var n = 0; n < formElement.elements.length; n++) {
        controlla = false;
        var grp = formElement.elements[n].getAttribute("group");
        if (group != null) {
            if (group == grp) {
                controlla = true;
            } else {
                controlla = false;
            }
        } else {
            controlla = true;
        }

        if (formElement.elements[n].disabled == true) {
            controlla = false;
        }

        if (controlla) {
            ritorno = validate(formElement.elements[n]);
        } else {
            if (formElement.elements[n].type != "radio" && formElement.elements[n].type != "checkbox") {
                if (formElement.elements[n].className == styleError) {
                    if (formElement.elements[n].getAttribute("required") == "true" || formElement.elements[n].getAttribute("requiredTemp") == "true") {
                        formElement.elements[n].className = styleReq;
                    } else {
                        formElement.elements[n].className = styleOK;
                    }
                }
            }
            ritorno = true;
        }

        if (!ritorno) {
            esecuzioneOk = false;
        }
    }

    validationForm = false;
    if (!esecuzioneOk) {
        document.getElementById(divErrorCont).style.visibility = "visible";
        document.getElementById(divErrorCont).innerHTML = "<BR />" + retError();
    } else {
        document.getElementById(divErrorCont).style.visibility = "hidden";
        document.getElementById(divErrorCont).innerHTML = "";
    }

    //    if (esecuzioneOk) {
    //        enableControl(group);
    //    }

    return esecuzioneOk;
}

//Esegue la validazione dell'intero form o del gruppo di controlli passato
function validateForm(formID, group) {

    var controlla;
    var ritorno;
    var errori;

    var formElement = document.getElementById(formID);

    validationForm = true;

    ritorno = true;
    esecuzioneOk = true;

    for (var n = 0; n < formElement.elements.length; n++) {
        controlla = false;
        var grp = formElement.elements[n].getAttribute("group");
        if (group != null) {
            if (group == grp) {
                controlla = true;
            } else {
                controlla = false;
            }
        } else {
            controlla = true;
        }

        if (formElement.elements[n].disabled == true) {
            controlla = false;
        }

        if (controlla) {
            ritorno = validate(formElement.elements[n]);
        } else {
            if (formElement.elements[n].type != "radio" && formElement.elements[n].type != "checkbox") {
                if (formElement.elements[n].className == styleError) {
                    if (formElement.elements[n].getAttribute("required") == "true" || formElement.elements[n].getAttribute("requiredTemp") == "true") {
                        formElement.elements[n].className = styleReq;
                    } else {
                        formElement.elements[n].className = styleOK;
                    }
                }
            }
            ritorno = true;
        }

        if (!ritorno) {
            esecuzioneOk = false;
        }
    }

    validationForm = false;

    if (!esecuzioneOk) {
        document.getElementById(divErrorCont).style.visibility = "visible";
        document.getElementById(divErrorCont).innerHTML = "<BR />" + retError();
    } else {
        document.getElementById(divErrorCont).style.visibility = "hidden";
        document.getElementById(divErrorCont).innerHTML = "";
    }

    if (esecuzioneOk) {
        enableControl(group);
    }

    return esecuzioneOk;
}

function emptyError() {
    document.getElementById(divErrorCont).style.visibility = "hidden";
    document.getElementById(divErrorCont).innerHTML = "";
}

//Esegue la validazione del controllo
function validate(control) {

    var ritorno;
    var type = control.type;

    var req = control.getAttribute("required");
    var reqTemp = control.getAttribute("requiredTemp");
    var ctr = control.getAttribute("control");
    var def = control.getAttribute("default");
    var msk = control.getAttribute("mask");
    var rul = control.getAttribute("rules");
    var frc = control.getAttribute("force");

    switch (type) {
        case "checkbox":
            req = control.parentNode.getAttribute("required");
            reqTemp = control.parentNode.getAttribute("requiredTemp");
            ctr = control.parentNode.getAttribute("control");
            def = control.parentNode.getAttribute("default");
            msk = control.parentNode.getAttribute("mask");
            rul = control.parentNode.getAttribute("rules");
            frc = control.parentNode.getAttribute("force");

            ritorno = validateCheck(control, req, ctr, def, rul);
            break;

        case "text":
            if (control.value == msk) {
                control.value = "";
            }
            ritorno = validateText(control, req, ctr, def, rul, frc, reqTemp);
            break;

        case "password":
            if (control.value == msk) {
                control.value = "";
            }
            ritorno = validateText(control, req, ctr, def, rul, frc, reqTemp);
            break;

        case "radio":
            req = control.parentNode.getAttribute("required");
            ctr = control.parentNode.getAttribute("control");
            def = control.parentNode.getAttribute("default");
            msk = control.parentNode.getAttribute("mask");
            rul = control.parentNode.getAttribute("rules");
            frc = control.parentNode.getAttribute("force");

            ritorno = validateRadio(control, req, ctr, def, rul);
            break;

        case "select-one":
            ritorno = validateCombo(control, req, ctr, def, rul, frc, reqTemp);
            break;

        case "hidden":
            if (control.value == msk) {
                control.value = "";
            }
            ritorno = validateText(control, req, ctr, def, rul, frc, reqTemp);
            break;

        case "textarea":
            if (control.value == msk) {
                control.value = "";
            }
            ritorno = validateText(control, req, ctr, def, rul, frc, reqTemp);
            break;

        default:
            ritorno = true;
    }

    return ritorno;
}

//Verifica la validità di un campo testo
function validateText(control, req, ctr, def, rul, frc, reqTemp) {

    var ritorno;

    ritorno = true;
    if (ctr == null) {
        ritorno = isText(control, req, def, frc);
        if (ritorno) {
            ritorno = isRuleValid(control.value, rul, control);
        }
    } else {
        switch (ctr) {
            case "mail":
                ritorno = isEmail(control, req, def, frc);
                if (ritorno) {
                    ritorno = isRuleValid(control.value, rul, control);
                }
                break;

            case "number":
                ritorno = isNumber(control, req, def, frc);
                if (ritorno) {
                    var valore = replaceChar(control.value, ",", ".");
                    ritorno = isRuleValid(valore, rul, control);
                    /*if (ritorno) {
                    valore = formatNumber(valore, 2, false);
                    valore = replaceChar(valore, ".", ",");
                    control.value = valore;
                    }*/
                }
                break;

            case "text":
                ritorno = isText(control, req, def, frc);
                if (ritorno) {
                    ritorno = isRuleValid(control.value, rul, control);
                }
                break;

            case "money":
                ritorno = isMoney(control, req, def, frc);
                if (ritorno) {
                    var valore = replaceChar(control.value, ".", "");
                    valore = replaceChar(valore, ",", ".");
                    ritorno = isRuleValid(valore, rul, control);
                    if (ritorno) {
                        valore = formatNumber(valore, 2, true);
                        valore = replaceChar(valore, ".", "/");
                        valore = replaceChar(valore, ",", ".");
                        valore = replaceChar(valore, "/", ",");
                        control.value = valore;
                    }
                }
                break;

            case "integer":
                ritorno = isInteger(control, req, def, frc);
                if (ritorno) {
                    ritorno = isRuleValid(control.value, rul, control);
                }
                break;

            case "date":
                ritorno = isDate(control, req, def, frc);
                if (ritorno) {
                    ritorno = isRuleValid(control.value, rul, control);
                }
                break;

            case "codicefiscale":
                ritorno = isCodiceFiscale(control, req, def, frc);
                break;

            case "partitaiva":
                ritorno = isPartitaIva(control, req, def, frc);
                break;

            case "cf-pi":
                ritorno = isCodiceFiscale(control, req, def, frc);
                if (!ritorno) {
                    ritorno = isPartitaIva(control, req, def, frc);
                }

            case "cap":
                ritorno = isCap(control, req, def, frc);
                if (ritorno) {
                    ritorno = isRuleValid(control.value, rul, control);
                }
                break;
            
            default:
                ritorno = true;
        }
    }

    if (ritorno == false && frc == "true") {
        control.value = def;
        ritorno = true;
    }

    if (validateOnBlur || validationForm) {
        if (!ritorno) {
            control.className = styleError;
        } else {
            if (ctr != "none") {
                if (req == "true" || reqTemp == "true") {
                    control.className = styleReq;
                } else {
                    control.className = styleOK;
                }
            }
        }
    }

    return ritorno;
}

//Verifica la validità di una combobox
function validateCombo(control, req, ctr, def, rul, frc, reqTemp) {

    var ritorno = isDefaultCombo(control.value, req, def, frc);
    if (ritorno) {
        ritorno = isRuleValid(control.value, rul, control);
    } else {
        addError(control, errorCombo);
    }

    if (validateOnBlur || validationForm) {
        if (!ritorno) {

            control.className = styleError;
        } else {
            if (ctr != "none") {
                if (req == "true" || reqTemp == "true") {
                    control.className = styleReq;
                } else {
                    control.className = styleOK;
                }
            }
        }
    }

    return ritorno;
}

//Verifica la validità di un controllo check
function validateCheck(control, req, ctr, def, rul) {

    var ritorno = true;

    if (req == "true") {
        if (!control.checked) {
            ritorno = false;
        }
    }

    if (ritorno) {
        ritorno = isRuleValid(control.value, rul, control);
    } else {
        addError(control, errorCheck);
    }

    //if (validateOnBlur || validationForm) {
    //if (!ritorno) {
    //    control.className = styleError;
    //} else {
    //    if (ctr != "none") {
    //        control.className = styleOK;
    //    }
    //}
    //}

    return ritorno;
}


//Verifica la validità di un controllo radio
function validateRadio(control, req, ctr, def, rul) {

    var ritorno = true;
    var radiochecked = false;

    name = control.getAttribute("name");

    var radiogroup = control.form.elements[name];

    if (req == "true") {
        for (var i = 0; i < radiogroup.length; i++) {
            if (radiogroup[i].checked) {
                radiochecked = true;
                break;
            }
        }
    } else {
        radiochecked = true;
    }

    ritorno = radiochecked;

    if (ritorno) {
        ritorno = isRuleValid(control.value, rul, control);
    } else {
        addError(control, errorRadio);
    }

    //if (validateOnBlur || validationForm) {
    //if (!ritorno) {
    //    control.className = styleError;
    //} else {
    //    if (ctr != "none") {
    //        control.className = styleOK;
    //    }
    //}
    //}

    return ritorno;
}

//Verifica la validità di tipo mail
function isEmail(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValore(control.value, valoreEmail);
            if (!ritorno) {
                addError(control, errorNumber);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di campo numerico con virgola
function isNumber(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValore(control.value, valoreNumber);
            if (!ritorno) {
                addError(control, errorNumber);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di un campo di testo
function isText(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (!ritorno) {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di un campo numerico con virgola
function isMoney(control, req, def, frc) {

    var ritorno = true;

    var value = replaceChar(control.value, ".", "");

    if (!isEmpty(value)) {
        ritorno = isDefault(value, req, def, frc);
        if (ritorno) {
            ritorno = isValore(value, valoreMoney);
            if (!ritorno) {
                addError(control, errorMoney);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di un campo numerico senza virgola
function isInteger(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValore(control.value, valoreInteger);
            if (!ritorno) {
                addError(control, errorInteger);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di una data
function isDate(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValidDate(control.value);
            if (!ritorno) {
                addError(control, errorDate);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di un campo CAP
function isCap(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValore(control.value, valoreCap);
            if (!ritorno) {
                addError(control, errorCap);
            }
        } else {
            addError(control, errorObbligatorio);
        }
    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la validità di un codice fiscale
function isCodiceFiscale(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValidCF(control.value);
            if (!ritorno) {
                addError(control, errorCF);
            }
        } else {
            addError(control, errorObbligatorio);
        }

    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la correttezza di un campo codice fiscale sul carattere finale di controllo
function isValidCF(value) {

    var validi, i, s, set1, set2, setpari, setdisp;

    value = value.toUpperCase();
    if (value.length != 16)
        return false;

    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    for (i = 0; i < 16; i++) {
        if (validi.indexOf(value.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(value.charAt(i))));

    for (i = 0; i <= 14; i += 2)
        s += setdisp.indexOf(set2.charAt(set1.indexOf(value.charAt(i))));

    if (s % 26 != value.charCodeAt(15) - 'A'.charCodeAt(0))
        return false;

    return true;
}

//Verifica la validità di una partita IVA
function isPartitaIva(control, req, def, frc) {

    var ritorno = true;

    if (!isEmpty(control.value)) {
        ritorno = isDefault(control.value, req, def, frc);
        if (ritorno) {
            ritorno = isValidPI(control.value);
            if (!ritorno) {
                addError(control, errorPI);
            }
        } else {
            addError(control, errorObbligatorio);
        }

    } else {
        if (req == "true") {
            addError(control, errorObbligatorio);
            ritorno = false;
        }
    }

    return ritorno;
}

//Verifica la correttezza di un campo partita IVA sul carattere finale di controllo (FORMATO es. IT12345678901)
function isValidPI(value) {

    value = value.toUpperCase();

    if (value.lenght == 11)
        value = "IT" + value;

    if (value.length != 13)
        return false;

    validi = "0123456789";
    validi2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (i = 2; i < 13; i++) {
        if (validi.indexOf(value.charAt(i)) == -1)
            return false;
    }

    for (i = 0; i < 2; i++) {
        if (validi2.indexOf(value.charAt(i)) == -1)
            return false;
    }

    s = 0;

    for (i = 2; i <= 11; i += 2)
        s += value.charCodeAt(i) - '0'.charCodeAt(0);

    for (i = 3; i <= 11; i += 2) {
        c = 2 * (value.charCodeAt(i) - '0'.charCodeAt(0));
        if (c > 9) c = c - 9;
        s += c;
    }

    if ((10 - s % 10) % 10 != value.charCodeAt(12) - '0'.charCodeAt(0))
        return false;

    return true;
}

//Controlla se la stringa rispetta i caratteri di controllo
function isValore(value, equal) {

    var ritorno = value.match(equal);

    if (ritorno == null) {
        return false;
    } else {
        return true;
    }
}

//Controlla se la stringa è vuota
function isEmpty(value) {

    if (value == null || value == "") {
        return true;
    } else {
        return false;
    }
}

//Controlla se il valore selezionato è uguale a quello di default
function isDefault(value, req, def, frc) {

    if (def == null) {
        return true;
    } else {
        if (req == "true") {
            if (def == value) {
                if (frc == "true") {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}

//Controlla se il valore selezionato è uguale a quello di default
function isDefaultCombo(value, req, def, frc) {

    if (def == null) {
        def = 0;
    }

    if (req == "true") {
        if (def == value) {
            if (frc == "true") {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    } else {
        return true;
    }
}

//Formatta il numero
function formatNumber(value, dec, separator) {

    if (!isEmpty(value)) {
        value = roundNumber(value, dec);
        if (separator) {
            value = formatDigit(value);
        }
        return value;
    } else {
        return "";
    }
}

//Aggiunge la suddivisione in punti
function formatDigit(amount) {

    var delimiter = ",";
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);

    if (isNaN(i)) {
        return '';
    }

    var minus = '';

    if (i < 0) {
        minus = '-';
    }

    i = Math.abs(i);

    var n = new String(i);
    var a = [];

    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }

    if (n.length > 0) {
        a.unshift(n);
    }

    n = a.join(delimiter);

    if (d.length < 1) {
        amount = n;
    } else {
        amount = n + '.' + d;
    }

    amount = minus + amount;

    return amount;
}

//Esegue l'arrotondamento di un numero
function roundNumber(amount, decimalNumber) {

    if (!decimalNumber) return Math.round(amount);

    if (amount == 0) {
        var decimals = "";
        for (var i = 0; i < decimalNumber; i++) decimals += "0";
        return "0." + decimals;
    }

    var exponent = Math.pow(10, decimalNumber);
    var num = Math.round((amount * exponent)).toString();
    if (num < 100) {
        num = 100 + num;
        return "0." + num.slice(-1 * decimalNumber);
    }
    else
        return num.slice(0, -1 * decimalNumber) + "." + num.slice(-1 * decimalNumber);
}

//Esegue il replace di caratteri
function replaceChar(value, oldchar, newchar) {

    var temp = "" + value;

    while (temp.indexOf(oldchar) > -1) {
        pos = temp.indexOf(oldchar);
        temp = "" + (temp.substring(0, pos) + newchar + temp.substring((pos + oldchar.length), temp.length));
    }

    return temp;
}

//Controllo caratteri
function stripCharsInBag(s, bag) {
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//Giorni del mese di febbraio
function daysInFebruary(year) {
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}

//Array di giorni
function daysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
        if (i == 2) { this[i] = 29 }
    }
    return this
}

//Verifica la correttezza di un campo data dd/mm/yyyy
function isValidDate(value) {

    var daysInMonth = daysArray(12);
    var pos1 = value.indexOf("/");
    var pos2 = value.indexOf("/", pos1 + 1);

    if (culture == "it-IT") {
        var strDay = value.substring(0, pos1);
        var strMonth = value.substring(pos1 + 1, pos2);
    } else {
        var strDay = value.substring(pos1 + 1, pos2);
        var strMonth = value.substring(0, pos2);
    }
    var strYear = value.substring(pos2 + 1);

    strYr = strYear;

    if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1);

    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1);

    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1);
    }

    var month = parseInt(strMonth);
    var day = parseInt(strDay);
    var year = parseInt(strYr);

    if (pos1 == -1 || pos2 == -1) {
        return false;
    }

    if (strMonth.length < 1 || month < 1 || month > 12) {
        return false;
    }

    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        return false;
    }

    if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
        return false;
    }

    if (value.indexOf("/", pos2 + 1) != -1 || isValore(stripCharsInBag(value, "/"), valoreInteger) == false) {
        return false;
    }

    return true;
}

//Compara la data 1 con la data 2, con type = 1 minore di e type = 2 maggiore di
function compareDate(date1, date2, type) {

    var pos1 = date1.indexOf("/");
    var pos2 = date1.indexOf("/", pos1 + 1);

    if (culture == "it-IT") {
        var strDay1 = date1.substring(0, pos1);
        var strMonth1 = date1.substring(pos1 + 1, pos2);
    } else {
        var strDay1 = date1.substring(pos1 + 1, pos2);
        var strMonth1 = date1.substring(0, pos2);
    }
    var strYear1 = date1.substring(pos2 + 1);

    if (date2.indexOf("today") != -1) {

        var numDays = 0;

        if (date2.indexOf("(") != -1)
            numDays = date2.substr(date2.indexOf("(") + 1, date2.indexOf(")") - (date2.indexOf("(") + 1));

        var d = new Date();

        d.setDate(d.getDate() + parseInt(numDays));

        var curr_date = d.getDate();
        var curr_month = d.getMonth();
        curr_month = curr_month + 1;
        var curr_year = d.getFullYear();

        if (culture == "it-IT") {
            date2 = curr_date + '/' + curr_month + '/' + curr_year;
        } else {
            date2 = curr_month + '/' + curr_date + '/' + curr_year;
        }

    }

    if (date2.indexOf("control") != -1) {

        var controlname = "";
        var numDays = 0;

        if (date2.indexOf("!") != -1) {
            controlname = date2.substr(date2.indexOf("(") + 1, date2.indexOf("!") - (date2.indexOf("(") + 1));
            numDays = date2.substr(date2.indexOf("!") + 1, date2.indexOf(")") - (date2.indexOf("!") + 1));
        } else {
            controlname = date2.substr(date2.indexOf("(") + 1, date2.indexOf(")") - (date2.indexOf("(") + 1));
            numDays = 0;
        }

        if (control.form.elements[controlname].value == "")
            return false;

        var dctr = new Date(control.form.elements[controlname].value);

        dctr.setDate(dctr.getDate() + parseInt(numDays));

        var curr_date = dctr.getDate();
        var curr_month = dctr.getMonth();
        curr_month = curr_month + 1;
        var curr_year = dctr.getFullYear();

        if (culture == "it-IT") {
            date2 = curr_date + '/' + curr_month + '/' + curr_year;
        } else {
            date2 = curr_month + '/' + curr_date + '/' + curr_year;
        }
    }
    
    pos1 = date2.indexOf("/");
    pos2 = date2.indexOf("/", pos1 + 1);

    if (culture == "it-IT") {
        var strDay2 = date2.substring(0, pos1);
        var strMonth2 = date2.substring(pos1 + 1, pos2);
    } else {
        var strDay2 = date2.substring(pos1 + 1, pos2);
        var strMonth2 = date2.substring(0, pos2);
    }
    var strYear2 = date2.substring(pos2 + 1);    

    if (strDay1.charAt(0) == "0" && strDay1.length > 1) strDay1 = strDay1.substring(1);

    if (strMonth1.charAt(0) == "0" && strMonth1.length > 1) strMonth1 = strMonth1.substring(1);

    for (var i = 1; i <= 3; i++) {
        if (strYear1.charAt(0) == "0" && strYear1.length > 1) strYear1 = strYear1.substring(1);
    }
    if (strDay2.charAt(0) == "0" && strDay2.length > 1) strDay2 = strDay2.substring(1);

    if (strMonth2.charAt(0) == "0" && strMonth2.length > 1) strMonth2 = strMonth2.substring(1);

    for (var i = 1; i <= 3; i++) {
        if (strYear2.charAt(0) == "0" && strYear2.length > 1) strYear2 = strYear2.substring(1);
    }

    var month1 = parseInt(strMonth1);
    var day1 = parseInt(strDay1);
    var year1 = parseInt(strYear1);
    var month2 = parseInt(strMonth2);
    var day2 = parseInt(strDay2);
    var year2 = parseInt(strYear2);

    if (type == 1) {
        if (year1 > year2) {
            return false;
        } else {
            if (year1 == year2) {
                if (month1 > month2) {
                    return false;
                } else {
                    if (month1 == month2) {
                        if (day1 > day2) {
                            return false;
                        }
                    }
                }
            }
        }
    } else {
        if (year1 < year2) {
            return false;
        } else {
            if (year1 == year2) {
                if (month1 < month2) {
                    return false;
                } else {
                    if (month1 == month2) {
                        if (day1 < day2) {
                            return false;
                        }
                    }
                }
            }
        }
    }

    return true;
}

//Esegue il controllo sui carattere inseriti al momento del click del bottone
function checkInsert(control, e) {

    var ritorno = true;
    var ctr = control.getAttribute("control");
    var value = control.value;
    var strKey = "";

    if (!e && window.event)
        e = window.event;

    var chrPress = (window.Event) ? e.which : e.keyCode;

    switch (chrPress) {
        case 46:
            return true;
            break;

        case 8:
            return true;
            break;

        case 0:
            return true;
            break;
    }

    strKey = String.fromCharCode(chrPress);

    switch (ctr) {

        case "number":
            ritorno = isValore(strKey, valoreNumber);
            break;

        case "money":
            ritorno = isValore(strKey, valoreMoney);
            break;

        case "integer":
            ritorno = isValore(strKey, valoreInteger);
            break;

        case "date":
            ritorno = isValore(strKey, valoreDate);
            break;

        case "cap":
            ritorno = isValore(strKey, valoreCap);
            break;
            
        default:
            errore = false;
    }

    if (ritorno == true) {
        ritorno = checkMask(control, false, e);
    }

    return ritorno;
}

//Gestione della maschera di inserimento
function checkMask(control, focus, e) {

    var msk = control.getAttribute("mask");
    var strKey = "";

    if (msk != null) {

        if (!e && window.event)
            e = window.event;

        if (e)
            var chrPress = (window.Event) ? e.which : e.keyCode;

        strKey = String.fromCharCode(chrPress);

        applyMask(control, strKey, msk, focus);

        return false;
    } else {
        return true;
    }
}

//Gestione dei tasti Canc e BackSpace
function checkSpecial(control, e) {

    var msk = control.getAttribute("mask");
    var numero;

    if (msk != null) {
        if (!e && window.event)
            e = window.event;

        if (e)
            var chrPress = (window.Event) ? e.which : e.keyCode;

        switch (chrPress) {
            case 46:
                control.value = msk;
                return false;
                break;

            case 8:
                control.value = removeChar(control.value, msk);
                return false;
                break;

            case 0:
                control.value = msk;
                return false;
                break;

            default:
                return true;
        }
    } else {
        return true;
    }
}

//Applica la maschera al valore del controllo
function applyMask(control, charRep, msk, focus) {

    var temp = "";
    var replaced = false;
    var stringa;

    if (focus == false && replaceChar(control.value, "_", "").length == msk.length) {
        stringa = msk;
    } else {
        stringa = control.value;
    }

    for (i = 0; i < msk.length; i++) {
        if (stringa.charAt(i) == "_" && !replaced && charRep != "") {
            temp = temp + charRep;
            replaced = true;
        } else {
            if (stringa.length > i) {
                temp = temp + stringa.charAt(i);
            } else {
                temp = temp + msk.charAt(i);
            }
        }
    }

    control.value = temp;
    if (focus && msk != stringa && replaceChar(control.value, "_", "").length == msk.length) {
        control.select();
    }
}

//Rimuove un carattere
function removeChar(value, msk) {

    var temp = "";
    replaced = false;

    if (value == msk) {
        temp = msk;
    } else {
        for (i = msk.length; i >= 0; i--) {
            if (value.charAt(i) != msk.charAt(i) && !replaced) {
                temp = msk.charAt(i) + temp;
                replaced = true;
            } else {
                temp = value.charAt(i) + temp;
            }
        }
    }

    return temp;
}

//Controlla se la regola è valida
function isRuleValid(value, rul, control) {

    var ritorno = true;
    var errore = "";

    if (rul != null) {
        var rules = rul.split(",");
        var exitFor = false;
        for (i = 0; i < rules.length; i++) {
            var rule = rules[i].split(":");
            switch (rule[0]) {
                case "minValue":
                    var valueCtr = replaceChar(rule[1], ",", ".");
                    if (parseFloat(value) < parseFloat(valueCtr)) {
                        errore = replaceChar(errorMinValue, "#", rule[1]);
                        addError(control, errore);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "maxValue":
                    var valueCtr = replaceChar(rule[1], ",", ".");
                    if (parseFloat(value) > parseFloat(valueCtr)) {
                        errore = replaceChar(errorMaxValue, "#", rule[1]);
                        addError(control, errore);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "minChar":
                    if (value.length < parseInt(rule[1])) {
                        errore = replaceChar(errorMinChar, "#", rule[1]);
                        addError(control, errore);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "maxChar":
                    if (value.length > parseInt(rule[1])) {
                        errore = replaceChar(errorMaxChar, "#", rule[1]);
                        addError(control, errore);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "equalTo":
                    if (control.form.elements[rule[1]].value != value) {
                        addError(control, errorEqualTo);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "isChecked":
                    if (control.form.elements[rule[1]].checked == true) {
                        addError(control, errorObbligatorio);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "isSelected":
                    var def = control.form.elements[rule[1]].getAttribute("default");
                    if (def == null) {
                        def = 0;
                    }
                    if (control.form.elements[rule[1]].selectedIndex != def) {
                        addError(control, errorObbligatorio);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "isValorized":
                    var def = control.form.elements[rule[1]].getAttribute("default");
                    if (def == null) {
                        def = "";
                    }
                    if (control.form.elements[rule[1]].value != def) {
                        addError(control, errorObbligatorio);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "isRadioAll":
                    var radiochecked = false;
                    var name = control.form.elements[rule[1]].getAttribute("name");
                    var radiogroup = control.form.elements[name];

                    for (var i = 0; i < radiogroup.length; i++) {
                        if (radiogroup[i].checked) {
                            radiochecked = true;
                            break;
                        }
                    }

                    if (radiochecked) {
                        addError(control, errorObbligatorio);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "isRadio":
                    if (control.form.elements[rule[1]].checked == true) {
                        addError(control, errorObbligatorio);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "minDate":
                    if (!compareDate(control.value, rule[1], 2)) {
                        addError(control, errorEqualTo);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                case "maxDate":
                    if (!compareDate(control.value, rule[1], 1)) {
                        addError(control, errorEqualTo);
                        ritorno = false;
                        exitFor = true;
                    }
                    break;

                default:
                    ritorno = true;
            }

            if (exitFor) {
                break;
            }
        }
    }

    return ritorno;
}

function addError(control, errore) {
    if (validationForm) {
        var type = control.type;
        
        if (type == "checkbox" || type == "radio")
            var name = control.parentNode.getAttribute("controlname");
        else
            var name = control.getAttribute("controlname");
        
        if (name != null) {
            errore = replaceChar(errore, "@", name);
        } else {
            errore = replaceChar(errore, "@", control.id);
        }

        if (errorMessage.indexOf(errore) == -1) {
            if (errorMessage != "") {
                errorMessage = errorMessage + "<BR />";
            }
            errorMessage = errorMessage + errore;
        }
    }
}

function retError() {
    var temp = errorMessage;
    errorMessage = "";
    return temp;
}

//Aggiunge dinamicamente gli eventi ai controlli della form
function addEvents(formID) {

    var formElement = document.getElementById(formID);

    var aggiungiBlur;
    var aggiungiChange;

    for (var n = 0; n < formElement.elements.length; n++) {
        aggiungiBlur = false;
        aggiungiChange = false;
        var type = formElement.elements[n].type;

        if (formElement.elements[n].type != "radio" && formElement.elements[n].type != "checkbox") {
            if (formElement.elements[n].getAttribute("required") == "true" || formElement.elements[n].getAttribute("requiredTemp") == "true") {
                formElement.elements[n].className = styleReq;
            }
        }

        switch (type) {
            case "checkbox":
                aggiungiBlur = true;
                break;
            case "text":
                aggiungiBlur = true;
                aggiungiChange = true;
                break;
            case "password":
                aggiungiBlur = true;
                aggiungiChange = true;
                break;
            case "radio":
                aggiungiBlur = true;
                break;
            case "select-one":
                aggiungiBlur = true;
                break;
                deafult:
                aggiungiBlur = false;
        }
        if (aggiungiBlur) {
            //Aggiunta del repost della pagina per la gestione dei fattori dinamici nella preventivazione
            if (formElement.elements[n].onblur == null) {
                formElement.elements[n].onblur = function() { return validate(this) };
            } 
           
            
        }
        if (aggiungiChange) {
            formElement.elements[n].onkeypress = function(e) { return checkInsert(this, e) };
            formElement.elements[n].onkeydown = function(e) { return checkSpecial(this, e) };
            formElement.elements[n].onpaste = function(e) { return checkInsert(this, e) };
            formElement.elements[n].onfocus = function(e) { checkMask(this, true, e) };
        }
    }
}

//// ------------------ CHIAMATA WEB METHOD ----------------------------------------

////Variabili:
//var arrayError; //Array contenente TUTTE le descrizioni di errore separate dal nome con "~".
//var retValore = false;
//var form1;
//var group1;

////Splitta la stringa di trascodifica e prende il valore del parametro keyString.
//function EstraiValore(keyString) {
//    if (arrayError != null) {
//        for (var i = 0; i < arrayError.length; i++) {
//            var mySplit = arrayError[i].split("~");
//            if (mySplit[0] == keyString)
//                return mySplit[1];
//        }
//    }

//    return "";
//}

////Chiama la validazione Anagrafica.
//function SetValidazioneAnagrafica(formID, group) {
//    form1 = formID;
//    group1 = group;

//    PageMethods.SetValidazioneAnagrafica(OnSucceededAnagrafica, OnFailed);
//    return retValore;
//}

////Chiama la validazione.
//function SetValidazione(formID, group) {
//    form1 = formID;
//    group1 = group;

//    PageMethods.SetValidazione(OnSucceeded, OnFailed);
//    return retValore;
//}

//// Callback function invoked on successful 
//// completion of the page method.
//function OnSucceededAnagrafica(key, userContext, methodName) {
//    if (methodName == "SetValidazioneAnagrafica") {
//        arrayError = key;
//        retValore = validateAnagrafica(form1, group1);
//    }
//}

//// Callback function invoked on successful 
//// completion of the page method.
//function OnSucceeded(key, userContext, methodName) {
//    if (methodName == "SetValidazione") {
//        arrayError = key;
//        retValore = validate(form1, group1);
//    }
//}

//// Callback function invoked on failure 
//// of the page method.
//function OnFailed(error, userContext, methodName) {
//    if (error !== null) {
//        alert(error.get_message());
//    }
//}

////if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
//// ---------------------------------------------------------------------------------
