$(function ()
{
  setTimeout("init_factuur()", 100);
});

var kostensoort_btw = ((typeof btw_data != "undefined") && btw_data.btw_val ? btw_data.btw_val : 0);
var v_isclone       = (typeof is_clone == "undefined" ? 0 : is_clone);

function init_factuur()
{
    $("#budgetdiscipline").change( change_discipline );
    $("#budgetproject").change( change_project );
    $("#company").change( change_bedrijf );
    $("#order").change( change_opdracht );
    $("#total").change( change_totaal );
    $("#totalvat").change( change_btw );
    $("#_staticinvoice").change( change_vastnummer );

    // budgetdiscipline en budgetproject kunnen ook als gekozen filter worden meegegeven
    // en worden dan als readonly velden getoond.
    if (typeof mldopdracht_key == "undefined")
    {   // rechtstreeks vanuit fin_factuur
        if (v_isclone == 1)
        {
            var v_budgetdiscipline = budgetdiscipline_key;
            var v_budgetproject = initproject_key;
            var v_costtype = -1;
            var v_company = (typeof $("#company").val() == "undefined" ? (typeof company_key == "undefined" ? -1 : company_key) : $("#company").val() );
            var v_order = -1;
        }
        else
        {
            var v_budgetdiscipline = (typeof $("#budgetdiscipline").val() == "undefined" ? -1 : $("#budgetdiscipline").val() );
            var v_budgetproject    = (typeof $("#budgetproject").val()    == "undefined" ? -1 : $("#budgetproject").val() );
            var v_company          = (typeof $("#company").val()          == "undefined" ? (typeof company_key == "undefined" ? -1 : company_key) : $("#company").val() );
            var v_order            = (typeof $("#order").val()            == "undefined" ? -1 : $("#order").val() );

            v_order = ( (v_order == null && typeof(order_key) == "number") ? order_key : v_order );
            var v_costtype = (typeof(costtype_key) == "number" ? costtype_key : -1);
        }
    }
    else
    {   // fin_factuur vanuit mld_opdr
        var v_budgetdiscipline = budgetdiscipline_key;
        var v_budgetproject    = budgetproject_key;
        var v_costtype         = costtype_key;
        var v_company          = company_key;
        var v_order            = mldopdracht_key;
    }

    var init_niveau = "";
    var init_key = -1;
    if (v_budgetdiscipline != -1) { init_niveau = "D"; init_key = v_budgetdiscipline; }
    if (v_budgetproject != -1)    { init_niveau = "P"; init_key = v_budgetproject; }
    if (v_costtype != -1)         { init_niveau = "S"; init_key = v_costtype; }
    if (v_company != -1)          { init_niveau = "B"; init_key = v_company; }
    if (v_order != -1)            { init_niveau = "O"; init_key = v_order; }

    if (init_key > 0)
    {
        $.getJSON( "../bgt/get_bgt_info_ajax.asp",
                   { req_info: "initsearch",
                     niveau: init_niveau,
                     parent_key: (init_niveau == "B" ? v_budgetproject : -1),
                     init_key: init_key
                   },
                   re_init_soort);
    }
    else
    {
        var data = { niveau: "D",
                     parents: { D: -1,
                                P: -1,
                                R: -1,
                                G: -1,
                                S: -1,
                                B: -1,
                                O: -1
                              }
                   };
        re_init_soort(data);
    }
}

function re_init_soort(data)
{
    $.ajaxSetup({async: false});
    fill_rubriekselector("D", -1            ,             -1, data.parents.D);
    fill_rubriekselector("P", data.parents.D,             -1, data.parents.P);
    fill_rubriekselector("S", data.parents.G, data.parents.S, data.parents.S);
    fill_rubriekselector("B", data.parents.D, data.parents.P, data.parents.B);
    fill_rubriekselector("O", data.parents.P, data.parents.B, data.parents.O);

    // Alle fill_rubriekselectors moeten (synchroon) uitgevoerd zijn.
    if (data.parents.D==-1 && data.parents.P==-1 && data.parents.B==-1)
    {
        $("#budgetproject").prop("disabled", true).addClass("btn_disabled");
        $("#company").prop("disabled", true).addClass("btn_disabled");
        $("#order").prop("disabled", true).addClass("btn_disabled");
    }
    $.ajaxSetup({async: true});
}

function change_discipline()
{
    var discipline_key = $("#budgetdiscipline").val();
    process_info({niveau:"B",lov:[]});
    process_info({niveau:"O",lov:[]});
    fill_rubriekselector("P", discipline_key);
    fill_rubriekselector("B", discipline_key, -1);
}

function change_project()
{
    var discipline_key = (typeof $("#budgetdiscipline").val() == "undefined" ? -1 : $("#budgetdiscipline").val() );
    var project_key = $("#budgetproject").val();
    process_info({niveau:"O",lov:[]});
    fill_rubriekselector("B", discipline_key, project_key);
}

function change_bedrijf()
{
    var project_key = (typeof $("#budgetproject").val() == "undefined" ? (typeof budgetproject_key == "undefined" ? -1 : budgetproject_key) : $("#budgetproject").val() );
    var bedrijf_key = (typeof $("#company").val()       == "undefined" ? (typeof company_key       == "undefined" ? -1 : company_key)       : $("#company").val() );
    fill_rubriekselector("O", project_key, bedrijf_key);
    fill_rubriekselector("S", -1, -1, -1);
}

function change_opdracht()
{
    // Als opdracht bekend is kan het bedrag ingevuld worden:
    // we weten dan de btw-percentage dat gebruikt moet worden,
    // en sla de key voor kostensoort bij deze opdracht op.
    var kostengroep_key = $("#order option:selected").attr("grp_key");
    var kostensoort_key = $("#order option:selected").attr("cost_key");
    if (kostensoort_key)
    {
        fill_rubriekselector("S", kostengroep_key, kostensoort_key, kostensoort_key);
        // Er is eerst eerst een opdracht gekozen. Vul de bijbehorende bedrijf in.
        var v_bedr_key = $("#order option:selected").attr("bedr_key");
        if (v_bedr_key)
            $("#company").val(v_bedr_key);
    }
    var btw_perc = parseFloat($("#order option:selected").attr("perc_btw").replace(/,/g,"."));
    if ($("#total").val() && btw_perc != kostensoort_btw)
    {
        FcltMgr.confirm(L("bgt_confirm_recalc_vat"), function() { change_totaal(); } );
    }
}

function change_totaal()
{
    // bereken btwbedrag (vat) adhv btw-percentage bij kostensoort.
    if ($("#order").length)
        var btw_perc = parseFloat($("#order option:selected").attr("perc_btw").replace(/,/g,"."));
    else
        var btw_perc = btw_data.btw_val;
    var amount = parseFloat($("#total").val().replace(/,/g,"."));

    kostensoort_btw = btw_perc;
    if ((btw_perc || btw_perc == 0) && !isNaN(btw_perc) )
    {
        if ($("#order option:selected").attr("verl_btw") == 1) // Als verl_btw==1 dan geen btw berekenen.
            btw_perc = 0;
        var perc = (btw_perc / 100);
        var vat = "";
        var incl = "";
        if (!isNaN(amount))
        {
            vat = amount * perc;
            incl = amount + vat;
        }
        if ($("#order").length)
        {
            $("#totalvat").val(num2currEditable(vat));
            $("#totalvat").closest("tr").next("tr").find("span").text(num2currEditable(incl));
        }
    }
}

function change_btw()
{
    // bereken totaalbedrag bij wijziging van het btw-bedrag.
    var amount = parseFloat($("#total").val().replace(/,/g,"."));
    var vat = parseFloat($("#totalvat").val().replace(/,/g,"."));
    var incl = amount + vat;
    $("#totalvat").closest("tr").next("tr").find("span").text(num2currEditable(incl));
}

function change_vastnummer()
{
    var vastnummer = $("#_staticinvoice option:selected").text();
    $("#invoice").val(vastnummer);
}

function fill_rubriekselector(niveau, parent_key, child_key, init_key)
{
    var sel_mode = (typeof cur_mode == "undefined" ? "list" : cur_mode);
    $.getJSON( "../bgt/get_bgt_info_ajax.asp",
               { req_info: "projectsearch",
                 niveau: niveau,
                 parent_key: parent_key,
                 child_key: child_key,
                 init_key: init_key,
                 sel_mode: sel_mode
               },
               process_info);
}

function process_info(data)
{
    var select;
    var readonly = false;
    switch(data.niveau)
    {
        case "D":  select = $("#budgetdiscipline"); break;
        case "P":  select = $("#budgetproject"); break;
        case "R":  select = $("#budgetcostcategory"); break;
        case "G":  select = $("#costtypegroup"); break;
        case "S":  select = $("#costtype"); readonly = true; break;
        case "B":  select = $("#company"); break;
        case "O":  select = $("#order"); break;
        case "KP": select = $("#account"); break;
        case "OP": select = $("#order"); break;
    }

    var sel_key = -1;
    $new_lov = $("<option>").val(-1).html("");
    select.empty().append($new_lov);
    if (data.lov.length > 0)
    {
        for (i=0; i < data.lov.length;i++)
        {
            var opt = data.lov[i];
            $new_lov = $("<option>").val(opt.key).html(opt.oms);
            if (opt.sel)
            {
                $new_lov.attr("selected", "selected");
                sel_key = opt.key;
            }

            if (data.niveau == "KP")
            {
                $new_lov.attr("par_key",  opt.atr.par_key);
            }
            else
            {
                $new_lov.attr("incl_btw", opt.atr.btw_inc);
                $new_lov.attr("perc_btw", opt.atr.btw_val);
                $new_lov.attr("verl_btw", opt.atr.btw_off);
                $new_lov.attr("grp_key",  opt.atr.grp_key);
                $new_lov.attr("cost_key", opt.atr.srt_key);
                $new_lov.attr("bedr_key", opt.atr.bdr_key);
            }
            select.append($new_lov);
        }
        select.prop("disabled", readonly);
        select.removeClass("btn_disabled");
    }
    else
    {
        select.prop("disabled", true);
        select.addClass("btn_disabled");
    }

    if (sel_key > -1)
        select.val(sel_key);

    $("input#contingency").prop("disabled", true );
    if (data.niveau == "S")
    {   // De kostensoort alleen tonen.
        select.prev().remove();
        select.parent().removeClass("multitoggle");
    }
}
