$(document).ready(function(){
    $("#cellulare").numeric();
    $("#citta").alpha();
    $("#cap").numeric();
    $("#fisso").numeric();
    $("#cartaFedelta").numeric();
    $("#cartaPass").numeric();
    $("#cartaPassMastercard").numeric();
    $("#dataNascita").numeric({
        allow: "/"
    });
    $("#dataNascTitCarta").numeric({
        allow: "/"
    });
    $("#spesamica_morefields").hide();
    $("#associazioneCartaFedeltaSpan").hide();
    jQuery.each($("input[id^='nomeFiglio']"), function(index, value){
        $(this).alpha();
    });
    jQuery.each($("input[id^='nascitaFiglio']"), function(index, value){
        $(this).numeric({
            allow: "/"
        });
    });
    
    jQuery.each($("p[id^='boxFiglio']"), function(index, value){
        $(this).hide();
    });
    jQuery.each($("p[id^='boxOtherFiglio']"), function(index, value){
        $(this).hide();
    });
    
    /*
     * Checking for logged in user for logonComponent
     */
    // retrieving cookie
    $.ajaxSetup({
        async: false
    });
    var cookie = $.cookie("jcmUserCookie");
    /*if (cookie != null) {
        $("#ghost").load("/dyncomponent/template/loggedLogonComponent.html");
    }*/
    $.ajaxSetup({
        async: true
    });
    //$("#cittaText").show();
    //$("#citta").hide();
    
    jQuery.each($("a[id^='new-errortip']"), function(index, value){
        $(this).hide();
        var name = $(this).attr("id").substring(13);
        /*if (name == 'password1' || name == 'password2') {
         $(this).parent().attr("class", "short");
         }
         else {*/
        $(this).parent().attr("class", "");
        //}
        var popup = $(this).attr("href");
        $(popup).hide();
        $(this).click(function(){
            $(popup).slideToggle();
        });
    });
    
    $.ajaxSetup({
        async: false
    });
    $.getJSON("/AjaxRpc/c4UserValidationWeb.retrieveCarrefourPuntiVendita?", null, function(data, textstatus){
        if (data.result) {
            var puntivendita = eval('(' + data.data + ')');
            
            for (var i = 0; i < puntivendita.length; i++) {
                $("#nomePdvPrimo").addOption(puntivendita[i].codicePdv, puntivendita[i].nomePdv);
                $("#nomePdvSecondo").addOption(puntivendita[i].codicePdv, puntivendita[i].nomePdv);
            }
            
            $("#nomePdvPrimo").addOption(" ", "");
            $("#nomePdvSecondo").addOption(" ", "");
            $("#nomePdvPrimo").sortOptions();
            $("#nomePdvSecondo").sortOptions();
            $("#nomePdvPrimo").combobox({
                buttonText: ''
            });
            $("#nomePdvSecondo").combobox({
                buttonText: ''
            });
        }
        else {
            $("#nomePdvPrimo").addOption("nessuno", "nessuno");
            $("#nomePdvSecondo").addOption("nessuno", "nessuno");
            
        }
        retrieveUserData();
    });
    $.ajaxSetup({
        async: true
    });
    
    $("#deleteProfileForm").click(function(){
        $.ajaxSetup({
            async: false
        });
        var message = "Stai per cancellare il tuo profilo, sei sicuro?";
        var scelta = confirm(message);
        var dominio = "errore";
        var splitted = document.domain.split(".");
        if (splitted.length > 1) {
            dominio = splitted[splitted.length - 2] + "." + splitted[splitted.length - 1];
        }
        else {
            dominio = splitted[splitted.length - 1];
        }
        if (scelta) {
            $.getJSON("/AjaxRpc/c4UserValidationWeb.deleteUserProfile?", null, function(data, textstatus){
                if (data.result) {
                	$.cookie("jcmUserCookie", null, {
                        path: '/',
                        expires: null,
                        domain: dominio
                    });
                    $.cookie("jcmPwdCookie", null, {
                        path: '/',
                        expires: null,
                        domain: dominio
                    });
                    $.cookie("jcmUserCookie", null, {
                        path: '/',
                        expires: null
                    });
                    $.cookie("jcmPwdCookie", null, {
                        path: '/',
                        expires: null
                    });
                    // redirecting to home page
                    window.location = "home.html";
                    return true;
                }
                else {
                    alert("Impossibile cancellare il profilo. " + data.message);
                }
            });
        }
        $.ajaxSetup({
            async: true
        });
    });
    
    function validateSpesamica(){
        $.ajaxSetup({
            async: false
        });
        var ret = false;
        $.getJSON("/AjaxRpc/c4UserValidationWeb.validateCard?cartaFedelta=" + $("#cartaFedelta").val(), null, function(data, textstatus){
            ret = data.result;
        });
        var carta = $("#cartaFedelta").val();
        if (carta.length == 13 && ret) {
            $("#new-errortip-cartaFedelta").hide();
            $("#new-errortip-cartaFedelta").parent().removeAttr("class");
            $("#spesamica_morefields").show();
        }
        else {
            $("#new-errortip-cartaFedelta").show();
            $("#new-errortip-cartaFedelta").parent().attr("class", "error");
            $("#spesamica_morefields").hide();
        }
        $.ajaxSetup({
            async: true
        });
        return false;
    }
    
    $("#convalidoreSpesamica").click(function(){
        validateSpesamica();
    });
    
    jQuery.each($("a[id^='new-errortip-']"), function(index, value){
        $(this).hide();
        var name = $(this).attr("id").substring(14);
        $(this).parent().attr("class", "");
    });
    
    var loc = "" + window.location;
    if (loc.search('myc4') != -1) {
        $("#controltab23").click();
    }
    
    $("#cap").blur(function(){
        var capclass = $("#new-errortip-cap").parent().attr("class").replace(" error", "");
        if ($("#cap").val() != null && $("#cap").val() != '') {
            if ($("#cap").val().length == 5) {
                retrieveProvinceByZipCode();
            }
            else {
                $("#cap").attr("value", "");
                $("#new-errortip-cap").show();
                $("#new-errortip-cap").parent().attr("class", capclass + " error");
            }
        }
        else {
            $("#citta").empty();
            $("#citta").addOption("", "Compilare il cap per visualizzare i comuni");
            $("#provincia").attr("value", "Compilare il cap per visualizzare la provincia")
        }
    });
    
    
    function retrieveProvinceByZipCode(){
        $.ajaxSetup({
            async: false
        });
        var capclass = $("#new-errortip-cap").parent().attr("class").replace(" error", "");
        var cap = $("#cap").val();
        $.getJSON("/AjaxRpc/c4UserValidationWeb.retrieveProvinceByZipCode?cap=" + cap + "&_=" + new Date().getMilliseconds().toString(), null, function(data, textstatus){
            if (data.result) {
                var splitted = data.data.split(":");
                $("#provincia").val(splitted[0]);
                /*if (splitted.length == 2) {
                 $("#cittaText").attr("value", splitted[1]);
                 $("#cittaText").show();
                 $("#citta").hide();
                 }
                 else {
                 if (splitted.length > 2) {*/
                //$("#cittaText").after("<select id='citta'></select>");
                $("#citta").empty();
                for (var i = 1; i < splitted.length; i++) {
                    $("#citta").addOption(splitted[i], splitted[i]);
                }
                $("#citta").show();
                $("#citta").sortOptions();
                /*$("#citta").addOption("", "Compilare il cap per visualizzare i comuni");
                 $("#citta").selectOptions("", null);*/
                //$("#cittaText").attr("value", "");
                //$("#cittaText").hide();
                /* $("#citta").combobox({
                 buttonText: ''
                 });*/
                //}
                //}
                $("#new-errortip-cap").hide();
                $("#new-errortip-cap").parent().attr("class", capclass);
            }
            else {
                $("#cap").attr("value", "");
                $("#new-errortip-cap").show();
                $("#new-errortip-cap").parent().attr("class", capclass + " error");
            }
        });
        $.ajaxSetup({
            async: true
        });
    }
    
    // Versione senza crc
    function CalculateFiscalCode(){
        if ($("#codFisc").val() != null && $("#codFisc").val() != '') {
            var cf = $("#codFisc").val();
            cf = cf.toUpperCase();
            if (cf.length != 16) {
                $("#new-errortip-codFisc").show();
                $("#new-errortip-codFisc").parent().attr("class", "error");
                return false;
            }
            validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for (i = 0; i < 16; i++) {
                if (validi.indexOf(cf.charAt(i)) == -1) {
                    $("#new-errortip-codFisc").show();
                    $("#new-errortip-codFisc").parent().attr("class", "error");
                    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)) {
                $("#new-errortip-codFisc").show();
                $("#new-errortip-codFisc").parent().attr("class", "error");
                return false;
            }
            $("#codFisc").attr("value", cf);
            $("#new-errortip-codFisc").hide();
            $("#new-errortip-codFisc").parent().removeAttr("class");
            return true;
        }
        else {
            return true;
        }
    }
    
    function checkNomiPdv(){
        var punto1 = false;
        if ($("#nomePdvPrimo").val() != null && $("#nomePdvPrimo").val() != '' && $("#nomePdvPrimo").val() != ' ') {
            jQuery.each(($("#combobox_container_nomePdvPrimo a")), function(index, value){
                var href = $(this).attr("href");
				var text = $(this).text();
                if (href.search("http://") != -1) {
                    var splitted = href.split("/");
                    href = splitted[splitted.length - 1];
                }
                var p = $("#nomePdvPrimo").val();
                if (p.search("http://") != -1) {
                    var splitted = p.split("/");
                    p = splitted[splitted.length - 1];
                }
				
                if (unescape(href.toLowerCase()) == unescape(p.toLowerCase()) || unescape(text.toLowerCase()) == unescape(p.toLowerCase())) {
					$("#combobox_container_nomePdvPrimo input").attr("value", text);
					$("#nomePdvPrimo").attr("value",href);
                    punto1 = true;
                    $("#new-errortip-nomePdvPrimo").hide();
                    $("#new-errortip-nomePdvPrimo").parent().removeAttr("class");
                }
            });
            if (!punto1) {
                $("#new-errortip-nomePdvPrimo").show();
                $("#new-errortip-nomePdvPrimo").parent().attr("class", "error");
            }
        }
        else {
            $("#new-errortip-nomePdvPrimo").show();
            $("#new-errortip-nomePdvPrimo").parent().attr("class", "error");
        }
        
        var punto2 = false;
        if ($("#nomePdvSecondo").val() != null && $("#nomePdvSecondo").val() != '' && $("#nomePdvSecondo").val() != ' ') {
            jQuery.each(($("#combobox_container_nomePdvSecondo a")), function(index, value){
                var href = $(this).attr("href");
				var text = $(this).text();
                if (href.search("http://") != -1) {
                    var splitted = href.split("/");
                    href = splitted[splitted.length - 1];
                }
                var p = $("#nomePdvSecondo").val();
                if (p.search("http://") != -1) {
                    var splitted = p.split("/");
                    p = splitted[splitted.length - 1];
                }
                if (escape(href.toLowerCase()) == escape(p.toLowerCase()) || escape(text.toLowerCase()) == escape(p.toLowerCase())) {
					$("#combobox_container_nomePdvSecondo input").attr("value", text);
					$("#nomePdvSecondo").attr("value",href);
                    punto2 = true;
                    $("#new-errortip-nomePdvSecondo").hide();
                    $("#new-errortip-nomePdvSecondo").parent().removeAttr("class");
                }
            });
            if (!punto2) {
                $("#new-errortip-nomePdvSecondo").show();
                $("#new-errortip-nomePdvSecondo").parent().attr("class", "error");
            }
        }
        else {
            $("#new-errortip-nomePdvSecondo").hide();
            $("#new-errortip-nomePdvSecondo").parent().removeAttr("class");
            punto2 = true;
        }
        if (punto1 && punto2) {
            return true;
        }
        else {
            return false;
        }
    }
    
    function checkMail(){
        $.ajaxSetup({
            async: false
        });
        var ret = true;
        if ($("#email").val() != null && $("#email").val() != '') {
            $.getJSON("/AjaxRpc/c4UserValidationWeb.validateEmail?email=" + $("#email").val() + "&cdClient=184625&millis=" + new Date().getMilliseconds().toString(), null, function(data, textstatus){
                if (!data.result) {
                    $("#new-errortip-email").show();
                    $("#new-errortip-email").parent().attr("class", "error");
                    ret = false;
                }
                else {
                    $("#new-errortip-email").hide();
                    $("#new-errortip-email").parent().removeAttr("class");
                    ret = true;
                }
            });
        }
        else {
            $("#new-errortip-email").show();
            $("#new-errortip-email").parent().attr("class", "error");
            ret = false;
        }
		$.ajaxSetup({
            async: true
        });
        return ret;
    }
    
    function checkSpesAmica(){
        var ret = true;
        if ($("#cartaFedelta").val() != null && $("#cartaFedelta").val() != '') {
            var carta = $("#cartaFedelta").val();
            validateSpesamica();
            if (!($("#nomeTitCarta").val() != '' && $("#nomeTitCarta").val() != null)) {
                $("#new-errortip-nomeTitCarta").show();
                $("#new-errortip-nomeTitCarta").parent().attr("class", "error");
                ret = false;
            }
            else {
                $("#new-errortip-nomeTitCarta").hide();
                $("#new-errortip-nomeTitCarta").parent().removeAttr("class");
            }
            if (!($("#cognomeTitCarta").val() != null && $("#cognomeTitCarta").val() != '')) {
                $("#new-errortip-cognomeTitCarta").show();
                $("#new-errortip-cognomeTitCarta").parent().attr("class", "error");
                ret = false;
            }
            else {
                $("#new-errortip-cognomeTitCarta").hide();
                $("#new-errortip-cognomeTitCarta").parent().removeAttr("class");
            }
            if (!($("#dataNascTitCarta").val() != null && $("#dataNascTitCarta").val() != '')) {
                $("#new-errortip-dataNascTitCarta").show();
                $("#new-errortip-dataNascTitCarta").parent().attr("class", "error");
                ret = false;
            }
            else {
                var datanascita = $("#dataNascTitCarta").val();
                datanascita = datanascita.split("/");
                if (datanascita[0].length == 2 && datanascita[1].length == 2 && datanascita[2].length == 4) {
                    $("#new-errortip-dataNascTitCarta").hide();
                    $("#new-errortip-dataNascTitCarta").parent().removeAttr("class");
                }
                else {
                    $("#new-errortip-dataNascTitCarta").show();
                    $("#new-errortip-dataNascTitCarta").parent().attr("class", "error");
                    ret = false;
                }
            }
        }
        return ret;
    }
    
    function checkPromoSms(){
        var ret = true;
        if ($("#operatore").val() != '' && $("#cellulare").val() != null && $("#cellulare").val() != '') {
            if ($("#cellulare").val().length > 8 && $("#cellulare").val().length < 11) {
                $("#new-errortip-cellulare").hide();
                $("#new-errortip-cellulare").parent().removeAttr("class");
                $("#operatore").removeAttr("style");
                $("#new-errortip-flSms").hide();
                $("#flSms").removeAttr("style");
                return ret;
            }
            else {
                ret = false;
                $("#new-errortip-cellulare").show();
                $("#new-errortip-cellulare").parent().attr("class", "error");
                if ($("#flSms").val() == 'S') {
                    $("#new-errortip-flSms").show();
                    $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                }
                else {
                    $("#new-errortip-flSms").hide();
                    $("#flSms").removeAttr("style");
                }
            }
        }
        else {
            if ($("#operatore").val() != '' || ($("#cellulare").val() != null && $("#cellulare").val() != '')) {
                if ($("#cellulare").val() == null || $("#cellulare").val() == '') {
                    $("#new-errortip-cellulare").show();
                    $("#new-errortip-cellulare").parent().attr("class", "error");
                    if ($("#flSms").val() == 'S') {
                        $("#new-errortip-flSms").show();
                        $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    }
                    else {
                        $("#new-errortip-flSms").hide();
                        $("#flSms").removeAttr("style");
                    }
                    ret = false;
                }
                if ($("#operatore").val() == null || $("#operatore").val() == '') {
                    $("#new-errortip-operatore").show();
                    $("#operatore").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    if ($("#flSms").val() == 'S') {
                        $("#new-errortip-flSms").show();
                        $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    }
                    else {
                        $("#new-errortip-flSms").hide();
                        $("#flSms").removeAttr("style");
                    }
                    ret = false;
                }
            }
            else {
                $("#new-errortip-cellulare").hide();
                $("#new-errortip-cellulare").parent().removeAttr("class");
                $("#new-errortip-operatore").hide();
                $("#operatore").removeAttr("style");
                if ($("#flSms").val() == 'S') {
                    $("#new-errortip-flSms").show();
                    $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    ret = false;
                }
                else {
                    $("#new-errortip-flSms").hide();
                    $("#flSms").removeAttr("style");
                }
            }
        }
        return ret;
    }
    
    function checkDataNascitaUtente(){
        var ret = true;
        if ($("#dataNascita").val() != null && $("#dataNascita").val() != '') {
            var datanascita = $("#dataNascita").val();
            datanascita = datanascita.split("/");
            if (datanascita[0].length == 2 && datanascita[1].length == 2 && datanascita[2].length == 4) {
                $("#new-errortip-dataNascita").hide();
                $("#new-errortip-dataNascita").parent().removeAttr("class");
            }
            else {
                $("#new-errortip-dataNascita").show();
                $("#new-errortip-dataNascita").parent().attr("class", "error");
                ret = false;
            }
        }
        if ($("#dataNascTitCarta").val() != null && $("#dataNascTitCarta").val() != '') {
            var datanascita = $("#dataNascTitCarta").val();
            datanascita = datanascita.split("/");
            if (datanascita[0].length == 2 && datanascita[1].length == 2 && datanascita[2].length == 4) {
                $("#new-errortip-dataNascTitCarta").hide();
                $("#new-errortip-dataNascTitCarta").parent().removeAttr("class");
            }
            else {
                $("#new-errortip-dataNascTitCarta").show();
                $("#new-errortip-dataNascTitCarta").parent().attr("class", "error");
                ret = false;
            }
        }
        return ret;
    }
    
    $("#resetProfileForm").click(function(){
        $.ajaxSetup({
            async: false
        });
        retrieveUserData();
        $.ajaxSetup({
            async: true
        });
    });
    
    $("#submitProfileForm").click(function(){
        $.ajaxSetup({
            async: false
        });
        checkAndUpdate();
        $.ajaxSetup({
            async: true
        });
    });
    
    $("#submitProfileReqForm").click(function(){
        $.ajaxSetup({
            async: false
        });
        var res = checkAndUpdate();
        $.ajaxSetup({
            async: true
        });
    });
    
    function checkAndUpdate(){
        // hiding combo box autocomplete
        $("#nomePdvPrimo").combobox.sluitSelect();
        $("#nomePdvSecondo").combobox.sluitSelect();
        
        jQuery.each($("a[id^='new-errortip']"), function(index, value){
            $(this).hide();
            var name = $(this).attr("id").substring(13);
            /*if (name == 'password1' || name == 'password2') {
             $(this).parent().attr("class", "short");
             }
             else {*/
            $(this).parent().attr("class", "");
            //}
            var popup = $(this).attr("href");
            $(popup).hide();
        });
        var test = checkSpesAmica();
        var testPdv = checkNomiPdv();
        var mailCheck = checkMail();
        var fiscal = CalculateFiscalCode();
        var mobile = checkPromoSms();
        var data = checkDataNascitaUtente();
        /*alert("spesamica "+test);
         alert("pdv "+testPdv);
         alert("mail "+mailCheck);
         alert("fiscal "+fiscal);
         alert("mobile "+mobile);
         alert("data "+data);*/
        if (test && testPdv && mailCheck && fiscal && mobile && data) {
            var url = "cdRegUser=-1";
            var servizi = "&servizi=";
            var mondiInteresse = "&mondiInteresse=";
			var next = 0;
            jQuery.each($("#profiloForm input"), function(index, value){
                if ($(this).attr("class") != 'custom' && $(this).attr("class").search('combobox') == -1) {
					url += "&" + $(this).attr("name") + "=" + $(this).val();
                }
                else {
                    if ($(this).attr("id") == 'nomePdvPrimo') {
                        if ($(this).val().search("http://") == -1) {
                            url += "&codicePrimoPdv=" + $(this).val();
                        }
                        else {
                            var p = $(this).val().split("/");
                            url += "&codicePrimoPdv=" + p[p.length - 1];
                        }
                    }
                    if ($(this).attr("id") == 'nomePdvSecondo') {
                        if ($(this).val().search("http://") == -1) {
                            url += "&codiceSecondoPdv=" + $(this).val();
                        }
                        else {
                            var p = $(this).val().split("/");
                            url += "&codiceSecondoPdv=" + p[p.length - 1];
                        }
                    }
                    if ($(this).attr("id") == 'provincia') {
                        if ($(this).val() == 'Compilare il cap per visualizzare la provincia') {
                            url += "&" + $(this).attr("name") + "=";
                        }
                        else {
                            url += "&" + $(this).attr("name") + "=" + $(this).val();
                        }
                    }
                    if ($(this).attr("name") == 'sesso') {
                        var sesso;
                        if (url.search("sesso") == -1) {
                            if ($("#sessoM").attr("checked") || $("#sessoF").attr("checked")) {
                                if ($("#sessoM").attr("checked")) {
                                    url += "&sesso=M";
                                }
                                else {
                                    url += "&sesso=F";
                                }
                            }
                            else {
                                url += "&sesso=";
                            }
                        }
                    }
                    if ($(this).attr("name") == 'marketingDiretto' && $(this).attr("checked")) {
                        url += "&marketingDiretto=" + $(this).val();
                    }
                    if ($(this).attr("name") == 'comComTerzeParti' && $(this).attr("checked")) {
                        url += "&comComTerzeParti=" + $(this).val();
                    }
                    if ($(this).attr("name") == 'flProfilazione' && $(this).attr("checked")) {
                        url += "&flProfilazione=" + $(this).val();
                    }
                    if ($(this).attr("name") == 'servizi' && $(this).attr("checked")) {
                        servizi += $(this).val() + ";";
                    }
                    if ($(this).attr("name") == 'mondiInteresse' && $(this).attr("checked")) {
                        mondiInteresse += $(this).val() + ";";
                    }
                }
            });
            if ($("#citta").val() == undefined) {
                url += "&citta=" + $("#cittaText").val();
            }
            else {
                url += "&citta=" + $("#citta").val();
            }
            url += servizi + mondiInteresse;
            jQuery.each($("#profiloForm select"), function(index, value){
                if ($(this).attr("class") != 'custom') {
                    if ($(this).attr("id") == 'viaggiOrganizzati') {
                        var viaggi = $("#viaggiOrganizzatiNumero").val() + ":" + $(this).val();
                        url += "&" + $(this).attr("id") + "=" + viaggi;
                    }
                    else {
                        url += "&" + $(this).attr("id") + "=" + $(this).val();
                    }
                }
            });
            var numeroFigli = $("#numeroFigli").val();
            var nomeFigli = "";
            var nascitaFigli = "";
            var sessoFigli = "";
            var lavoroFigli = "";
            var studioFigli = "";
            if ($("#numeroFigli").val() != 'nessuno') {
                if (numeroFigli == 'oltre4') {
                    numeroFigli = 4;
                }
                for (var i = 0; i < numeroFigli; i++) {
                    var current = i + 1;
                    if ($("#nomeFiglio" + current).val() != null && $("#nomeFiglio" + current).val() != '') {
                        nomeFigli += $("#nomeFiglio" + current).val() + ";";
                    }
                    if ($("#nascitaFiglio" + current).val() != null && $("#nascitaFiglio" + current).val() != '') {
                        nascitaFigli += $("#nascitaFiglio" + current).val() + ";";
                    }
                    if (($("#nomeFiglio" + current).val() != null && $("#nomeFiglio" + current).val() != '') || ($("#nascitaFiglio" + current).val() != null && $("#nascitaFiglio" + current).val() != '')) {
                        sessoFigli += $("#sessoFiglio" + current).val() + ";";
                        lavoroFigli += $("#lavoroFiglio" + current).val() + ";";
                        studioFigli += $("#titoloStudioFiglio" + current).val() + ";";
                    }
                }
            }
            url += "&nomiDeiFigli=" + nomeFigli + "&dateNascitaDeiFigli=" + nascitaFigli + "&sessoDeiFigli=" + sessoFigli + "&lavoroDeiFigli=" + lavoroFigli + "&titoloStudioDeiFigli=" + studioFigli;
            $.getJSON("/AjaxRpc/c4UserValidationWeb.updateUserDataMod?" + url, null, function(data, textstatus){
                if (!data.result) {
                    eval('bean=' + data.data);
                    jQuery.each($("#profiloForm input"), function(index, value){
                        var idField = $(this).attr("name");
                        if (bean[idField] != null && bean[idField] != 'undefined' && bean[idField] != '') {
                            $("#new-errortip-" + idField).show();
                            $("#new-errortip-" + idField).parent().attr("class", "error");
                        }
                        else {
                            $("#new-errortip-" + idField).hide();
                            $("#new-errortip-" + idField).parent().removeAttr("class");
                        }
                    });
                    window.scrollTo(0, 0);
                    alert("Ci sono errori nella compilazione della pagina. Verificare tutti i dati inseriti nelle pagine");
                    return false;
                }
                else {
                    if (data.data != null && data.data != '') {
                        if (data.data == 'changeEmail') {
                            //alert(data.message);
                            //removing cookie
                            $.cookie("jcmUserCookie", null, {
                                path: '/',
                                expires: null
                            });
                            $.cookie("jcmPwdCookie", null, {
                                path: '/',
                                expires: null
                            });
                            alert("E' stata cambiata l'email di registrazione, verrà inviata un'email al nuovo indirizzo per la conferma dell'utente");
                            window.location = "/utenti/welcome-registration.html";
                        }
                    }
                    else {
                        alert("dati salvati")
                        window.location.reload();
                    }
                }
            });
        }
        else {
            window.scrollTo(0, 0);
            alert("Ci sono errori nella compilazione della pagina. Verificare tutti i dati inseriti nelle pagine");
            return false;
        }
    }
    
    function retrieveUserData(){
        $.ajaxSetup({
            async: false
        });
        $(".grid_12").block({
            message: 'Caricamento',
            css: {
                border: 'none',
                backgroundColor: 'transparent'
            },
            overlayCSS: {
                opacity: '0.0'
            }
        });
        $.getJSON("/AjaxRpc/c4UserValidationWeb.retrieveUserData?millis=" + new Date().getMilliseconds().toString(), null, function(data, textstatus){
            if (!data.result) {
                //alert(data.message);
                //removing cookie
                $.cookie("jcmUserCookie", null, {
                    path: '/',
                    expires: null
                });
                $.cookie("jcmPwdCookie", null, {
                    path: '/',
                    expires: null
                });
                // redirecting to home page
                window.location = "home.html";
                return false;
            }
            else {
                eval('bean=' + data.data);
                jQuery.each($("#profiloForm input"), function(index, value){
                    var idField = $(this).attr("name");
                    if (bean[idField] != null && bean[idField] != 'undefined' && bean[idField] != '') {
                        if (idField == 'sesso' || idField == 'servizi' || idField == 'mondiInteresse' || idField == 'flProfilazione' || idField == 'comComTerzeParti' || idField == 'marketingDiretto' || idField == 'cap') {
                            if (idField == 'sesso') {
                                $("#sesso" + bean[idField]).attr("checked", true);
                            }
                            if (idField == 'servizi') {
                                var servizi = bean['servizi'].split(";");
                                for (var i = 0; i < servizi.length; i++) {
                                    if ($(this).val() == servizi[i]) {
                                        $(this).attr("checked", true);
                                    }
                                }
                            }
                            if (idField == 'mondiInteresse') {
                                var mondiInteresse = bean['mondiInteresse'].split(";");
                                for (var i = 0; i < mondiInteresse.length; i++) {
                                    if ($(this).val() == mondiInteresse[i]) {
                                        $(this).attr("checked", true);
                                    }
                                }
                            }
                            if (idField == 'marketingDiretto') {
                                $("#marketingDiretto" + bean[idField]).attr("checked", true);
                            }
                            
                            if (idField == 'comComTerzeParti') {
                                $("#comComTerzeParti" + bean[idField]).attr("checked", true);
                            }
                            if (idField == 'flProfilazione') {
                                $("#flProfilazione" + bean[idField]).attr("checked", true);
                            }
                            if (idField == 'cap') {
                                $(this).attr("value", bean[idField]);
                                retrieveProvinceByZipCode();
                            }
                        }
                        else {
                            $(this).attr("value", bean[idField]);
                        }
                    }
                    var pdvs = $(this).attr("id");
                    if (pdvs == 'nomePdvPrimo') {
                        var text = bean[pdvs];
						var href = bean['codicePrimoPdv'];
                        $("#combobox_container_nomePdvPrimo input").attr("value", text);
						$("#nomePdvPrimo").attr("value",href);
                    }
                    if (pdvs == 'nomePdvSecondo') {
                        var text = bean[pdvs];
						var href = bean['codiceSecondoPdv'];
                        $("#combobox_container_nomePdvSecondo input").attr("value", text);
						$("#nomePdvSecondo").attr("value",href);
                    }
                    if (pdvs == 'cellulare' && $(this).val() != null && $(this).val() != '') {
                        $("#spesamicaWeb").selectOptions("S", true);
                    }
                });
                if ($("#cartaFedelta").val() != null && $("#cartaFedelta").val() != '') {
                    $("#spesamica_morefields").show();
                }
                jQuery.each($("#profiloForm select"), function(index, value){
                    var idField = $(this).attr("id");
                    if (bean[idField] != null && bean[idField] != 'undefined' && bean[idField] != '') {
                        if (idField == 'numeroFigli') {
                            var numeroFigli = bean[idField];
                            if (numeroFigli == 'oltre4') {
                                numeroFigli = 4;
                            }
                            var nomeFigli = bean['nomiDeiFigli'].split(';');
                            var nascitaFigli = bean['dateNascitaDeiFigli'].split(';');
                            var sessoFigli = bean['sessoDeiFigli'].split(';');
                            var lavoroFigli = bean['lavoroDeiFigli'].split(';');
                            var studioFigli = bean['titoloStudioDeiFigli'].split(';');
                            if (numeroFigli != null && numeroFigli != '' && numeroFigli != 'nessuno') {
                                var inte = parseInt(numeroFigli);
                                for (var i = 0; i < inte; i++) {
                                    var current = i + 1;
                                    $("#boxFiglio" + current).show();
                                    $("#nomeFiglio" + current).attr("value", nomeFigli[i]);
                                    $("#nascitaFiglio" + current).attr("value", nascitaFigli[i]);
                                    $("#sessoFiglio" + current).selectOptions(sessoFigli[i], true);
                                    $("#boxOtherFiglio" + current).show();
                                    $("#lavoroFiglio" + current).selectOptions(lavoroFigli[i], true);
                                    $("#titoloStudioFiglio" + current).selectOptions(studioFigli[i], true);
                                }
                            }
                        }
                        if (idField == 'viaggiOrganizzati') {
                            var splitted = bean[idField].split(":");
                            $("#viaggiOrganizzatiNumero").selectOptions(splitted[0], true);
                            $(this).selectOptions(splitted[1], true);
                        }
                        $(this).selectOptions(bean[idField], true);
                        /*if(idField == 'citta'){
                         var citta = bean[idField];
                         if(citta != null && citta != ''){
                         $("#citta").removeOption(0);
                         }
                         }*/
                    }
                });
                jQuery.each($("span[id^='status']"), function(index, value){
                    var idField = $(this).attr("id");
                    if (bean[idField] != null && bean[idField] != 'undefined' && bean[idField] != '') {
                        if (bean[idField] == 'WAIT' || bean[idField] == 'OK') {
                            var inputId = idField.substring(6, idField.length);
                            $("#" + inputId).attr("readonly", "readonly");
                            $("#nomeTitCarta").attr("readonly", "readonly");
                            $("#cognomeTitCarta").attr("readonly", "readonly");
                            $("#dataNascTitCarta").attr("readonly", "readonly");
                            if (bean[idField] == 'WAIT') {
                                $(this).text(" richiesta inoltrata");
                                $(this).attr("style", "color:#ffcc00;");
                            }
                            else {
                                $(this).text(" carta associata");
                                $("#convalidoreSpesamica").hide();
                                $("#submitProfileReqForm").hide();
                                $.getJSON("/AjaxRpc/c4UserValidationWeb.retrieveCarrefourClientPoints?", null, function(data, textstatus){
                                    if (data.result) {
                                        var punti = eval('(' + data.data + ')');
                                        $("#points").text(punti['points']);
                                        $("#pointsBlock").show();
                                    }
                                });
                            }
                        }
                        if (bean[idField] == 'FAILED') {
                            $(this).text(" numero di carta non corrispondente ai dati inseriti");
                            $(this).attr("style", "color:#ff0000;");
                        }
                    }
                });
            }
        });
        $(".grid_12").unblock();
        $.ajaxSetup({
            async: true
        });
    }
    
    $("#numeroFigli").change(function(){
        jQuery.each($("p[id^='boxFiglio']"), function(index, value){
            $(this).hide();
        });
        jQuery.each($("p[id^='boxOtherFiglio']"), function(index, value){
            $(this).hide();
        });
        var numeroFigli = $("#numeroFigli").val();
        if (numeroFigli != 'nessuno') {
            if (numeroFigli == 'oltre4') {
                numeroFigli = 4;
            }
            for (var i = 0; i < numeroFigli; i++) {
                var current = i + 1;
                $("#boxFiglio" + current).show();
                $("#boxOtherFiglio" + current).show();
            }
        }
    });
});
