// SETTINGS
var contratsTypesConf = {
    type                          : "contrats type",
    baseURL                       : "contrats_types.php",
    // LIST
    list_selector                 : "#contratsTypesList",
    // FILTRES
    filtres_selector              : "#contratsTypesSearch select",
    // VIEW
    view_modalSelector            : "#modalViewContratsType",
    view_btnSelector              : ".btnViewContratsType",
    // ADD
    add_modalSelector             : "#modalAddContratsType",
    add_btnSelector               : "#btnAddContratsType",
    // EDIT
    edit_modalSelector            : "#modalEditContratsType",
    edit_btnSelector              : ".btnEditContratsType",
    // DELETE
    delete_modalSelector          : "#modalDeleteContratsType",
    delete_btnSelector            : ".btnDeleteContratsType",
}

// MODALS
var modalViewContratsType    = false;
var modalAddContratsType     = false;
var modalEditContratsType    = false;
var modalDeleteContratsType  = false;

$(document).ready( function() {
    // LIST LOADER
    initListProgressLoad($(contratsTypesConf.list_selector), contratsTypesConf.baseURL, contratsTypesConf.type+" list");
    
    // FILTRES
    $(contratsTypesConf.filtres_selector).initFiltreSelect();
    
    // VIEW
    modalViewContratsType = $(contratsTypesConf.view_modalSelector);
    if(modalViewContratsType.length>0) {
        initViewContratsType();
        // VIEW REQUEST
        var id = getUrlParameter("ref");
        if(id!==false && parseInt(id)>0 && current_page == "contratsTypes") {
            modalViewContratsType_clear(modalViewContratsType);
            modalViewContratsType_loadDatas(modalViewContratsType, id);
        }
    }
    
    // ADD
    modalAddContratsType = $(contratsTypesConf.add_modalSelector);
    if(modalAddContratsType.length>0) initAddContratsType();

    // EDIT
    modalEditContratsType = $(contratsTypesConf.edit_modalSelector);
    if(modalEditContratsType.length>0) initEditContratsType();

    // DELETE
    modalDeleteContratsType = $(contratsTypesConf.delete_modalSelector);
    if(modalDeleteContratsType.length>0) initDeleteContratsType();
});

/***** MODAL VIEW *****/
function initViewContratsType() {
    // INIT VIEW BTNs
    var initBtnFct = function() { modalForm_initBtnView(
        $(contratsTypesConf.view_btnSelector),        // BTNs
        modalViewContratsType,                        // MODAL
        modalViewContratsType_clear,                  // CLEAR FUNCTION
        modalViewContratsType_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

    // CANCEL
    modalViewContratsType.on('hidden.bs.modal', function() { modalViewContratsType_clear(modalViewContratsType); });
}

function modalViewContratsType_loadDatas(modal, id) {
    $.post(contratsTypesConf.baseURL, { 'ref' : id, 'action' : 'getDatas' }, function(jsonTxt) {
        var datas = JSON.parse(jsonTxt);

        modal.find("small.db_ref > span").html(datas.ref);
        
        modal.find("td.nom").html(datas.nom);
        modal.find("td.groupe").html(datas.groupe_nom);
        modal.find("td.frequence").html(datas.frequence_print);
        modal.find("td.panier_type").html(datas.panier_type_nom);
        modal.find("td.nb_paniers").html(datas.nb_paniers + " panier" + (datas.nb_paniers>1 ? "s" : ""));
        modal.find("td.prix_total").html(datas.prix_total + " €");
        
        modal.modal('show');
    }).fail(function() { alert("("+contratsTypesConf.type+" - load modal view)"); });
}

function modalViewContratsType_clear(modal) {
    modal.removeAttr("view_id");
    
    modal.find("small.db_ref > span").html("");
    
    modal.find("td.nom").html("");
    modal.find("td.groupe").html("");
    modal.find("td.frequence").html("");
    modal.find("td.panier_type").html("");
    modal.find("td.nb_paniers").html("");
    modal.find("td.prix_total").html("");
}

/***** MODAL FORM ADD/EDIT *****/
function modalFormContratsType_init(modal) {
    modal.find("form").on("submit", function(e) { e.preventDefault(); });
    
    // GROUPE
    modal.find("select[name=groupe]").change(function(e) { modalFormContratsType_refreshPaniersTypesSelectList(modal, $(this).val()); });
    
    // FREQUENCE
    modal.find("select[name=frequence]").change(function(e) { $(this).blur(); });
    
    // PANIERS TYPE
    modal.find("select[name=panier_type]").change(function(e) { 
        $(this).blur();
        $(this).attr("old", $(this).attr("valeur"))
               .attr("valeur", $(this).find("option:selected").attr("valeur"));
        modalFormContratsType_calcPrixTotal(modal, false);
    }).focus(function(e) {
        $(this).attr("old", $(this).attr("valeur"));
    });
    
    // NB PANIERS
    initIntInputWithLimits(modal.find("input[name=nb_paniers]"), 1, 99);
    modal.find("input[name=nb_paniers]").focus(function(e) {
        $(this).attr("old", $(this).val());
    }).change( function(e) { 
        modalFormContratsType_calcPrixTotal(modal, false);
    });
    
    // PRIX TOTAL
    initFloatInput(modal.find("input[name=prix_total]"));
    modal.find("button.btnCalcTotal").click(function(e) {
        e.preventDefault();
        $(this).blur();
        modalFormContratsType_calcPrixTotal(modal, true);
    })
}

function modalFormContratsType_loadDatas(modal,id) {
    $.post(contratsTypesConf.baseURL, { 'ref' : id, 'action' : 'getDatas' }, function(jsonTxt) {
        var datas = JSON.parse(jsonTxt);

        modal.find("input[name=nom]").val(datas.nom);
        modal.find("select[name=groupe]").val(datas.groupe_ref);
        modal.find("select[name=frequence]").val(datas.frequence);
        modal.find("select[name=panier_type]").val(datas.panier_type_ref)
                                              .attr("valeur", datas.panier_type_valeur)
                                              .attr("old", datas.panier_type_valeur);
        modal.find("input[name=nb_paniers]").val(datas.nb_paniers)
                                            .attr("old", datas.nb_paniers);
        modal.find("input[name=prix_total]").val(datas.prix_total);

        if(modal) modal.modal('show');
    }).fail(function() { alert("("+contratsTypesConf.type+" - load datas in modal form)"); });
}

function modalFormContratsType_refreshPaniersTypesSelectList(modal, groupe) {
    datas = {
        'action' : 'select_list',
        'groupe' : groupe
    };
    $.post("paniers.php", datas, function(result) {
        var oldVal = parseInt( modal.find("select[name=panier_type]").val() );
        modal.find("select[name=panier_type]").html(result);
        if(oldVal>0 && modal.find("select[name=panier_type] option[value="+oldVal+"]")) modal.find("select[name=panier_type]").val(oldVal);
    }).fail(function() { alert("ERREUR SERVEUR ! (form contrats type - refresh paniers types select list)"); });
}

function modalFormContratsType_calcPrixTotal(modal, force) {
    var panier_type = modal.find("select[name=panier_type]");
    var ipt_nb_paniers = modal.find("input[name=nb_paniers]");
    var ipt_total = modal.find("input[name=prix_total]");
    
    var old_valeur_panier = parseFloat( panier_type.attr("old") );
    if(!old_valeur_panier>0) old_valeur_panier = 0.0;
    var valeur_panier = parseFloat( panier_type.attr("valeur") );
    if(!valeur_panier>0) valeur_panier = 0.0;
    var old_nb_paniers = parseFloat( ipt_nb_paniers.attr("old") );
    if(!nb_paniers>0) nb_paniers = 0.0;
    var nb_paniers = parseFloat( ipt_nb_paniers.val() );
    if(!nb_paniers>0) nb_paniers = 0.0;
    var total = parseFloat( ipt_total.val() );
    if(!total>0) total = 0.0;
    
    if((
            (old_valeur_panier != valeur_panier || old_nb_paniers != nb_paniers) 
            && total == (old_valeur_panier * old_nb_paniers)
        ) || force) ipt_total.val(number_format(nb_paniers * valeur_panier, 2, ".", ""));
    
    panier_type.attr("old", panier_type.find("option:selected").attr("valeur"));
    ipt_nb_paniers.attr("old", ipt_nb_paniers.val());
}

function modalFormContratsType_clear(modal) {
    modal.removeAttr("edit_id");
    modal.find("div.modaLoader").removeClass("show");
    
    modal.find("input[name=nom]").val("");
    modal.find("select[name=groupe]").val(0);
    modal.find("select[name=frequence]").val(0);
    modal.find("select[name=panier_type]").val(0).attr("valeur", 0).attr("old", 0);
    modal.find("input[name=nb_paniers]").val(1).attr("old", 1);
    modal.find("input[name=prix_total]").val(0);
}

function modalFormContratsType_getDatas(modal) {
    var datas = {
        'nom' :                    modal.find("input[name=nom]").val(),
        'groupe' :       parseInt( modal.find("select[name=groupe]").val() ),
        'frequence' :              modal.find("select[name=frequence]").val(),
        'panier_type' :  parseInt( modal.find("select[name=panier_type]").val() ),
        'nb_paniers' :   parseInt( modal.find("input[name=nb_paniers]").val() ),
        'prix_total' : parseFloat( modal.find("input[name=prix_total]").val() )
    };
    return datas;
}

function modalFormContratsType_checkDatas(datas) { 
    if(    datas.nom=="" 
       || !datas.groupe>0 
       || !(datas.frequence=="hebdo" || datas.frequence=="quinz")
       || !datas.panier_type>0 
       || !datas.nb_paniers>1 ) { 
        alert("ERREUR : un nom et tous les crit!ères du type de contrat doivent être renseigné !");
        return false;
    }
    return true;
}

/***** ADD *****/
function initAddContratsType() {
    // INIT FORM
    modalFormContratsType_init(modalAddContratsType);

    // INIT ADD BTN
    modalForm_initBtnAdd(
        $(contratsTypesConf.add_btnSelector),         // BTN ADD
        modalAddContratsType,                         // MODAL
        modalFormContratsType_clear                   // CLEAR FORM FUNCTION
    );
    
    // INIT SAVE BTN
    modalForm_initBtnSaveAdd(
        modalAddContratsType.find(".btnSave"),        // BTN SAVE
        contratsTypesConf.type,                       // ADD TYPE
        modalAddContratsType,                         // MODAL
        modalFormContratsType_getDatas,               // GET FORM DATAS FUNCTION
        modalFormContratsType_checkDatas,             // CHECK FORM DATAS FUNCTION
        contratsTypesConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalAddContratsType.on('hidden.bs.modal', function (e) { modalFormContratsType_clear(modalAddContratsType); });
}

/***** EDIT *****/
function initEditContratsType() {
    // INIT FORM
    modalFormContratsType_init(modalEditContratsType);

    // INIT EDIT BTNs
    var initBtnFct = function() { modalForm_initBtnEdit(
        $(contratsTypesConf.edit_btnSelector),        // BTNs
        modalEditContratsType,                        // MODAL
        modalFormContratsType_clear,                  // CLEAR FUNCTION
        modalFormContratsType_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // INIT SAVE EDIT BTN
    modalForm_initBtnSaveEdit(
        modalEditContratsType.find(".btnSave"),       // BTN SAVE
        contratsTypesConf.type,                       // EDIT TYPE
        modalEditContratsType,                        // MODAL
        modalFormContratsType_getDatas,               // GET FORM DATAS FUNCTION
        modalFormContratsType_checkDatas,             // CHECK FORM DATAS FUNCTION
        contratsTypesConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalEditContratsType.on('hidden.bs.modal', function (e) { modalFormContratsType_clear(modalEditContratsType); });
}

/***** DELETE *****/
function initDeleteContratsType() {
    // INIT DELETE BTNs
    var initBtnFct = function() { modalForm_initBtnDelete(
        $(contratsTypesConf.delete_btnSelector),      // BTNs
        modalDeleteContratsType,                      // MODAL
        modalDeleteContratsType_clear,                // CLEAR MODAL FUNCTION
        modalDeleteContratsType_loadDatas             // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

    // INIT SAVE DELETE BTN
    modalForm_initBtnSaveDelete(
        modalDeleteContratsType.find(".btnSave"),     // BTN SAVE
        contratsTypesConf.type,                       // DELETE TYPE
        modalDeleteContratsType,                      // MODAL
        false,                                  // GET FORM DATAS FUNCTION
        false,                                  // CHECK FORM DATAS FUNCTION
        contratsTypesConf.baseURL                     // SAVE URL
    );

    // CANCEL
    modalDeleteContratsType.on('hidden.bs.modal', function (e) { modalDeleteContratsType_clear(); });
}

function modalDeleteContratsType_loadDatas(btn, id) {
    modalDeleteContratsType.find('b.name').html( btn.attr('nom') );
    modalDeleteContratsType.modal('show');
}

function modalDeleteContratsType_clear() {
    modalDeleteContratsType.removeAttr("delete_id");
    modalDeleteContratsType.find('b.name').html("");
}