
/**
 * treatment of ajax prospect response
 * @param response
 * @param statusText
 * @return mixed
 */
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'){
    	
    	//-----------------------------------------------------//
		/*******
		 * Affiche les tags puis redirige la page
		 *******/
    	 var content = [
                '<img width="0" height="0" src="http://ext.trackingwiz.com/Aspx/pixel.aspx?tpid=i1091ee32&IDADV=', response.email, '"/>', // CS tracking tag
                '<img src="http://mediastay.directtrack.com/track_lead/643/', response.email, '"/>'
            ];
    	
    	 $("#prospect-response").html(content.join(""));
    	 var pr = document.getElementById("prospect-response");
    	 
    	 //waitLoadImages(pr.getElementsByTagName("img"), function() {
    		 document.location="bilan/choix-morphotype.html?" + jQuery.param(response);
    	 //});
    	 
        
        //-----------------------------------------------------//
    } else  if (response.result == 'error') {
        $.facybox('<div style="width:400px">'+response.errorMsg+'</div>');
    }
    else if (response.result == 'redirectToChat'){
    	document.location = publicUrl + "/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;
}

/**
 * A simple "barrier" type synchronization mechanism.
 * The objective is to wait until all the images have loaded
 * before calling the callback function.
 * 
 * @param imageArray
 * @param callback
 */
function waitLoadImages(imageArray, callback) {
	var len = imageArray.length;
	var limit = len;
	for (var i=0; i < limit; i++) {
		
		imageArray[i].onload = function() {
			--len;
			if (len == 0) {
				callback();
			}
		}
	}
}

function attachValidationFormProspect () {
    var rulesArray = new Array();
    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};
    rulesArray['emailAddress'] =    {required: true, email:true};
    rulesArray['firstName'] =    {required: true};

    $("#morphobilan").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) {
            var id = label.attr("for");
            $("#errorPlaceHolder_" + id).hide();
            $("#errorPlaceHolderPicto_" + id).html('<img src="' + publicUri + '/img/picto_morpho_ok.gif" width="25" height="16" alt="Ok" />');
        },
        messages :{
            emailAddress :" ",
            age :" ",
            height :" ",
            weight :" ",
            wantedWeight :" ",
            firstName :" "
        },
        rules: rulesArray,
        showErrors: function(errorMap, errorList) {
            var i;
            for (i in errorMap) {
                $("#errorPlaceHolder_"+i).hide().show();
            }
            this.defaultShowErrors();
        },
        highlight: function (element, errorClass) {
            var id = $(element).attr("id");
            $("#errorPlaceHolderPicto_" + id).html('<img src="' + publicUri + '/img/picto_morpho_nok.gif" width="25" height="16" alt="Erreur" />');
        }
    });
}

$(document).ready(function(){
    attachValidationFormProspect();
    $("#form_inscription").validate({
        submitHandler: function (form) {
            $.post($(form).attr("action"), $(form).serialize(), handleResponse, "json");
            return false;
        },
        success: function (label) {
            var id = label.attr("for");
            $("#errorPlaceHolder_" + id).hide();
            $("#errorPlaceHolderPicto_" + id).html('<img src="' + publicUri + '/img/picto_morpho_ok.gif" width="25" height="16" alt="Ok" />');
        },
        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."
            },
            promo_code: {
            	required: "Cette valeur est obligatoire et ne peut \u00EAtre vide."
            },
            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"
            },
            promo_code: {
            	required: true
            },
            term3: {
                required: true
            }
        },
        showErrors: function (errorMap, errorList) {
            var id;
            $(errorList).each(function (i, error) {
                id = $(error.element).attr("id");
                $("#errorPlaceHolder_" + id).html(error.message).show();
                $("#errorPlaceHolderPicto_" + id).html('<img src="' + publicUri + '/img/picto_morpho_nok.gif" width="25" height="16" alt="Erreur" />');
            });
            this.defaultShowErrors();
            viewPromocodeValidator();
        },
        errorPlacement: function (error, element) {
            return false;
        }
    });
    $("#btn_cliquez").click(function (event) {
        event.preventDefault();
        $.getJSON(publicUrl + "/index/is-prospect", [], handleResponse);
    });

});

function viewPromocodeValidator() {
    var elem = $(".rowform_error#errorPlaceHolder_promo_code");
	if(elem.html != null || elem.html != '' || elem.html != undefined) {
		elem.show();
	} else {
		elem.hide();
	}
}

