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

var bedrijf_btw = 0;
var last_account_key = -1;

function init_opdracht()
{
    $("#account").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 );
    $("#company").change( change_bedrijf );
    $("#amount").change( change_amount );
    $("#vat").change( change_vat );
    $("#account").change( change_account );

    // 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;
    var v_opdr               = typeof mld_opdr_key           == "undefined" ? -1 : mld_opdr_key;
    var sel_mode             = typeof cur_mode               == "undefined" ? "list" : cur_mode;

    // Overrules voor de multiedit modal
    if (typeof budgetdiscipline_overrule != "undefined" && budgetdiscipline_overrule != -1) v_budgetdiscipline    = budgetdiscipline_overrule;
    if (typeof budgetproject_overrule    != "undefined" && budgetproject_overrule    != -1) v_budgetproject       = budgetproject_overrule;
    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 (v_opdr != -1)                         { init_niveau = "O"; init_key = v_opdr; }

    if (init_key > 0)
    {
        $.getJSON( "../bgt/get_bgt_info_ajax.asp",
                   { req_info: "initsearch",
                     niveau: init_niveau,
                     parent_key: -1,
                     init_key: init_key,
                     sel_mode: sel_mode
                   },
                   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();
    }
}

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);
    fill_rubriekselector("B", data.parents.D, data.parents.B, data.parents.S);
    fill_plaatsselector("KP", data.parents.D, data.parents.P, (data.sel_mode == "order_edit" ? data.parents.K : -1) );
}

function re_init_plaats(data)
{
    var init_key = ($("#account").val() != -1 ? $("#account").val() : data.parents.K || -1);
    var project_key = $("#budgetproject").val() || data.parents.P;
    var discipline_key = $("#budgetdiscipline").val() || data.parents.D;
    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:[]});
    process_info({niveau:"B",lov:[]});
    fill_rubriekselector("P", discipline_key);
    fill_plaatsselector("KP", discipline_key, -1, -1);

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

    $("#order").empty().prop("disabled", true);
}
function change_rubriek()
{
    var rubriek_key = $("#budgetcostcategory").val();
    process_info({niveau:"S",lov:[]});
    process_info({niveau:"B",lov:[]});
    fill_rubriekselector("G", rubriek_key);
    $("#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 != bedrijf_btw)
    {
        FcltMgr.confirm(L("bgt_confirm_recalc_vat"), function() { change_amount(); } );
    }

}
function change_groep()
{
    var groep_key = $("#costtypegroup").val();
    process_info({niveau:"B",lov:[]});
    fill_rubriekselector("S", groep_key);

    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 )
    {
        ksoort_key = $("#costtype option:selected").val();
        kplaats_key = $("#costtype option:selected").attr("kpn_key");
        var v_attr = $("#costtype option:selected").attr("perc_btw");
        if (typeof v_attr !== typeof undefined && v_attr !== false)
        {
            btw_perc = parseFloat($("#costtype option:selected").attr("perc_btw").replace(/,/g,"."));
        }
    }
    fill_rubriekselector("B", bdiscipline_key, -1, ksoort_key);

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

    if ($("#amount").val() && btw_perc != bedrijf_btw)
    {
        FcltMgr.confirm(L("bgt_confirm_recalc_vat"), function() { change_amount(); } );
    }
}
function change_bedrijf()
{
    // Vraag of de btw gewijzigd moet worden als het btw-percentage veranderd door het wijzigen van bedrijf.
    var amount = parseFloat($("#amount").val().replace(/,/g,"."));
    if (!isNaN(amount))
    {
        var btw_perc;
        if (btw_data && btw_data.btw_val)
        {
            btw_perc = parseFloat(btw_data.btw_val);
        }
        else
        {
            btw_perc = ( $("#company option:selected").attr("perc_btw")
                       ? parseFloat($("#company option:selected").attr("perc_btw").replace(/,/g,"."))
                       : null
                       );
        }

        if (btw_perc != bedrijf_btw)
        {
            FcltMgr.confirm(L("bgt_confirm_recalc_vat"), {}, function() { change_amount(); } );
        }
    }
}

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

    if ($("#costtype").is("select"))
    {
        btw_perc = ( $("#costtype option:selected").attr("perc_btw")
                   ? parseFloat($("#costtype option:selected").attr("perc_btw").replace(/,/g,"."))
                   : null
                   );
    }
    else
    {
        btw_perc = parseFloat(btw_data.btw_val);
    }

    if ($("#company").is("select"))
    {
        btw_perc = ( $("#company option:selected").attr("perc_btw")
                   ? parseFloat($("#company option:selected").attr("perc_btw").replace(/,/g,"."))
                   : null
                   );
    }
    else
    {
        // Er is op bedrijf gefilterd.
        // btw_off=[0|1] : 1 = bedrijf is vrijgesteld van btw (verlegd)
        btw_perc = (btw_data.btw_off == 1 ? 0 : btw_perc); // Als vrijgesteld dan 0, anders percentage van kostensoort.
    }

    bedrijf_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 || btw_perc == 0) && !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 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 fill_rubriekselector(niveau, parent_key, init_key, child_key)
{
    var sel_mode = (typeof cur_mode == "undefined" ? "list" : cur_mode);
    var do_exec = true;

    if (niveau == "B")
    {
        init_key = (!init_key ? -1 : init_key);
        if ($("#company").length)
        {
            if (sel_mode == "order_edit" || sel_mode == "order_new" )
            {
                // bedrijf (nog) is niet afhankelijk van discipline en/of project
                parent_key = -1;
                child_key = child_key;
            }
        }
        else
            do_exec = false;
    }

    if (do_exec)
    {
        var data = { req_info: "projectsearch"
                   , niveau: niveau
                   , parent_key: parent_key
                   , init_key: init_key
                   , sel_mode: sel_mode
                   };
        if (child_key)
            data.child_key = child_key;

        $.getJSON( "../bgt/get_bgt_info_ajax.asp",
                   data,
                   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 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 "B":  select = $("#company"); 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;
    }
}
