function handleResponse(response, statusText)  {
    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property
    if (response.result == 'ok'){
        var content = [
            '<img src="', publicUri, '/photos/message_prospect_registration_ok.jpg" width="623" height="240" alt="Lien pour commencer un dialogue avec votre coach personnel envoy&eacute; par email" />',
            '<img src="http://ww2.affilcenter.com/tags/profil.cfm?tuid=170&email=', response.email, '" width=1 height=1 border=0>',
            '<img src="http://tracking.publicidees.com/check.php?comid=115666&progid=1516&uniqid=', response.email, '" width="0" height="0" border="0">',
            '<img width="0" height="0" src="http://ext.trackingwiz.com/Aspx/pixel.aspx?tpid=i109166aa&IDADV=', response.email, '"/>',
            '<img src="http://tbl.tradedoubler.com/report?organization=1489783&event=196288&leadNumber=', response.email, '"/>'
        ];
        $.facybox(content.join(""));
        // send Tag
        if (undefined !== response.email) {
            sendInscriptionConfirmationTag(response.email);
        }
    } else  if (response.result == 'error') {
        $.facybox('<div style="width:400px">'+response.errorMsg+'</div>');
    }
    else if (response.result == 'redirectToChat'){
    	alert("Vous êtes déjà inscrit avec l'adresse indiquée, nous allons vous rediriger automatiquement vers le chat");
    	document.location="/dialoguer-avec-un-coach";
    }
    else if ("ajaxError" === response.result) {
        if (undefined !== response.errors) {
            $.each(response.errors, function (id, error) {
                $("#errorPlaceHolderPicto_" + id).html('<em class="error"></em>');
                $("#errorPlaceHolder_" + id).html(error.join("<br />")).closest("tr").show();
            });
        }
    }
    else if ("ajaxSuccess" === response.result) {
        if (undefined !== response.url) {
            document.location = response.url;
        }
    }
    else if ("notProspect" === response.result) {
        if (undefined !== response.form) {
            $.facybox(response.form);
            attachValidationFormProspect();
        }
    }
    else alert("reponse non reconnue:"+response.result);
        return false;
}


function attachValidationFormProspect () {

	var rulesArray = new Array();

	rulesArray['firstName'] = {required : true};

	if($('#age').length>0 &&
	   $('#height').length>0 &&
	   $('#weight').length>0 ) {
		    rulesArray['age'] =          {required: true, min : 18, digits:true};
		    rulesArray['height'] =       {required: true, min : 1, digits:true};
		    rulesArray['weight'] =       {required: true, min : 1, digits:true};
	   		rulesArray['wantedWeight'] = {required: true, min : 1, digits:true};
	   }


    $("#formProspect").validate({
        submitHandler: function(form) {
            var customUrl = $(form).attr('action')+"?ajax=true";
            $.ajax({
                url : customUrl,
                success:	handleResponse,
                data : $(form).serialize(),
                dataType:	'json'
            });
            return false;
        },
        success: function(label) {
            label.addClass("success");
            var obj =$("#errorPlaceHolder_"+label.attr("for"));
                obj.hide();
        },
        messages :{
            emailAddress :" ",
            age :" ",
            height :" ",
            weight :" ",
            wantedWeight :" ",
            firstName :" "
        },
        rules: rulesArray,
        errorElement: "em",
        showErrors: function(errorMap, errorList) {
            for (var i in errorMap) {
                var obj =$("#errorPlaceHolder_"+i);
                obj.hide().show();
            }
            this.defaultShowErrors();
        },
        errorPlacement: function(error, element) {
            error.appendTo("#errorPlaceHolderPicto_"+element.attr("id"));
        }
    });
}

$(document).ready(function(){
    attachValidationFormProspect();
    $("#formAbo").validate({
        submitHandler: function (form) {
            $.post($(form).attr("action"), $(form).serialize(), handleResponse, "json");
            return false;
        },
        success: function (label) {
            label.attr("class", "success");
            $("#errorPlaceHolder_"+label.attr("for")).closest("tr").hide();
        },
        messages: {
            last_name: "Le nom est obligatoire.",
            first_name: "Le pr\u00E9nom est obligatoire.",
            email_address: {
                required: "L'email est obligatoire.",
                email: "L'adresse email n'est pas au bon format.",
                equalTo: "Votre adresse email de confirmation est incorrecte."
            },
            confirm_email_address: {
                required: "La confirmation de l'email est obligatoire.",
                email: "L'adresse email n'est pas au bon format.",
                equalTo: "Votre adresse email de confirmation est incorrecte."
            },
            term3: {
                required: "Merci de bien vouloir accepter les conditions g\u00E9n\u00E9rales d'utilisation du site."
            }
        },
        rules: {
            last_name: {
                required: true
            },
            first_name: {
                required: true
            },
            email_address: {
                required: true,
                email: true
            },
            confirm_email_address: {
                required: true,
                email: true,
                equalTo: "#email_address"
            },
            term3: {
                required: true
            }
        },
        showErrors: function (errorMap, errorList) {
            var id;
            $(errorList).each(function (i, error) {
                id = $(error.element).attr("id");
                $("#errorPlaceHolder_" + id).html(error.message).closest("tr").show();
                $("#errorPlaceHolderPicto_" + id).empty();
            });
            this.defaultShowErrors();
        },
        errorPlacement: function (error, element) {
            $("#errorPlaceHolderPicto_"+element.attr("id")).html(error.empty());
        },
        errorElement: "em"
    });
    $("#btn_cliquez").click(function (event) {
        event.preventDefault();
        $.getJSON("/index/is-prospect", [], handleResponse);
    });
});

