// SETTINGS
var legumesConf = {
    type                          : "legume",
    baseURL                       : "legumes.php",
    // LIST
    list_selector                 : "#legumesList",
    btn_list_print_selector       : "#btnPrintLegumesList",
    // SEARCH
    search_form_selector          : "#legumesSearch",
    search_selector               : "#legumesSearch .searchGrp",
    // 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
    initListProgressLoad($(legumesConf.list_selector), legumesConf.baseURL, legumesConf.type+" list");
    $(legumesConf.btn_list_print_selector).click(function(e) {
        e.preventDefault(); $(this).blur();
        window.open(legumesConf.baseURL+"?action=printList", '_blank');
    });
    
    // 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);
        
        // TARIFS
        if(Object.keys(datas.tarifs_list).length>0) {            
            modal.find("table.modal-body tbody tr.nullchild").addClass("hide");
            var tarifs_courant = {};
            $.each(datas.tarifs, function(n,e) { tarifs_courant[e.ref] = e });
            $.each(datas.tarifs_list, function(n,e) { modalViewLegume_addTarif(modal, e, datas.tarifs); });
        }
        
        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("table.modal-body tbody tr.nullchild").removeClass("hide");
    modal.find("table.modal-body tbody tr.tarif").remove();
}

function modalViewLegume_addTarif(modal, datas, tarifs_courant) {
    // ANALYSE DATAS
    var date            = parseDate(datas.date, 'yyyy-mm-dd');
    var grp_ref         = parseInt(datas.groupe_ref);
    var is_all          = !(parseInt(datas.groupe_ref)>0);
    var is_all_next     = true;
    var is_all_current  = true;
    var is_all_old      = true;
    var grps = [];
    var grps_by_id = {};
    modal.find("table.modal-body tbody th.titre.groupe").each(function(n,e) {
        var g = {
            ref         : parseInt($(this).attr('ref')),
            apply       : false,
            is_next     : false,
            is_current  : false,
            is_old      : false
        };
        g.apply = ((!grp_ref>0) || (grp_ref == g.ref));
        if(g.apply) {
            var current = tarifs_courant[ g.ref ];
            if(current.ref == datas.ref) { g.is_current = true; is_all_next = false; is_all_old = false; }
            else {
                is_all_current = false;
                currentDate = parseDate(current.date, 'yyyy-mm-dd');
                if(date>currentDate) { g.is_next = true; is_all_old = false; }
                else { g.is_old = true; is_all_next = false; }
            }
        }
        else { is_all_next = false; is_all_current = false; is_all_old = false; }
        grps_by_id[g.ref] = g;
        grps.push(g);
    });
    
    // BUILD
    var tr = $("<tr class='tarif'></tr>")
    .append( $("<td class='date'></td>").html(datas.date_print).attr("date", datas.date));
    
    // FIND OLD ROW AT SAME DATE
    var trOld = [];
    modal.find("table.modal-body tbody tr.tarif td.date").each(function(n,e) {
        if($(this).attr('date') == datas.date && trOld.length==0) trOld = $(this).parent();
    });
    replace_cell = false;
    
    // APPLY TO ALL GROUPES
    if(is_all && (is_all_next || is_all_current || is_all_old)) {
        // REPLACE CELL IF POSSIBLE
        if(trOld.length>0) {
            td = trOld.find('td.tarif.not_apply');
            if(td.length>0) {
                td.each(function(n,e) {
                    $(this).removeClass("not_apply").html(datas.print);
                    if(is_all_next) td.addClass('next');
                    else if(is_all_current) td.addClass('current');
                    else td.addClass('old');
                })
                replace_cell = true;
            }
        }
        // ADD NEW ROW
        if(!replace_cell) {
            td = $("<td class='tarif'></td>").attr("colspan", grps.length).html(datas.print);
            if(is_all_next) td.addClass('next');
            else if(is_all_current) td.addClass('current');
            else td.addClass('old');
            tr.append( td );
            modal.find("table.modal-body tbody").append(tr);
        }
    }
    // APPLY BY GROUP
    else {
        // REPLACE IF POSSIBLE
        if(trOld.length>0) {
            // REPLACE CELL BY CELL IF POSSIBLE
            if(grp_ref>0) {
                // REPLACE NOT_APPLY
                td = trOld.find('td.tarif.not_apply[grp='+grp_ref+']');
                if(td.length>0) {
                    td.removeClass('not_apply').html( datas.print );
                    g = grps_by_id[grp_ref];
                    if(g.is_next) td.addClass('next');
                    else if(g.is_current) td.addClass('current');
                    else td.addClass('old');
                    replace_cell = true;
                }
                // SPLIT ALL
                else {
                    td = trOld.find('td.tarif[colspan='+grps.length+']');
                    if(td.length>0) {
                        old = {
                            'print' : td.html(),
                            'class' : td.attr("class")
                        }
                        td.remove();
                        for(var i=0; i<grps.length; i++) {
                            g = grps[i];
                            td = $("<td class='tarif'>.</td>").attr('grp', g.ref);
                            if(g.ref == grp_ref) {
                                td.html( datas.print );
                                if(g.is_next) td.addClass('next');
                                else if(g.is_current) td.addClass('current');
                                else td.addClass('old');
                            }
                            else td.html( old.print ).attr('class', old.class);
                            trOld.append( td );
                        }
                        replace_cell = true;
                    }
                }
            }
            // APPLY TO NOT ALREADY APPLY IF POSSIBLE
            else {
                td = trOld.find('td.tarif.not_apply');
                if(td.length>0) {
                    td.each(function(n,e) {
                        $(this).removeClass('not_apply').html( datas.print );
                        g = grps_by_id[$(this).attr('grp')];
                        if(g.is_next) $(this).addClass('next');
                        else if(g.is_current) $(this).addClass('current');
                        else $(this).addClass('old');
                    });
                    replace_cell = true;
                }
            }
        }
        // ADD CELL BY GROUPE
        if(!replace_cell) {
            for(var i=0; i<grps.length; i++) {
                g = grps[i];
                td = $("<td class='tarif'>.</td>").attr('grp', g.ref);
                if(g.apply) {
                    td.html( datas.print );
                    if(g.is_next) td.addClass('next');
                    else if(g.is_current) td.addClass('current');
                    else td.addClass('old');
                }
                else td.addClass("not_apply");
                tr.append( td );
            }
            modal.find("table.modal-body tbody").append(tr);
        }
    }
}

/***** MODAL FORM ADD/EDIT *****/
function modalFormLegume_init(modal) {
    modal.find("form").preventFormValidation();
    
    // BTN ADD TARIF
    modal.find("button.btnAddTarif").click(function(e) {
        e.preventDefault();
        iptGrp = modalFormLegume_addTarif(modal, false);
        iptGrp.find("input[name=prix]").focus();
    });
    
    // 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);
        
        $.each(datas.tarifs_list, function(n,e) { 
            if(e.ref>0) modalFormLegume_addTarif(modal, e);
        });

        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");
    
    modal.find("input[name=nom]").val("");
    modal.find("div.tarifs div.tarif").remove();
}

function modalFormLegume_addTarif(modal, datas) {
    if(modal.find("div.tarifs div.tarif[ref="+datas.ref+"]").length>0) return;
    
    var iptGrp = $( modal.find("div.tarif_template").html() ).addClass("tarif").attr('ref', 'new');
    
    if(isDefined(datas) && typeof(datas)==="object") {
        iptGrp.attr('ref', datas.ref);
        iptGrp.find("select[name=groupe]").val(datas.groupe_ref).prop("disabled", datas.use);
        iptGrp.find("input[name=prix]").val(datas.prix).prop("disabled", datas.use);
        iptGrp.find("select[name=unite]").val(datas.unite).prop("disabled", datas.use);
        iptGrp.find("input[name=date]").val(datas.date).prop("disabled", datas.use);
        iptGrp.find("button.btnDel").prop("disabled", datas.use);
    }
    else iptGrp.find("input[name=date]").val(getTodayDate("yyyy-mm-dd")).attr('min', getTodayDate("yyyy-mm-dd"));
    
    modal.find("div.tarifs").append(iptGrp);
    
    // INIT
    initFloatInputWithLimits( iptGrp.find("input[name=prix]"), 0.0, 999.99 );
    initDateInput( iptGrp.find("input[name=date]") );
    
    iptGrp.find("button.btnDel").click(function(e) {
        e.preventDefault(); $(this).blur();
        if(parseInt(iptGrp.attr("ref"))>0) {
            if(iptGrp.hasClass("deleted")) {
                iptGrp.removeClass("deleted");
                $(this).removeClass("btn-info").addClass("btn-danger")
                       .find("i").removeClass("glyphicon-refresh").addClass("glyphicon-trash");
            }
            else {
                iptGrp.addClass("deleted");
                $(this).removeClass("btn-danger").addClass("btn-info")
                       .find("i").removeClass("glyphicon-trash").addClass("glyphicon-refresh");
            }
        }
        else iptGrp.remove();
    });
    
    return iptGrp;
}

function modalFormLegume_getDatas(modal) {
    var datas = {
        'nom'       : modal.find("input[name=nom]").val()
    };
    
    // TARIFS
    var tarifs = [];
    modal.find("div.tarifs div.input-group.tarif").each(function(n,e) {
        tarifs.push({
            'ref'       : $(this).attr('ref'),
            'groupe'    : parseInt( $(this).find("select[name=groupe]").val() ),
            'prix'      : parseFloat( $(this).find("input[name=prix]").val() ),
            'unite'     : $(this).find("select[name=unite]").val(),
            'date'      : $(this).find("input[name=date]").val(),
            'del'       : $(this).hasClass("deleted") ? 1 : 0
        });
    });
    datas.tarifs = JSON.stringify(tarifs);
    return datas;
}

function modalFormLegume_checkDatas(datas) {
    tarifs = JSON.parse(datas.tarifs);
    var nb_valid_tarifs = 0;
    $.each(tarifs, function(n,e) {
        if(e.prix>0 && parseDate(e.date, 'yyyy-mm-dd') && e.del==0) nb_valid_tarifs++;
    });
    
    if(datas.nom=="" || nb_valid_tarifs==0) {
        alert("ERREUR : au minimum, un nom et un tarif doivent ê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("");
}