﻿/*____________________________________________
|     _     _ ___      __ _                   |
|    (_)___(_) __|___ / _| |_ __ _ _ _ ___    |
|    | |_ /| \__ | _ \  _|  _/ _` | '_/ -_)   |
|    |_/__||_|___|___/_|  \__\__,_|_| \___|   |
|                                             |
|       ©2010 iziSoftware - Version 1.0       |
|_____________________________________________|

WESendMail : Envoie les données d'un formulare par email

*/


//Démarrage
$(document).ready(function() {

    WESendMailCoreJs.Initialize();

});


var WESendMailCoreJs = {

    //Propriétés
    CurrSendMail: null,            //SendMail courrent
    LoadingOpen: false,

    //Initialisation des menus
    Initialize: function() {
        for (Elem in OEConfWESendMail) {
            WESendMailCoreJs.IniSendMail(Elem)
        }

        // alert(options.url);
        /*$('#XForm').ajaxStart(function(e) {


        });

        $('#XForm').ajaxStop(function(e) {
            //Pas la fin du loading sinon interference avec la réponse
        });*/

        //En cas d'erreur ajax
        $('#XForm').ajaxError(function(e) {
            OECenterLoading.Close(); //arret loading
            response = WEEdSiteCommon.GetLocalizableString(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.NoPopupMessage);
            response += "\n" + data.State + " - Error Ajax."
            if (response != "") OEPopupModalJs.ShowModalPopup(response, WEInfoPage.RelativePath + "WEFiles/Image/warning.png"); //Affichage du message d'erreur du form en cours

        });

        
        
    },


 
    //Initialisation du sendmail
    IniSendMail: function(Elem) {

        DataWESendMail = OEConfWESendMail[Elem]; //Contenu du json

        // Option d'envoi AJAX 
        var options = {
            beforeSubmit: this.showRequest,
            success: this.showResponse,
            data: null,
            url: WEInfoPage.RelativePath + 'WEFiles/Server/WESendMail_v' + WEInfoPage.OEVersion + '.php'//,  // your upload script
            //	        dataType:      'json' // Le retour ne doit pas être en JSON lorsque le form peut contenir un upload
        };


        //recup des données
        var DataButtonSubmitID = DataWESendMail.FormLinks.ButtonSubmitID;
        var DataElementsID = DataWESendMail.FormLinks.ElementsID;


        //Evenement sur le bouton submit du sendmail : Elem
        var ButtonSubmit = $("#" + DataButtonSubmitID);
        if (ButtonSubmit.size() < 1) { return }
        ButtonSubmit.click(function(e) {
            // memorisation du send mail en cours
            WESendMailCoreJs.CurrSendMail = Elem;

            //Lancement du submit du form
            WESendMailCoreJs.submit(Elem, options);
            return false;

        });

        /*  
        //Evenement sur le bouton cancel
        if (DataButtonCancelID.lenght>0) {
        var ButtonCancel = $("#"+DataButtonCancelID);
        if (ButtonCancel.size()<1) {return}
        ButtonCancel.click(function(e) {
        WESendMailCoreJs.Cancel();
        });
        }
        */

    },

    //Fonction executée au submit
    submit: function(Elem, options) {

        if (window.location.protocol.match("file+")) {
            alert(WEEdSiteCommon.HtmlDecode(WEInfoPage.EditorTexts["ExecutionOnlyOnline"])); // "Impossible d'executer cette action depuis OpenElement.\n Vous devez mettre en ligne votre page.");
            return false;
        }
        if (WEInfoPage.PHPVersion == "" || WEInfoPage.PHPVersion == 'undefined' || WEInfoPage.PHPVersion == null ) {
            alert("WESendMail : "+WEEdSiteCommon.HtmlDecode(WEInfoPage.EditorTexts["NoPHP"])); // Impossible d'exécuter cette action. Le PHP n'est pas installé sur votre hébergement. Veuillez contacter votre hébergeur pour l'activer.
            return false;
        }
        
        
        //Creation des data supplementaires à creer avec le SendMail en cours de submit
        OECenterLoading.Open(); //Lancement loading
        options.data = { PagePath: WEInfoPage.PageAssociatePath, WESendMailID: Elem, Culture: WEInfoPage.Culture, RelativePath: WEInfoPage.RelativePath, OEVersion: WEInfoPage.OEVersion };
        $('#XForm').ajaxSubmit(options);
        return false;
    },



    //Fonction BeforeSubmit (validation)

    showRequest: function(formData, jqForm, options) {

        //Validation du form
        var validatorsOk = true;

        DataWESendMail = OEConfWESendMail[options.data.WESendMailID]; //Contenu du json
        var DataElementsID = DataWESendMail.FormLinks.ElementsID;

        for (ID in DataElementsID) {
            var elm = $("#" + ID).find(":input"); //Champ de form
            if (elm.size() < 1) continue;
            var Value = elm.fieldValue(); //valeur du champ
            if (!WEFormValidator.Execute($("#" + ID), Value)) validatorsOk = false; // validation de la valeur

        }
        if (!validatorsOk) { OECenterLoading.Close(); }
        return validatorsOk;

    },

    //Fonction AfterSubmit, affichage du resultat
    //showResponse : function (data, statusText)  {
    showResponse: function(data, statusText, xhr, $form) {

        OECenterLoading.Close(); //arret loading
        dataInit = data;

        //alert(data);
        data = data.substr(data.indexOf("{"), data.lastIndexOf("}") - data.indexOf("{") + 1);
        try {

            data = JSON.parse(data);


            var response;
            var popupResponse = OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.PopupConfirm;
            var RedirectResponce = OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.PageReturn;

            // Reponse à l'envoi      
            if (statusText == 'success') {
                if (data.State == "success") {
                    // si il y a réponse c'est soit popup, soit redirection 
                    if (popupResponse == true) {
                        response = WEEdSiteCommon.GetLocalizableString(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.OkpopupMessage);
                        if (response != "") OEPopupModalJs.ShowModalPopup(response, WEInfoPage.RelativePath + "WEFiles/Image/information2.png");
                    }
                    if (RedirectResponce == true) {
                        var link = WEEdSiteCommon.LinkGetPath(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.OkPageLink);
                        if (link != "") window.location = link;
                    }

                } else {
                    if (popupResponse == true) {
                        response = WEEdSiteCommon.GetLocalizableString(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.NoPopupMessage);
                        response += "<br /><br /><span style='font-size: 12px;font-style: italic;'>" + data.State + " - " + data.ErrorDescription + "</span>";
                        if (response != "") OEPopupModalJs.ShowModalPopup(response, WEInfoPage.RelativePath + "WEFiles/Image/warning.png");
                    }
                    if (RedirectResponce == true) {
                        var link = WEEdSiteCommon.LinkGetPath(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.NoPageLink);
                        if (link != "") window.location = link;
                    }
                }
            } else {

		
                response = GetLocalizableString(OEConfWESendMail[WESendMailCoreJs.CurrSendMail].SendMailResponse.NoPopupMessage);

                response += "\n" + "Erreur Ajax";
                OEPopupModalJs.ShowModalPopup(response, WEInfoPage.RelativePath + "WEFiles/Image/warning.png");
            }
        }
        catch (Err) {
            response = WEEdSiteCommon.HtmlDecode(WEInfoPage.EditorTexts["NoResponse"]) + "<br />" + data +"<br /><span style='font-size:12px'>Error :" + Err.description + dataInit +"</span>"    // "Pas de réponse du serveur!<br /> Veuillez réessayer ultérieurement.";
            OEPopupModalJs.ShowModalPopup(response, WEInfoPage.RelativePath + "WEFiles/Image/warning.png");
             //alert("Error : --"+Err.description +"\n\n"+dataInit); //Affichage de l'erreur lorsque l'affichage standard ne fonctionne pas + affichage du retour du php (en cas d'erreur php non parsable
        }



    }

} 
