
    var jsUserMustBeAuthentificate = false;

    $(function(){  

		/** Organisation (oui/non) */
		$("input[name=orga]").click( function() {
			if ( $(this).val() == "1" ) {
				$('#radioOrganisation').css("display", "block");
			}
			else {
				$('#radioOrganisation').css("display", "none");
				$('#organisation').val("");
				$("#recap_organisation").html("");
			}
		});
    
        $(".abonnement").click(function(){
            manageSouscriptions();
        });    
        $(".engagement").click(function(){
            manageSouscriptions();
        });    
        

/** ******************* */
/** divAuthentification */
/** ******************* */

        /** Formatage de la boîte de dialogue pour l'authentification */
        $("#divAuthentification").dialog({
            modal: true,
            autoOpen: false,
            closeOnEscape: false,
            width: 500,
            height: 450,
				buttons: {
            	"Envoyer": function() {
                    $("#btnConnexion").click();
               }
				},
				close: function(event, ui) {
					if ( $.browser.msie && $.browser.version=="6.0" ) {
						$("#affectation").css("display", "");
						$("#civilite").css("display", "");
						$("#pays").css("display", "");
						$("#naissance").css("display", "");
					}
				}

        });
        $("#formLogin").submit( function () {
            $("#btnConnexion").click();
            return false;
        });

		/* Sur sortie du champ email */
		$("#email").blur(function() {
            if ( $("#email").val().length > 0 ) {
                jsUserMustBeAuthentificate = false;
                var sympid = $("#sympid").val();
                if ( sympid.length == 0 ) {
            		$.ajax({
            			cache: false,
            			async: false,
            			type: "GET",
            			url: "ressources/xml/getFromSecure.php",
            			data: "symp_email=" + $("#email").val() + "&xmlUrl=" + urlWebServices + "/amis/getinfo_v5.xml.php",
            			datatype: "xml",
						success: function(xml) {
    	    	            $(xml).find('xmlresponse').each(function(){
    							var code_email = $(this).find('email').text();
    							if ( code_email == 1 ) {
    								var inscription_type = $(this).find('inscription_type').text();
    								if ( inscription_type == 3 ) {
    									renseignerSympathisant(xml);
    								}
    								else {
    									jsUserMustBeAuthentificate = true;
    									$(".blocDivApparitionAlerte #courriel").html($("#email").val());
    									if ( $.browser.msie && $.browser.version=="6.0" ) {
    										$("#affectation").css("display", "none");
    										$("#civilite").css("display", "none");
    										$("#pays").css("display", "none");
    										$("#naissance").css("display", "none");
    									}
    									$("#divAuthentification").dialog("open");
    									$("#motdepasse").focus();
    								}
    							}
                            });
                        }
            		});				
                }
            }
		});

    	/* Demande de mot de passe oublié */
    	$("#chkOubli").click( function () {
    		if ( $("#chkOubli").attr("checked") == true ) {
    			$("#pPassword").css("visibility", "hidden");
    			$(":button:contains('Envoyer')").html("<span class=\"ui-button-text\">En recevoir un nouveau par email</span>");
    		}
    		else {
    			$("#pPassword").val("");
    			$("#pPassword").css("visibility", "visible");
    			$(":button:contains('En recevoir un nouveau par email')").html("<span class=\"ui-button-text\">Envoyer</span>");
    		}
    	});

        /**
         * Sur authentification réussie,
         * Prise des informations du sympathisant depuis le XML
         * Mise en place dans le formulaire
         * Mise à jour du récapitulatif
         *
         */
    	$("#btnConnexion").click( function () {

    		var courriel = $("#courriel").html();
    		var motdepasse = $("#motdepasse").val();
    
    		var mdpOubli = 0;
    		if ( $("#chkOubli").attr("checked") == true ) {
    			mdpOubli = 1;
                motdepasse = "";
    		}
    
    	    $.ajax({
    			type: "GET",
    			url: "ressources/xml/getFromSecure.php",
    			data: "symp_email=" + courriel + "&pass=" + motdepasse + "&mdpOubli=" + mdpOubli + "&privateKey=" + $("#privateKey").val() + "&xmlUrl=" + urlWebServices + "/amis/getinfo.xml.php",
    			datatype: "xml",
    	        success: function(xml) {
    	            $(xml).find('xmlresponse').each(function(){
    	                var code_retour = $(this).find('code_retour').text();
    	                var sympid = $(this).find('sympid').text();
    	                if ( code_retour == 1 && mdpOubli == 0 ) {
                            renseignerSympathisant(xml);
                            if ( $.browser.msie && $.browser.version=="6.0" ) {
								$("#affectation").css("display", "");
								$("#civilite").css("display", "");
								$("#pays").css("display", "");
								$("#naissance").css("display", "");
                            }
                            $("#divAuthentification").dialog('close');
    	                }
    	                else {
    	                	var msg = $(this).find('msg').text();
    	                	$("#msg").html(msg);
                            $("#chkOubli").attr("checked", false);
                			$("#pPassword").val("");
                			$("#pPassword").css("visibility", "visible");
                			$(":button:contains('En recevoir un nouveau par email')").html("<span class=\"ui-button-text\">Envoyer</span>");
    	                }
    	            });
    	        }
    
    	    });            

    	});
    
    });

/* ************************************ */
/* ************************************ */

    $(document).ready( function() {

		/** Initialisation de l'affichage */
		$("#radioOrganisation").css("display", "none");
        initSouscriptions();
    
        /** Charge la liste déroulante des pays */
		$.ajax({
			type: "GET",
			url: "ressources/xml/iso_3166-1_list_fr.xml",
			dataType: "xml",
			success: function(xml) {
				var cbOptions = "";
				$(xml).find("ISO_3166-1_Entry").each(function(){
					var countryName = $(this).find("ISO_3166-1_Country_name").text();
					var countryAlphaCode = $(this).find("ISO_3166-1_Alpha-2_code").text();
					cbOptions = cbOptions + "<option value=\"" + countryAlphaCode + "\">" + countryName + "</option>\n";
				});
				$("#pays").html(cbOptions);
				$("#pays").val("FR");
			}
		});

        /* Champs mettant à jour le récapitulatif */
        $(".setRecap").each(function(){
	    	var html_id = $(this).attr("id");
			$("#" + html_id).change(function() {
			     valeur = $("#" + html_id).val();
                 switch ( html_id ) {
                    case "pays":
                        $("#recap_pays").html( $("#pays option:selected").text() );
                        break;
                    default:
                        $("#recap_" + html_id).html( valeur.toUpperCase() );
                        break;
                 }
            });
        });

   	});    

/* ************************************ */
/* ************************************ */

/**
 * GESTION DU SYMPATHISANT
 * Contrôles JS pour tous les champs nécessaires au niveau de Sympathisant
 *
 */ 
    
    /**
     * Après authentification
     * Renseigner les champs du formulaire avec les données du sympathisant
     * Bloquer l'accès au changement d'adresse email
     * Rechercher spécifiquement l'abonnement à la newsletter (identifiant = 3)
     * Rechercher également l'abonnement à la brochure (identifiant = 64)
     *
     */
    function renseignerSympathisant(xml) {

        initSouscriptions();

        var champs = new Array("sympid", "nom", "prenom", "civilite", "organisation", "adresse", "adresse2", "cp", "ville", "pays", "naissance", "telephone", "abonnements");
        for ( champ in champs ) {
            $(xml).find('xmlresponse').each(function(){
                var valeur = $(this).find(champs[champ]).text();
                switch ( champs[champ] ) {
                	case "organisation":
                		if ( valeur != "" ) {
                			$("#radioOrganisationOui").attr("checked", true);
                			$("#radioOrganisationNon").attr("checked", false);
                			$("#radioOrganisation").css("display", "block");
                			$("#" + champs[champ]).val(valeur.toUpperCase());
                            $("#recap_" + champs[champ]).html( valeur.toUpperCase() );
                		}
                		else {
                			$("#radioOrganisationOui").attr("checked", false);
                			$("#radioOrganisationNon").attr("checked", true);
                			$("#radioOrganisation").css("display", "none");
                		}
                		break;
                    
                    case "pays":
                        $("#recap_pays").html( $("#pays option:selected").text() );
                        break;
                        
                    case "telephone":
                		$("#tel").val(valeur.toUpperCase());
                        $("#recap_tel").html( valeur.toUpperCase() );
                        break;
                        
                	case "abonnements":
                        $(this).find("abonnement").each(function(){
                            if ( $(this).text() == "3" ) {
									$("#radioChoixnewsletterNon").attr("checked", false);
									$("#radioChoixnewsletterOui").attr("checked", true);
                            }
                        });
                        manageSouscriptions();
                        break;
                    
                    default:
                		$("#" + champs[champ]).val(valeur.toUpperCase());
                        $("#recap_" + champs[champ]).html( valeur.toUpperCase() );
                		break;
                }

            });
        }

        $("#email").attr("readonly", true);
        
    }

    /**
     * Analyse les données du formulaire pour retour sur anomalie(s)
     *
     *
     */
    function analyserSympathisant() {

        var message = "";
        $("#messageEtape2").empty();

        if ( jsUserMustBeAuthentificate == true && $("#sympid").val() == "" ) {
            message = message + "<li><strong>Vous devez vous authentifier pour continuer votre don !</strong></li>";
        }            
        
		if ( !$("#radioOrganisationOui").is(":checked") && !$("#radioOrganisationNon").is(":checked") ) { 
            message = message + "<li>Etes-vous une société, une organisation ?</li>";
        }		
        if ( $("input[name=orga]:radio:checked").val() == "1" && $("#organisation").val() == "" ) {
            message = message + "<li>Vérifier votre dénomination</li>";
        }
        if ( $("#civilite").val() == "" ) {
            message = message + "<li>Vérifier votre civilité</li>";
        }           
		if ( $("#nom").val().length < 2 ) {
            message = message + "<li>Vérifier votre nom</li>";
		}
		if ( $("#prenom").val().length < 2 ) {
            message = message + "<li>Vérifier votre prénom</li>";
		}
		if ( $("#adresse").val().length < 2 ) {
            message = message + "<li>Vérifier votre adresse</li>";
		}
        if ( !isCodePostal( $("#cp").val() ) ) {
            message = message + "<li>Vérifier votre code postal</li>";
        }
		if ( $("#ville").val().length < 2 ) {
            message = message + "<li>Vérifier votre ville</li>";
		}
		if ( $("#email").val().length < 2 ) {
            message = message + "<li>Vérifier votre email</li>";
		}
        else {
            if ( !isEmail( $("#email").val() ) ) {
                message = message + "<li>Vérifier votre email</li>";
            }
        }
        if ( !isAnneeNaissance( $("#naissance").val() ) ) {
            message = message + "<li>Vérifier votre année de naissance</li>";
        }
        if ( !$("#radioChoixnewsletterOui").is(":checked") && !$("#radioChoixnewsletterNon").is(":checked") ) { 
            message = message + "<li>Souhaitez-vous recevoir la newsletter de la Fondation ?</li>";
        }
        /*
        if ( !$("#radioChoixbrochureLegsOui").is(":checked") && !$("#radioChoixbrochureLegsNon").is(":checked") ) { 
            message = message + "<li>Souhaitez-vous recevoir la brochure pour les dons et legs de la Fondation ?</li>";
        }
        */

        if ( message != "" ) {
            boolShowAlerte = true;
            $("#messageEtape2").append( "<ul>" + message + "</ul>" );
            return false;	
        }
        
        return true;
        
    }

    /** Analyse l'email */
    function isEmail(email) {
        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return filter.test(email);
    }    

    /**
     * Analyse du code postal selon le pays
     * Si pays FRANCE, alors vérfiier la correspondance du code postal sur 5 chiffres
     * Sinon, ne rien vérifier
     */
    function isCodePostal(code_postal) {

        if ( $("#pays").val() != "FR" ) {
            return true;
        }
        else {
            var filter = /^[0-9]{5}$/;
            return filter.test(code_postal);    
        }
    }    
	
    /**
     * Analyse de l'année de naissance
     */
    function isAnneeNaissance(naissance) {
        if ( $("#naissance").val() == "" ) {
            return true;
        }
        else {
            var filter = /^[0-9]{4}$/;
            return filter.test(naissance);    
        }
    }
    
    
    /**
     * Gestion des souscriptions : abonnements / engagements
     * Nécessite la classe "souscription" sur les boutons radio impactés
     *
     */
    function initSouscriptions() {
        $(".engagement").each(function(){
            if ( $(this).val() == "" ) {
                $(this).attr("checked", true);
            }
            else {
                $(this).attr("checked", false);
            }
        });
    }
    function manageSouscriptions() {
        var tblInscriptions = new Array();
        var tblDesinscriptions = new Array();
        $(".abonnement").each(function(){
            if ( !$(this).is(":checked") ) {
                tblDesinscriptions.push( $(this).val() );
            }
            else {
                tblInscriptions.push( $(this).val() );
            }
        });
        $(".engagement").each(function(){
            if ( $(this).is(":checked") ) {
                tblInscriptions.push( $(this).val() );
            }
        });
        
        var souscriptions = tblDesinscriptions.toString();
        if ( souscriptions == "," ) {
            souscriptions = "";    
        }
        if ( souscriptions.substring(0, 1) == "," ) {
            souscriptions = souscriptions.substring(1, souscriptions.length);
        }
        if ( souscriptions.substr(souscriptions.length - 1) == "," ) {
            souscriptions = souscriptions.substr(0, souscriptions.length - 1);
        }
        $("#unsouscriptions").val( souscriptions );


        var souscriptions = tblInscriptions.toString();
        if ( souscriptions == "," ) {
            souscriptions = "";    
        }
        if ( souscriptions.substring(0, 1) == "," ) {
            souscriptions = souscriptions.substring(1, souscriptions.length);
        }
        if ( souscriptions.substr(souscriptions.length - 1) == "," ) {
            souscriptions = souscriptions.substr(0, souscriptions.length - 1);
        }
        $("#souscriptions").val( souscriptions );

    }     
    
    
