﻿
// Funzioni gestione campo /////////////////////////////////////////////////////////////////////////////////////////////////////////
function emptyField(field) { if (field.defaultValue == field.value) { field.value = ''; } }
function fillField(field) { if (field.value == '') { field.value = field.defaultValue; } }

// Funzioni gestione cookie /////////////////////////////////////////////////////////////////////////////////////////////////////////

// imposta il cookie sNome = sValore per la durata di iGiorni
function setCookie(sNome, sValore, iGiorni) {
    var dtOggi = new Date()
    var dtExpires = new Date()
    dtExpires.setTime(dtOggi.getTime() + 24 * iGiorni * 3600000)
    document.cookie = sNome + "=" + escape(sValore) + "; expires=" + dtExpires.toGMTString() + ";path = /";
}

// restituisce il valore del cookie sNome
function getCookie(sNome) {
    // genera un array di coppie "Nome = Valore"
    // NOTA: i cookies sono separati da ';'
    var asCookies = document.cookie.split("; ");
    // ciclo su tutti i cookies
    for (var iCnt = 0; iCnt < asCookies.length; iCnt++) {
        // leggo singolo cookie "Nome = Valore"
        var asCookie = asCookies[iCnt].split("=");
        if (sNome == asCookie[0]) {
            return (unescape(asCookie[1]));
        }
    }
    // SE non esiste il cookie richiesto
    return ("");
}

// rimuove un cookie
function delCookie(sNome) {
    setCookie(sNome, "");
}

// Mostra il popup /////////////////////////////////////////////////////////////////////////////////////////////////////////
var cookiePopup_Name = 'popupMessage';
function showPopup(cassa, freq, width, height) {
    // Leggo il cookie per determinare se far apparire il messaggio
    var show = getCookie(cookiePopup_Name + cassa);
    if (show != 1 || freq <= 0) {
        setCookie(cookiePopup_Name + cassa, 1, freq);
        window.open('/Page.aspx', 'Page', 'width=' + width + ',height=' + height + ',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes');
    }
}

// Controllo indirizzi email /////////////////////////////////////////////////////////////////////////////////////////////////////////
function isEmail(emailStr) {
    // Formato user@domain e separazione di username e dominio
    var emailPat = /^(.+)@(.+)$/;
    // Pattern per ritrovare i caratteri speciali (non consentiti)
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    // Caratteri consentiti in username o domainname
    var validChars = "\[^\\s" + specialChars + "\]";
    // Username contenente spazi
    var quotedUser = "(\"[^\"]*\")";
    // domainName costituito da un indirizzo IP
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    // Unità 'atomo' ovvero una serie di caratteri non speciali
    var atom = validChars + '+';
    // Una 'word' dell'username. L'username può essere costituito da più 'word'
    // separate da .
    var word = "(" + atom + "|" + quotedUser + ")";
    // Struttura dell'username
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    // Dominio sombolico
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");

    // Controllo della sintassi username@domain e separazione dell'username dal
    // domain
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null) {
        //alert("Email address seems incorrect (check @ and .'s)")
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    // User valido.
    if (user.match(userPat) == null) {
        //alert("The username doesn't seem to be valid.")
        return false;
    }

    // Indirizzo IP valido (nel caso in cui il domain sia un IP.
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                //alert("Destination IP address is invalid!")
                return false;
            }
        }
        return true;
    }

    // Domain è un nome simbolico
    var domainArray = domain.match(domainPat);
    if (domainArray == null) {
        //alert("The domain name doesn't seem to be valid.")
        return false;
    }

    // controllo sulla parte terminale del domain.

    // Spezzo il domain in 'atomi'
    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if ((domArr[domArr.length - 1].length < 2) ||
	    (domArr[domArr.length - 1].length > 6)) {
        // alert("The address must end in a three-letter domain, or two letter country.")
        return false;
    }

    // Parte terminale del dominio preceduta da un host name.
    if (len < 2) {
        //var errStr="This address is missing a hostname!"
        //alert(errStr)
        return false;
    }

    return true;
}

// Controllo submit form /////////////////////////////////////////////////////////////////////////////////////////////////////////
var checkSubmitForm_Email = '';
function checkSubmitForm(sender) {
    sender = $(sender);

    var formsubmit = true;
    $('.required-field').css('display', 'none');

    var req = sender.find('.required-field');
    req.each(function () {
        var el = $(this);
        var forceMessage = false;
        var prev = el.prevAll('input,textarea,select,.privacy-nl-group');
        if (prev.length > 0) {
            prev = prev.eq(0);
            var fieldValue = '';
            if (prev.attr('type') == 'checkbox') {
                fieldValue = prev.attr('checked') ? '1' : '';
            }
            else if (prev.hasClass('email')) {
                fieldValue = isEmail(prev.val()) ? prev.val() : '';
                checkSubmitForm_Email = fieldValue;
            }
            else if (prev.hasClass('email-confirm')) {
                fieldValue = isEmail(prev.val()) ? prev.val() : '';
                forceMessage = checkSubmitForm_Email != fieldValue;
            }
            else if (prev.hasClass('privacy-nl-group')) {
                var checkedRadio = prev.find('input[type="radio"]:checked').eq(0);
                fieldValue = checkedRadio.val() == "1" ? checkedRadio.val() : '';
            }
            else {
                fieldValue = prev.val();
            }
            if (fieldValue == null || fieldValue.length <= 0 || forceMessage) {
                prev.focus();
                el.css('display', 'block');
                formsubmit = false;
            }
        }
    });
    return formsubmit;
}
