var Forms = function () {};

Forms.Init = function ()
{   
};

/*
 * Chargement de l'application
 */
Forms.Load = function (parameter)
{
    this.LoadEvent();
     
    return;
    parameter = serialization.Decode(parameter);

    Forms.formId = parameter['formId'];
    Forms.ReturnedFunction = parameter['ReturnedFunction'];

    this.LoadEvent();

    if (typeof (Forms.formId) != "undefined")
    {
        FormsAction.LoadQuestionReponse('', Forms.formId);
    } else
    {
        //Charge les formulaires de l'utilisateur
        FormsAction.LoadMyForms();
    }
};

/*
 * Chargement des �venements
 */
Forms.LoadEvent = function ()
{
    Dashboard.AddEventAppMenu(Forms.Execute, "", "Forms");
    Dashboard.AddEventWindowsTool("Forms");
    
    Forms.InitTabForms();
    Forms.InitTabResponse();
};

/***
 * Init the tab Mooc
 */
Forms.InitTabForms = function () {
    //Catégory
    Event.AddById("btnAddForm", "click", () => {
        Forms.ShowAddForm("")
    });

    EntityGrid.Initialise('gdForm');
};

/**
 * Init the response Tab
 */
Forms.InitTabResponse = function(){
    Event.AddById("lstForm", "click", Forms.LoadResponse);
};

/****
 * Edit a mooc
 * @param {type} categoryId
 * @returns {undefined}
 */
Forms.EditForm = function (formId) {
    Forms.ShowAddForm(formId);
};

/**
 * Edit a Forms
 * @param {type} moocId
 * @returns {undefined}
 */
Forms.ShowAddForm = function (formId) {

    Dialog.open('', {"title": Dashboard.GetCode("Forms.AddForm"),
        "app": "Forms",
        "class": "DialogAdminForm",
        "method": "AddForm",
        "type": "full",
        "params": formId
    });
};


/***
 * Rafraichit la tab des tutoriel
 * @returns {undefined}
 */
Forms.ReloadForm = function (data) {
    let gdForms = Dom.GetById("gdForm");
    gdForms.parentNode.innerHTML = data.data;
    Forms.InitTabForm();
};



/***
 * Supprime une catégorie
 * @param {type} categoryId
 * @returns {undefined}
 */
Forms.DeleteForm = function (formId) {

    Animation.Confirm(Language.GetCode("Forms.ConfirmRemoveForm"), () => {

        let data = "Class=Forms&Methode=DeleteForm&App=Forms";
        data += "&formId=" + formId;

        Request.Post("Ajax.php", data).then(data => {
            Dashboard.StartApp("",'Forms', "");
        });
    });
};

/**
 * Load respinse
 */
Forms.LoadResponse = function(e){
    let formId = e.srcElement.value;

    if(formId != ""){
        let data = "Class=Forms&Methode=ShowByGroup&App=Forms";
        data += "&FormId=" + formId;

        Request.Post("Ajax.php", data).then(data => {
            Animation.Load("userReponseContainer", data);

        });
    }
};

/*
 * Execute une fonction
 */
Forms.Execute = function (e)
{
    //Appel de la fonction
    Dashboard.Execute(this, e, "Forms");
    return false;
};

/*
 *	Affichage de commentaire
 */
Forms.Comment = function ()
{
    Dashboard.Comment("Forms", "1");
};

/*
 *	Affichage de a propos
 */
Forms.About = function ()
{
    Dashboard.About("Forms");
};

/*
 *	Affichage de l'aide
 */
Forms.Help = function ()
{
    Dashboard.OpenBrowser("Forms", "{$BaseUrl}/Help-App-Forms.html");
};

/*
 *	Affichage de report de bug
 */
Forms.ReportBug = function ()
{
    Dashboard.ReportBug("Forms");
};

/*
 * Fermeture
 */
Forms.Quit = function ()
{
    Dashboard.CloseApp("", "Form");
};

/*
 * Cr�e un nouveau document
 */
Forms.New = function ()
{
    var params = Array();
    params['Title'] = "Forms.New";

    Dashboard.OpenPopUp('Form', 'DetailForm', '', '', '', 'FormAction.RefreshForm();', serialization.Encode(params), '');
};

Forms.InitAdminWidget = function(){
    
};

// Action Utilisateur
FormAction = function () {};

/**
 * Charge les formulaire de l'utilisateur
 * @returns {undefined}
 */
FormAction.LoadMyForm = function ()
{
    FormAction.FormId = "";

    var data = "Class=Form&Methode=LoadForm&App=Form";
    Dashboard.LoadControl("dvDesktop", data, "", "div", "Form");

    //Ajoute les evements
    //FormAction.AddEvent();
};
/*
 * Rafraichit la liste des formulaires
 */
FormAction.RefreshForm = function ()
{
    var data = 'App=Form&Methode=LoadForm';
    Dashboard.LoadControl("dvDesktop", data, "", "div", "Form");

    //TODO
    if (typeof (Forms.IdProjet) != 'undefined')
    {
        eval(Forms.ReturnedFunction);
    }
};

/**
 * Charge toutes les donn�es du formulaire
 
 */
FormAction.LoadForm = function (control, idForm)
{
    var data = 'App=Form&Methode=LoadForm';
    data += '&idForm=' + control.id;
    data += '&idForm=' + idForm;

    FormAction.FormId = idForm;

    Dashboard.LoadControl("dvDesktop", data, "", "div", "Form");
};

/*
 * Edite un formulaire
 */
FormAction.EditForm = function (id)
{
    var parameter = Array();
    parameter["idEntity"] = id;
    parameter['Title'] = "Forms.Edit";

    Dashboard.OpenPopUp('Form', 'DetailForm', '', '', '', 'FormAction.RefreshForm();', serialization.Encode(parameter), '');
};

/*
 * Supprime un formulaire
 */
FormAction.DeleteForm = function (id)
{
    if (Dashboard.ConfirmDelete())
    {
        var data = 'App=Form&Methode=DeleteForm';
        data += "&idEntity=" + id;

        Dashboard.LoadControl("dvDesktop", data, "", "div", "Form");

        /// JAjax.GetRequest('Ajax.php');
    }
};

/*
 * Charge les questions et les r�ponses
 */
FormAction.LoadQuestionReponse = function (control, idForm)
{
    var data = 'App=Form&Methode=LoadQuestionReponse';
    if (control != '')
    {
        data += "&idEntity=" + idForm;
        FormAction.FormId = idForm;
    } else
    {
        data += "&idEntity=" + idForm;
        FormAction.FormId = idForm;

    }

    Dashboard.LoadControl("dvDesktop", data, "", "div", "Form");
};

/*
 * Edite un formulaire
 */
FormAction.DetailQuestion = function (id)
{
    var parameter = Array();
    parameter["idForm"] = id;
    parameter['Title'] = "FormQuestion.Edit";

    Dashboard.OpenPopUp('Form', 'DetailQuestion', '', '', '', 'FormAction.RefreshQuestion();', serialization.Encode(parameter), '');
};
/*
 * Initialise le type de reponse
 */
FormAction.SelectResponseType = function ()
{
    var lstType = document.getElementById("lstType");
    var dvResponse = document.getElementById("dvResponse", "div", "Form");

    switch (lstType.value)
    {
        case '0' :
            dvResponse.innerHTML = "<input type='text' disabled='disabled' />";
            break;
        case '1':
            dvResponse.innerHTML = "<textArea disabled='disabled' ></textarea>";
            break;
        case '2':
            var TextControl = "<div id='lstResponse'><input type='Radio'  name='rb'/>";
            TextControl += "<input type='text' id='tbResponseText' /></div>";
            TextControl += "<input type='button' id='btnAddResponse' class='btn btn-info' value='Ajouter une r&eacute;ponse' onclick='FormAction.AddResponse(\"radio\")' />";

            dvResponse.innerHTML = TextControl;
            break;
        case '3':
            var TextControl = "<div id='lstResponse'><input type='checkbox'  name='cb'/>";
            TextControl += "<input type='text' id='tbResponseText' /></div>";
            TextControl += "<input type='button' class='btn btn-info'  id='btnAddResponse' value='Ajouter une r&eacute;ponse' onclick='FormAction.AddResponse(\"check\")' />";

            dvResponse.innerHTML = TextControl;
            break;
        case '4' :
            var TextControl = "<div id='lstResponse'>";
            TextControl += "<input type='text' id='tbResponseText' /></div>";
            TextControl += "<input type='button' class='btn btn-info' id='btnAddResponse' value='Ajouter une r&eacute;ponse' onclick='FormAction.AddResponse(\"list\")' />";

            dvResponse.innerHTML = TextControl;
            break;
    }
};
/*
 * Ajoute une r�ponse
 */
FormAction.AddResponse = function (type)
{
    var dvResponse = document.getElementById("lstResponse");

    switch (type)
    {
        case 'radio':
            var span = document.createElement("div");

            var rb = document.createElement('input');
            rb.type = 'radio';
            rb.name = "rb";
            span.appendChild(rb);

            var tb = document.createElement('input');
            tb.type = 'text';
            tb.id = "tbResponseText";
            span.appendChild(tb);

            var img = document.createElement('i');
            img.className = 'icon-remove';
            img.title = "Supprimer";
            img.innerHTML = "&nbsp;";
            Dashboard.AddEvent(img, "click", FormAction.DelResponse);
            span.appendChild(img);

            dvResponse.appendChild(span);
            break;
        case 'check':

            var span = document.createElement("div");

            var rb = document.createElement('input');
            rb.type = 'checkbox';
            rb.name = "rb";
            span.appendChild(rb);

            var tb = document.createElement('input');
            tb.type = 'text';
            tb.id = "tbResponseText";
            span.appendChild(tb);

            var img = document.createElement('i');
            img.className = 'icon-remove';
            img.tilte = "Supprimer";
            img.innerHTML = "&nbsp;";
            Dashboard.AddEvent(img, "click", FormAction.DelResponse);
            span.appendChild(img);

            dvResponse.appendChild(span);


            break;
        case 'list':

            var span = document.createElement("div");

            var rb = document.createElement('input');
            rb.type = 'text';
            span.appendChild(rb);

            var img = document.createElement('i');
            img.className = 'icon-remove';
            img.tilte = "Supprimer";
            img.innerHTML = "&nbsp;";
            Dashboard.AddEvent(img, "click", FormAction.DelResponse);
            span.appendChild(img);

            dvResponse.appendChild(span);
            break;
    }
};

/**
 * Supprime une réponse
 **/
FormAction.DelResponse = function (e)
{
    control = e.srcElement || e.target;
    FormAction.DeleteResponse(control);
};

/*
 * Supprime la r�ponse
 *
 */
FormAction.DeleteResponse = function (control)
{
    control.parentNode.parentNode.removeChild(control.parentNode);
};

/*
 * Enregistre la question et les r�ponses
 */
FormAction.SaveQuestion = function (idForm, idEntite)
{
    //Recuperation des contr�les
    var Libelle = document.getElementById('Libelle');
    var Commentaire = document.getElementById('Commentaire');
    var lstType = document.getElementById('lstType');

    if (Libelle.value != "" && lstType.value != "")
    {

        var responses = Array();

        //Recuperation des reponses
        if (lstType.value == '2' || lstType.value == '3' || lstType.value == '4')
        {
            var dvResponse = document.getElementById("lstResponse");
            var controls = dvResponse.getElementsByTagName('input');

            for (i = 0; i < controls.length; i++)
            {
                if (controls[i].type == 'text')
                {
                    responses.push(controls[i].value + "!!" + controls[i].name);
                }
            }
        }

        var JAjax = new ajax();
        JAjax.data = 'App=Form&Methode=SaveQuestion';
        JAjax.data += '&Libelle=' + Libelle.value;
        JAjax.data += '&Commentaire=' + Commentaire.value;
        JAjax.data += '&lstType=' + lstType.value;
        JAjax.data += "&idForm=" + idForm;
        JAjax.data += "&idEntite=" + idEntite;

        if (responses.length > 0)
        {
            JAjax.data += '&response=' + responses.join('_-');
        }
        //Resultat
        var lbResultQuestion = document.getElementById('jbForm');
        lbResultQuestion.innerHTML = JAjax.GetRequest('Ajax.php');
    } else
    {
        alert(Dashboard.GetCode("Forms.FieldError"));
    }
};

/*
 * Rafraichit la liste des questions
 */
FormAction.RefreshQuestion = function ()
{
    FormAction.LoadQuestionReponse('', FormAction.FormId);
};

/*
 * Suprrime la question
 */
FormAction.DeleteQuestion = function (idQuestion)
{
    var JAjax = new ajax();
    JAjax.data = 'App=Form&Methode=DeleteQuestion';
    JAjax.data += "&idEntite=" + idQuestion;

    JAjax.GetRequest('Ajax.php');

    FormAction.LoadQuestionReponse('', FormAction.FormId);
};

/**
 * Permet  de tester le questrionnaire
 */
FormAction.TryForm = function (idForm)
{
    var parameter = Array();
    parameter["idForm"] = idForm;
    parameter["Title"] = "Forms.answer";

    Dashboard.OpenPopUp('Form', 'TryForm', '', '', '', '', serialization.Encode(parameter), '');

};

/**
 * Affiche les réponses du forulaire groupé 
 * @param {type} formId
 * @returns {undefined}
 */
FormAction.ShowByGroup = function (formId)
{
    var data = "Class=Forms&Methode=ShowByGroup&App=Forms";
    data += "&FormId=" + formId;

    Request.Post("Ajax.php", data).then(data => {
        Animation.Load("userReponseContainer", data);
    });
};

/**
 * Affiche les réponses du forulaire par utilisateur 
 * @param {type} formId
 * @returns {undefined}
 */
FormAction.ShowByUser = function (formId)
{
    var data = "Class=Forms&Methode=ShowByUser&App=Forms";
    data += "&FormId=" + formId;

    Request.Post("Ajax.php", data).then(data => {
        Animation.Load("userReponseContainer", data);
    });
};

FormAction.SendForm = function ()
{
    alert('TODO');
};

