var lastError= "";
$(document).ready(function(){
    $("#cellulare").numeric();
    $("#citta").alpha();
    $("#cap").numeric();
    $("#fisso").numeric();
    $("#cartaFedelta").numeric();
    $("#cartaPass").numeric();
    $("#cartaPassMastercard").numeric();
    $("#dataNascita").numeric({
        allow: "/"
    });
    $("#flSms[value='N']").attr("checked", true);
    $("#flNewsletter[value='N']").attr("checked", true);
    $("#flProfilazione[value='N']").attr("checked", true);
    $("#flSmsSa[value='N']").attr("checked", true);
    $("#flNewsletterSa[value='N']").attr("checked", true);
    $("#flProfilazioneSa[value='N']").attr("checked", true);
    $("#spesamicaWeb[value='N']").attr("checked", true);
    $("#comComTerzeParti[value='N']").attr("checked", true);
    $("#marketingDiretto[value='N']").attr("checked", true);
//    $("#dataNascTitCarta").numeric({
//        allow: "/"
//    });
	$("p#eliminaSpesamica").css("display","none");
    $("div[id^='spesamica_morefields']").hide();
    $("#associazioneCartaFedeltaSpan").hide();
    
    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 && cookie.search('1071061') != -1){
        window.location = "home.html";
        return true;
    }
    $.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 + ')');

            $("#pdvPar").hide();
            for (var i = 0; i < puntivendita.length; i++) {
                $("#nomePdvPrimo").addOption(puntivendita[i].codicePdv, puntivendita[i].insegna +" - "+puntivendita[i].nomePdv);
                $("#nomePdvSecondo").addOption(puntivendita[i].codicePdv, puntivendita[i].insegna +" - "+puntivendita[i].nomePdv);
            }
            $("#nomePdvPrimo").addOption(" ", "");
            $("#nomePdvSecondo").addOption(" ", "");
            $("#nomePdvPrimo").sortOptions();
            $("#nomePdvSecondo").sortOptions();
            $("#nomePdvPrimo").combobox({
                buttonText: ''
            });
            $("#nomePdvSecondo").combobox({
                buttonText: ''
            });
            $("#pdvPar").show();
        }
        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
        });
    });
    
    $("#eliminaSpesamica").click(function(){
        $.ajaxSetup({
            async: false
        });
        var message = "Il numero di carta SpesAmica attuale verrà eliminato dal tuo profilo MyCarrefour. Sei sicuro di voler eliminare l'associazione attuale?";
        var scelta = confirm(message);
        if (scelta) {
            $.getJSON("/AjaxRpc/c4UserValidationWeb.deleteSpesamica?", null, function(data, textstatus){
                if (data.result) {
                	alert("dati salvati");
                    window.location.reload();
                }
                else {
                    alert("Impossibile cancellare l'associazione alla carta. " + 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");
            //$("div[id^='spesamica_morefields']").show();
			$.ajaxSetup({
                async: true
            });
            return true;
        }
        else {
            $("#new-errortip-cartaFedelta").show();
            $("#new-errortip-cartaFedelta").parent().attr("class", "error");
            $("div[id^='spesamica_morefields']").hide();
            lastError = "#cartaFedelta";
        }
        $.ajaxSetup({
            async: true
        });
        return false;
    }
    
    $("#convalidoreSpesamica").click(function(){
        if(validateSpesamica()){
            $("#statuscartaFedelta").hide();
        	alert("Numero carta valido. Per associare la carta al tuo profilo clicca su \"Conferma modifica\"");
        }
    });
    
    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");
                lastError = "#cap";
            }
        }
        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]);
                
                $("#citta").empty();
                var output = "";
                for (var i = 1; i < splitted.length; i++) {
                	if(output.search(">"+ splitted[i] +"<") == -1){
                		output += "<option value='"+ splitted[i] +"'>"+ splitted[i] +"</option>";
                	}
                }
                $('#citta').html(output);
                //$("#citta").show();
                //$("#citta").sortOptions();
                $("#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");
                lastError = "#cap";
            }
        });
        $.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");
                lastError = "#codFisc";
                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");
                    lastError = "#codFisc";
                    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");
                lastError = "#codFisc";
                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");
                lastError = "#nomePdvPrimo";
            }
        }
        else {
            $("#new-errortip-nomePdvPrimo").show();
            $("#new-errortip-nomePdvPrimo").parent().attr("class", "error");
            lastError = "#nomePdvPrimo";
        }
        
        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");
                lastError = "#nomePdvSecondo";
            }
        }
        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");
                    lastError = "#email";
                    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");
            lastError = "#email";
            ret = false;
        }
		$.ajaxSetup({
            async: true
        });
        return ret;
    }
    
    
    function checkPassword(){
        var ret = true;
        var pwd1 = $("#password1").val();
        var pwd2 = $("#password2").val();
        if ( pwd1 != null && pwd1 != '') {
        	if(pwd1.length < 6 || pwd1.search(" ") != -1){
        		$("#new-errortip-password1").show();
                $("#new-errortip-password1").parent().attr("class", "error");
                lastError = "#password1";
                ret = false;
        	} else {
        		if(pwd2 != pwd1){
            		$("#new-errortip-password2").show();
                    $("#new-errortip-password2").parent().attr("class", "error");
                    lastError = "#password2";
                    ret = false;
            	}        		
        	}
        }
        return ret;
    }
    
    function checkSpesAmica(){
        var ret = true;
        if ($("#cartaFedelta").val() != null && $("#cartaFedelta").val() != '') {
            var carta = $("#cartaFedelta").val();
            ret = validateSpesamica();
   /*         if (!($("#nomeTitCarta").val() != '' && $("#nomeTitCarta").val() != null)) {
                $("#new-errortip-nomeTitCarta").show();
                $("#new-errortip-nomeTitCarta").parent().attr("class", "error");
                lastError = "#cartaFedelta";
                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");
                lastError = "#cartaFedelta";
                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");
//                lastError = "#cartaFedelta";
//                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");
//                    lastError = "#cartaFedelta";
//                    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[value='S']").attr("checked")) {
                    $("#new-errortip-flSms").show();
                    $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    lastError = "#flSms";
                }
                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[value='S']").attr("checked")) {
                        $("#new-errortip-flSms").show();
                        $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                        lastError = "#flSms";
                    }
                    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);");
                    lastError = "#operatore";
                    if ($("#flSms[value='S']").attr("checked")) {
                        $("#new-errortip-flSms").show();
                        $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                        lastError = "#flSms";
                    }
                    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[value='S']").attr("checked")) {
                    $("#new-errortip-flSms").show();
                    $("#flSms").attr("style", "border: 1px solid rgb(255, 0, 0);");
                    lastError = "#flSms";
                    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");
                lastError = "#dataNascita";
                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");
//                lastError = "#dataNascita";
//                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(){
    	
        //controllo non salvo tag guest
        var utenteTG = $.cookie("jcmUserCookie");
        if(utenteTG!=null && utenteTG.indexOf("1071061")!=-1){
            $.cookie("jcmUserCookie", null);
  	    $.cookie("jcmPwdCookie", null);
            alert("Si è verificato un errore sull'utente. Eseguire nuovamente il login.");
            window.location = "home.html";
            return;
        }

        // 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 pwdCheck = checkPassword();
        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 && pwdCheck) {
            var url = "cdRegUser=-1";
            var servizi = "&servizi=";
            var mondiInteresse = "&mondiInteresse=";
			var next = 0;
			var pwd = $("#password1").val();
	        if ( pwd != null && pwd != '') {
	        	url+="&password="+pwd;
	        } else {
	        	url+="&password=";
	        }
			url += "&nomeTitCarta=&cognomeTitCarta=&dataNascTitCarta=";
            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).val() == 'S' && $(this).attr("checked")) {
                        url += "&marketingDiretto=" + $(this).val();
                    } else if ($(this).attr("name") == 'marketingDiretto' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&marketingDiretto=" + $(this).val();
                    } else if ($(this).attr("name") == 'marketingDiretto' && !$("#marketingDiretto[value='S']").attr("checked") && !$("#marketingDiretto[value='N']").attr("checked")){
                    	url += "&marketingDiretto=";
                    }
                    if ($(this).attr("name") == 'comComTerzeParti' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&comComTerzeParti=" + $(this).val();
                    } else if  ($(this).attr("name") == 'comComTerzeParti' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&comComTerzeParti=" + $(this).val();
                    } else if ($(this).attr("name") == 'comComTerzeParti' && !$("#comComTerzeParti[value='S']").attr("checked") && !$("#comComTerzeParti[value='N']").attr("checked")){
                    	url += "&comComTerzeParti=";
                    }
                    if ($(this).attr("name") == 'flProfilazione' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flProfilazione=" + $(this).val();
                    } else if  ($(this).attr("name") == 'flProfilazione' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flProfilazione=" + $(this).val();
                    } else if ($(this).attr("name") == 'flProfilazione' && !$("#flProfilazione[value='S']").attr("checked") && !$("#flProfilazione[value='N']").attr("checked")){
                    	url += "&flProfilazione=";
                    }
                    if ($(this).attr("name") == 'flNewsletter' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flNewsletter=" + $(this).val();
                    } else if  ($(this).attr("name") == 'flNewsletter' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flNewsletter=" + $(this).val();
                    } else if ($(this).attr("name") == 'flNewsletter' && !$("#flNewsletter[value='S']").attr("checked") && !$("#flNewsletter[value='N']").attr("checked")){
                    	url += "&flNewsletter=";
                    }
                    if ($(this).attr("name") == 'flSms' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flSms=S";
                    } else if  ($(this).attr("name") == 'flSms' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flSms=N";
                    } else if ($(this).attr("name") == 'flSms' && !$("#flSms[value='S']").attr("checked") && !$("#flSms[value='N']").attr("checked")){
                    	url += "&flSms=";
                    }
                    if ($(this).attr("name") == 'flProfilazioneSa' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flProfilazioneSa=" + $(this).val();
                    } else if  ($(this).attr("name") == 'flProfilazioneSa' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flProfilazioneSa=" + $(this).val();
                    } else if ($(this).attr("name") == 'flProfilazioneSa' && !$("#flProfilazioneSa[value='S']").attr("checked") && !$("#flProfilazioneSa[value='N']").attr("checked")){
                    	url += "&flProfilazioneSa=";
                    }
                    if ($(this).attr("name") == 'flNewsletterSa' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flNewsletterSa=" + $(this).val();
                    } else if  ($(this).attr("name") == 'flNewsletterSa' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flNewsletterSa=" + $(this).val();
                    } else if ($(this).attr("name") == 'flNewsletterSa' && !$("#flNewsletterSa[value='S']").attr("checked") && !$("#flNewsletterSa[value='N']").attr("checked")){
                    	url += "&flNewsletterSa=";
                    }
                    if ($(this).attr("name") == 'flSmsSa' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&flSmsSa=S";
                    } else if  ($(this).attr("name") == 'flSmsSa' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&flSmsSa=N";
                    } else if ($(this).attr("name") == 'flSmsSa' && !$("#flSmsSa[value='S']").attr("checked") && !$("#flSmsSa[value='N']").attr("checked")){
                    	url += "&flSmsSa=";
                    }
                    if ($(this).attr("name") == 'spesamicaWeb' && $(this).val() == 'S' && $(this).attr("checked")) {
                        url += "&spesamicaWeb=S";
                    } else if  ($(this).attr("name") == 'spesamicaWeb' && $(this).val() == 'N' && $(this).attr("checked")) {
                        url += "&spesamicaWeb=N";
                    } else if ($(this).attr("name") == 'spesamicaWeb' && !$("#spesamicaWeb[value='S']").attr("checked") && !$("#spesamicaWeb[value='N']").attr("checked")){
                    	url += "&spesamicaWeb=";
                    }
                    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 + "&idRegola=-1";
            
            
            $.getJSON("/AjaxRpc/c4UserValidationWeb.updateUserDataModAndPwd?" + 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");
                            lastError = idField;
                        }
                        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");
                    var id = $(lastError).closest("div[id^='tab-profilo']").attr("id");
                    $("a[href='#"+id+"']").click();
                    return false;
                }
                else {
                    if (data.data != null && data.data != '') {
                        if (data.data == 'changeEmail') {
                            //alert(data.message);
                            //removing cookie
                            var splitted = document.domain.split(".");
			    var dominio = "errore";
			    if(splitted.length>1){
			    	dominio = splitted[splitted.length-2] + "." + splitted[splitted.length-1];
			    } else {
			    	dominio = splitted[splitted.length-1];
			    }
			    $.cookie("jcmUserCookie", null, {
			                    path: '/',
			                    expires: null,
			                    domain: dominio
			                });
			     $.cookie("jcmPwdCookie", null, {
			                    path: '/',
			                    expires: null,
			                    domain: dominio
			                });
                            
                            window.location = "/utenti/changemail.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");
            var id = $(lastError).closest("div[id^='tab-profilo']").attr("id");
            $("a[href='#"+id+"']").click();
            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 == 'flSms' || idField == 'flNewsletter' || idField == 'servizi' || idField == 'mondiInteresse' || idField == 'flProfilazione' || idField == 'comComTerzeParti' || idField == 'marketingDiretto' || idField == 'cap' || idField == 'flSmsSa' || idField == 'flNewsletterSa' || idField == 'flProfilazioneSa' || idField == 'spesamicaWeb') {
                            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[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'comComTerzeParti') {
                                $("#comComTerzeParti[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'flProfilazione') {
                                $("#flProfilazione[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'flSms') {
                                $("#flSms[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'spesamicaWeb') {
                                $("#spesamicaWeb[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'flNewsletterSa') {
                                $("#flNewsletterSa[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'flProfilazioneSa') {
                                $("#flProfilazioneSa[value='" + bean[idField]+"']").attr("checked", true);
                            } else if (idField == 'flSmsSa') {
                                $("#flSmsSa[value='" + 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 ($("#cartaFedelta").val() != null && $("#cartaFedelta").val() != '') {
                    $("div[id^='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' || bean[idField] == 'PART' || bean[idField] == 'ERROR') {
                            var inputId = idField.substring(6, idField.length);
                            $("#" + inputId).attr("readonly", "readonly");
                            $("#nomeTitCarta").attr("readonly", "readonly");
                            $("#cognomeTitCarta").attr("readonly", "readonly");
                            
//                            $("#dataNascTitCarta").attr("readonly", "readonly");
                            $("#calendarLink1").parent().hide();
                            if (bean[idField] == 'WAIT') {
                                $(this).text(" Richiesta associazione inoltrata");
                                $(this).attr("style", "color:#ffcc00;display: inline;width:400px; position: absolute; margin-left: 30px;margin-top: 5px;");
                            }
                            else {
                                $(this).text(" Stato carta : Associata");
                                $(this).attr("style", "color:#419d03;display: inline;width:400px; position: absolute; margin-left: 30px;margin-top: 5px;");
                                $("#okgif").show();
                                $("#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();
                                        $("p#eliminaSpesamica").css("display","block");
                                    }
                                });
				$.getJSON("/AjaxRpc/c4UserValidationWeb.getUserPdvInfo?", null, function(data, textstatus){
                                    if (data.result) {
						var pdvInfo  = eval('(' + data.data + ')');
						if(pdvInfo.codiceCatalogo == '1'){
							$("#siciliaText").show();
							$('a[href$="/my-carrefour/spesamica.html"]').attr("href",'/landing/110527-raddoppiaerisparmia.html');
						}
						if(pdvInfo.codiceCatalogo2 == '1'){
							$("#siciliaText").show();
						}
					}
                                });
                            }
                        }
                        if (bean[idField] == 'FAILED') {
                            $(this).text(" Numero di carta non corrispondente ai dati inseriti");
                            $(this).attr("style", "color:#ff0000;display: inline;width:400px; position: absolute; margin-left: 30px;margin-top: 5px;");
                        }
                    }
                });
            }
        });
        $(".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();
            }
        }
    });
});
