// SETTINGS
var legumesConf = {
    type                          : "legume",
    baseURL                       : "legumes.php",
    // LIST
    list_selector                 : "#legumesList",
    // SEARCH
    search_selector               : "#legumesSearch .searchGrp",
    filtres_selector              : "#legumesSearch select",
    // VIEW
    view_modalSelector            : "#modalViewLegume",
    view_btnSelector              : ".btnViewLegume",
    // ADD
    add_modalSelector             : "#modalAddLegume",
    add_btnSelector               : "#btnAddLegume",
    // EDIT
    edit_modalSelector            : "#modalEditLegume",
    edit_btnSelector              : ".btnEditLegume",
    // DELETE
    delete_modalSelector          : "#modalDeleteLegume",
    delete_btnSelector            : ".btnDeleteLegume",
}

// MODALS
var modalViewLegume    = false;
var modalAddLegume     = false;
var modalEditLegume    = false;
var modalDeleteLegume  = false;

$(document).ready( function() {
    // LIST LOADER
    initListProgressLoad($(legumesConf.list_selector), legumesConf.baseURL, legumesConf.type+" list");
    
    // SEARCH
    $(legumesConf.search_selector).initSearchGroup();
    
    // VIEW
    modalViewLegume = $(legumesConf.view_modalSelector);
    if(modalViewLegume.length>0) {
        initViewLegume();
        // VIEW REQUEST
        var id = getUrlParameter("ref");
        if(id!==false && parseInt(id)>0 && current_page == "legumes") {
            modalViewLegume_clear(modalViewLegume);
            modalViewLegume_loadDatas(modalViewLegume, id);
        }
    }
    
    // ADD
    modalAddLegume = $(legumesConf.add_modalSelector);
    if(modalAddLegume.length>0) initAddLegume();

    // EDIT
    modalEditLegume = $(legumesConf.edit_modalSelector);
    if(modalEditLegume.length>0) initEditLegume();

    // DELETE
    modalDeleteLegume = $(legumesConf.delete_modalSelector);
    if(modalDeleteLegume.length>0) initDeleteLegume();
});

/***** MODAL VIEW *****/
function initViewLegume() {
    // INIT VIEW BTNs
    var initBtnFct = function() { modalForm_initBtnView(
        $(legumesConf.view_btnSelector),        // BTNs
        modalViewLegume,                        // MODAL
        modalViewLegume_clear,                  // CLEAR FUNCTION
        modalViewLegume_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

    // CANCEL
    modalViewLegume.on('hidden.bs.modal', function() { modalViewLegume_clear(modalViewLegume); });
}

function modalViewLegume_loadDatas(modal, id) {
    $.post(legumesConf.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.tarif").html(datas.tarif_print+" <small>(depuis le "+datas.tarif_date_print+")</small>");
        
        if(datas.historique_tarif.length>0) {            
            modal.find("table.modal-body tfoot").removeClass("hide");
            $.each(datas.historique_tarif, function(n,e) { addTarifLegumeHist(e); });
        }
        
        modal.modal('show');
    }).fail(function() { alert("("+legumesConf.type+" - load modal view)"); });
}

function modalViewLegume_clear(modal) {
    modal.find("small.db_ref > span").html("");
    
    modal.find("td.nom").html("");
    modal.find("td.tarif").html("");
    
    modal.find("table.modal-body tfoot").addClass("hide").find("tr:not(.header)").remove();
}

function modalViewLegume_addTarifLegumeHist(modal, datas) {
    var tr = $("<tr></tr>").attr("ref", datas.ref);
    tr.append($("<td></td>").html(datas.tarif_print));
    tr.append($("<td></td>").html(datas.tarif_periode));
    btnDel = $('<button class="btn btn-xs btn-link glyphicon glyphicon-trash btnDeleteTarifLegume"></button>').attr('ref', datas.ref).attr('tarif', datas.tarif_print).attr('periode', datas.tarif_periode);
    tr.append($("<td class='td_btn_action td_btn_delete'></td>").append(btnDel));
    modal.find("table.modal-body tfoot").append(tr);
    
    btnDel.click(function(e) {
        e.preventDefault(); $(this).blur();
        tr = $(this).parent().parent();
        id = parseInt( $(this).attr("ref") );
        if(!id>0) return;
        msg = "Êtes vous sûr de vouloir supprimer le tarif de "+$(this).attr("tarif")+" en application "+$(this).attr("periode")+" ?";
        if(confirm(msg)) {
            datas = { 'action' : 'deleteTarif', 'tarif' : id };
            $.post( legumesConf.baseURL, datas, function( result ) {
                if(parseInt(result)>0) { 
                    tr.remove();
                    if(modal.find("table.modal-body tfoot tr:not(.header)").length == 0) modal.find("table.modal-body tfoot").addClass("hide");
                }
                else { console.error(result); alert(result); }
            }).fail(function() { alert("("+legumesConf.type+" - delete tarif)"); });
        }
    })
}

/***** MODAL FORM ADD/EDIT *****/
function modalFormLegume_init(modal) {
    modal.find("form").on("submit", function(e) { e.preventDefault(); });
    
    // BTN EDIT TARIF
    modal.find("button.btnEditTarif").click(function(e) {
        e.preventDefault();
        $(this).blur().addClass('hide');
        modal.find("input[name=prix]").attr('ref', 'new').prop('disabled', false);
        modal.find("select[name=unite]").prop('disabled', false);
        modal.find("input[name=date]").prop('disabled', false).val(getTodayDate("yyyy-mm-dd"));
    });
    
    // PRIX
    initFloatInput(modal.find("input[name=prix]"));
}

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

        modal.find("input[name=nom]").val(datas.nom);
        modal.find("input[name=prix]").val(datas.tarif_prix).attr('ref', datas.tarif_ref);
        modal.find("select[name=unite]").val(datas.tarif_unite);
        modal.find("input[name=date]").val(datas.tarif_date);

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

function modalFormLegume_clear(modal) {
    modal.removeAttr("edit_id");
    modal.find("div.modaLoader").removeClass("show");

    add = modal.hasClass("add");
    
    modal.find("input[name=nom]").val("");
    if(add) modal.find("button.btnEditTarif").addClass('hide');
    else modal.find("button.btnEditTarif").removeClass('hide');
    modal.find("input[name=prix]").val("").attr('ref', "new").prop('disabled', !add);
    modal.find("select[name=unite]").val("kg").prop('disabled', !add);
    modal.find("input[name=date]").val(getTodayDate("yyyy-mm-dd")).prop('disabled', !add);
}

function modalFormLegume_getDatas(modal) {
    var datas = {
        'nom' : modal.find("input[name=nom]").val(),
        'tarif_ref' :       (modal.find("input[name=prix]").attr('ref')=="new") ? "new" : parseInt(modal.find("input[name=prix]").attr('ref')),
        'tarif_prix' :      parseFloat( modal.find("input[name=prix]").val() ),
        'tarif_unite' :     modal.find("select[name=unite]").val(),
        'tarif_date' :      modal.find("input[name=date]").val()
    };
    return datas;
}

function modalFormLegume_checkDatas(datas) { 
    if(datas.nom=="") { 
        alert("ERREUR : au minimum, un nom doit être renseigné !");
        return false;
    }
    return true;
}

/***** ADD *****/
function initAddLegume() {
    // INIT FORM
    modalFormLegume_init(modalAddLegume);

    // INIT ADD BTN
    modalForm_initBtnAdd(
        $(legumesConf.add_btnSelector),         // BTN ADD
        modalAddLegume,                         // MODAL
        modalFormLegume_clear                   // CLEAR FORM FUNCTION
    );
    
    // INIT SAVE BTN
    modalForm_initBtnSaveAdd(
        modalAddLegume.find(".btnSave"),        // BTN SAVE
        legumesConf.type,                       // ADD TYPE
        modalAddLegume,                         // MODAL
        modalFormLegume_getDatas,               // GET FORM DATAS FUNCTION
        modalFormLegume_checkDatas,             // CHECK FORM DATAS FUNCTION
        legumesConf.baseURL                     // SAVE URL
    );

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

/***** EDIT *****/
function initEditLegume() {
    // INIT FORM
    modalFormLegume_init(modalEditLegume);

    // INIT EDIT BTNs
    var initBtnFct = function() { modalForm_initBtnEdit(
        $(legumesConf.edit_btnSelector),        // BTNs
        modalEditLegume,                        // MODAL
        modalFormLegume_clear,                  // CLEAR FUNCTION
        modalFormLegume_loadDatas               // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();
    
    // INIT SAVE EDIT BTN
    modalForm_initBtnSaveEdit(
        modalEditLegume.find(".btnSave"),       // BTN SAVE
        legumesConf.type,                       // EDIT TYPE
        modalEditLegume,                        // MODAL
        modalFormLegume_getDatas,               // GET FORM DATAS FUNCTION
        modalFormLegume_checkDatas,             // CHECK FORM DATAS FUNCTION
        legumesConf.baseURL                     // SAVE URL
    );

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

/***** DELETE *****/
function initDeleteLegume() {
    // INIT DELETE BTNs
    var initBtnFct = function() { modalForm_initBtnDelete(
        $(legumesConf.delete_btnSelector),      // BTNs
        modalDeleteLegume,                      // MODAL
        modalDeleteLegume_clear,                // CLEAR MODAL FUNCTION
        modalDeleteLegume_loadDatas             // LOAD DATAS FUNCTION
    )};
    registerListProgressLoadCbkFct( $("tbody.progressLoadList"), initBtnFct );
    initBtnFct();

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

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

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

function modalDeleteLegume_clear() {
    modalDeleteLegume.removeAttr("delete_id");
    modalDeleteLegume.find('b.name').html("");
}