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

var kostensoort_btw = 0;
var last_account_key = -1;

function init_budget()
{
    $("#account").prop("disabled", true);
    $("input#contingency").prop("disabled", true );
    $("#order").prop("disabled", true);

    $("#budgetdiscipline").change( change_discipline );
    $("#budgetproject").change( change_project );
    $("#budgetcostcategory").change( change_rubriek );
    $("#costtypegroup").change( change_groep );
    $("#costtype").change( change_soort );
    $("#amount").change( change_amount );
    $("#vat").change( change_vat );
    $("#account").change( change_account );
    $("input#contingency").change( change_contingency );

    // budgetdiscipline en budgetproject kunnen ook als gekozen filter worden meegegeven
    // en worden dan als readonly velden getoond.
    // LET OP: bij delayload = true wordt een select nooit default gevuld voordat het hier komt.
    var v_budgetdiscipline   = typeof budgetdiscipline_key   == "undefined" ? -1 : budgetdiscipline_key;
    var v_budgetproject      = typeof budgetproject_key      == "undefined" ? -1 : budgetproject_key;
    var v_budgetcostcategory = typeof budgetcostcategory_key == "undefined" ? -1 : budgetcostcategory_key;
    var v_costtypegroup      = typeof costtypegroup_key      == "undefined" ? -1 : costtypegroup_key;
    var v_costtype           = typeof costtype_key           == "undefined" ? -1 : costtype_key;

    // Overrules voor de multiedit modal
    if (typeof budgetrubriek_overrule    != "undefined" && budgetrubriek_overrule    != -1) v_budgetcostcategory  = budgetrubriek_overrule;
    if (typeof kostensoortgroep_overrule != "undefined" && kostensoortgroep_overrule != -1) v_costtypegroup       = kostensoortgroep_overrule;

    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_budgetcostcategory != -1)           { init_niveau = "R"; init_key = v_budgetcostcategory; }
    if (v_costtypegroup != -1)                { init_niveau = "G"; init_key = v_costtypegroup; }
    if (v_costtype != "" && v_costtype != -1) { init_niveau = "S"; init_key = v_costtype; }

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

    init_niveau = "KP";
    init_key = -1;
    if ($("#account").val() != -1)
    {
        init_key = $("#account").val();
    }

    if (!$("input#contingency").prop("checked"))
    {   // Geen kostenplaats bij een reservebudget selecteren!
        $.getJSON( "../bgt/get_bgt_info_ajax.asp",
                   { req_info: "initsearch",
                     niveau: init_niveau,
                     root_key: (v_budgetdiscipline ? v_budgetdiscipline : -1),
                     parent_key: (v_budgetproject ? v_budgetproject : -1),
                     child_key: (v_costtype ? v_costtype : -1),
                     init_key: init_key
                   },
                   re_init_plaats);
    }
}

function re_init_soort(data)
{
    fill_rubriekselector("D", -1            , data.parents.D);
    fill_rubriekselector("P", data.parents.D, data.parents.P);
    fill_rubriekselector("R", data.parents.P, data.parents.R);
    fill_rubriekselector("G", data.parents.R, data.parents.G);
    fill_rubriekselector("S", data.parents.G, data.parents.S);
}

function re_init_plaats(data)
{
    var init_key = ($("#account").val() != -1 ? $("#account").val() : data.parents.K || -1);
    var project_key = $("#budgetproject").val() || (data.parents ? data.parents.P || -1 : -1);
    var discipline_key = $("#budgetdiscipline").val() || (data.parents ? data.parents.D || -1 : -1);
    fill_plaatsselector("KP", discipline_key, project_key, init_key);
}

function change_discipline()
{
    var discipline_key = $("#budgetdiscipline").val();
    process_info({niveau:"R",lov:[]});
    process_info({niveau:"G",lov:[]});
    process_info({niveau:"S",lov:[]});
    multiselect_rubriekselector("P", discipline_key);
    fill_plaatsselector("KP", discipline_key, -1, -1);
    use_contingency(false);

    $("#order").empty().prop("disabled", true);
}
function change_project()
{
    var project_key = $("#budgetproject").val();
    process_info({niveau:"G",lov:[]});
    process_info({niveau:"S",lov:[]});
    multiselect_rubriekselector("R", project_key);
    use_contingency(false);

    $("#order").empty().prop("disabled", true);
}
function change_rubriek()
{
    var rubriek_key = $("#budgetcostcategory").val();
    process_info({niveau:"S",lov:[]});
    multiselect_rubriekselector("G", rubriek_key);
    use_contingency(true);

    $("#order").empty().prop("disabled", true);

    var btw_perc = 0;
    if ($("#budgetcostcategory").val() != -1 )
    {
        btw_perc = ( $("#budgetcostcategory option:selected").attr("perc_btw")
                   ? parseFloat($("#budgetcostcategory option:selected").attr("perc_btw").replace(/,/g,"."))
                   : 0
                   );
    }
    if ($("#amount").val() && btw_perc != kostensoort_btw)
    {
        FcltMgr.confirm(L("bgt_confirm_recalc_vat"), function() { change_amount(); } );
    }

}
function change_groep()
{
    var groep_key = $("#costtypegroup").val();
    var is_reserve = !(groep_key > 0); // Als het budget een kostensoortgroep heeft dan is het geen reserve.
    multiselect_rubriekselector("S", groep_key);
    use_contingency(is_reserve); // als groep weer leeg is gemaakt mag het budget wel weer reserve zijn/

    fill_opdrachtselector("OP", groep_key);
}
function change_soort()
{
    var bdiscipline_key = typeof budgetdiscipline_key == "undefined" ? -1 : budgetdiscipline_key;
    var bproject_key = typeof budgetproject_key == "undefined" ? -1 : budgetproject_key;
    var kplaats_key = -1;
    var btw_perc = 0;
    if ($("#costtype").val() != -1 )
    {
        kplaats_key = $("#costtype option:selected").attr("kpn_key");
        btw_perc = parseFloat($("#costtype option:selected").attr("perc_btw").replace(/,/g,"."));
    }

    fill_plaatsselector("KP", bdiscipline_key, bproject_key, kplaats_key);

    if ($("#amount").val() && btw_perc != kostensoort_btw)
    {
        FcltMgr.confirm(L("bgt_confirm_recalc_vat"), function() { change_amount(); } );
    }
    use_contingency(false);
}

function change_amount()
{
    // bereken btwbedrag (vat) adhv btw-percentage bij kostensoort.
    var btw_incl;
    var btw_perc;
    var amount = parseFloat($("#amount").val().replace(/,/g,"."));

    // voor model_bgt_budget
    if (btw_data && btw_data.btw_val)
    {
        btw_incl = btw_data.btw_inc;
        btw_perc = parseFloat(btw_data.btw_val);
    }
    else
    {
        if ($("#costtype").prop("disabled"))
        {
            btw_incl = $("#budgetcostcategory option:selected").attr("incl_btw") == "1";
            btw_perc = ( $("#budgetcostcategory option:selected").attr("perc_btw")
                       ? parseFloat($("#budgetcostcategory option:selected").attr("perc_btw").replace(/,/g,"."))
                       : null
                       );
        }
        else
        {
            btw_incl = $("#costtype option:selected").attr("incl_btw") == "1";
            btw_perc = ( $("#costtype option:selected").attr("perc_btw")
                       ? parseFloat($("#costtype option:selected").attr("perc_btw").replace(/,/g,"."))
                       : null
                       );
        }
    }

    kostensoort_btw = btw_perc; // Huidige btw-percentage globaal opslaan.
    if (isNaN(amount))
    {
        $("#vat").val("");
        $("#vat").closest("tr").next("tr").find("span").text("");
    }
    else
    {
        if (btw_perc && !isNaN(btw_perc))
        {
            var perc = (btw_perc / 100);
            var vat = amount * perc;
            var incl = amount + vat;

            $("#vat").val(num2currEditable(vat));
            $("#vat").closest("tr").next("tr").find("span").text(num2currEditable(incl));
        }
    }
}

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

function change_account()
{
    // Vul de prs_kostenplaatsgrp_key
    var costgrp_key = $("#account option:selected").attr("par_key");
    $("#costgroup").val(costgrp_key);

    var account_key = $("#account").val();
    if (account_key > 0)
        last_account_key = account_key;
}

function change_contingency()
{
    var is_reserve = $("input#contingency").prop('checked');
    $("#account").val( is_reserve ? -1 : last_account_key);
    $("#account").prop("disabled", is_reserve);
}

function fill_opdrachtselector(niveau, parent_key, init_key)
{
    $.getJSON( "../bgt/get_bgt_info_ajax.asp",
               { req_info: "order",
                 niveau: niveau,
                 parent_key: parent_key,
                 init_key: init_key
               },
               process_info);
}

function multiselect_rubriekselector(niveau, parent_key)
{
    if ((typeof parent_key == "object") && parent_key.length != 1)
    {
        process_info({niveau:niveau,lov:[]});
    }
    else
    {
        fill_rubriekselector(niveau, parent_key);
    }
}

function fill_rubriekselector(niveau, parent_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,
                 init_key: init_key,
                 sel_mode: sel_mode
               },
               process_info);
}

function fill_plaatsselector(niveau, root_key, parent_key, init_key)
{
    $("#account").prop("disabled", false);
    $.getJSON( "../bgt/get_bgt_info_ajax.asp",
               { req_info: "plaatssearch",
                 niveau: niveau,
                 root_key: root_key,
                 parent_key: parent_key,
                 init_key: (init_key && init_key != "null" ? init_key : -1)
               },
               process_info);
}

function use_contingency(contingency_mode)
{
    // is reservebudget, kan aangezet worden als alleen kostenrubriek is gekozen.
    if (contingency_mode)
    {
        $("input#contingency").prop("disabled", false );
    }
    else
    {
        $("input#contingency").prop('checked', false);
        $("input#contingency").prop("disabled", true );
    }
    change_contingency();
}

function process_info(data)
{
    var select;
    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"); 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);
                $new_lov.attr("kpn_key",  opt.atr.kpn_key);
            }
            else
            {
                $new_lov.attr("incl_btw", opt.atr.btw_inc);
                $new_lov.attr("perc_btw", opt.atr.btw_val);
                $new_lov.attr("kpn_key",  opt.atr.kpn_key);
            }
            select.append($new_lov);
        }
        select.prop("disabled", false);
        select.removeClass("btn_disabled");
    }
    else
    {
        select.prop("disabled", true);
        select.addClass("btn_disabled");
    }

    if (sel_key > -1)
    {
        select.val(sel_key);
        if (data.niveau == "KP")
            last_account_key = sel_key;
    }
    //$("input#contingency").prop("disabled", true );
}
