<%@ language="javascript"%>
<% /*
     $Revision$
     $Id$

     File:           fac_edit_menu.asp
     Description:
     Parameters:     menu_key

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="fac.inc" -->
<!-- #include file="../Shared/FlexFiles.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/autorisatieselector.inc" -->
<%
FCLTHeader.Requires({plugins:["jQuery"]})

var autfunction = "WEB_PRSSYS";
var authparams = user.checkAutorisation(autfunction);

var copy = getQParamInt("copy", 0) == 1;

var menu_key = getQParamInt("menu_key", -1);
var menuitem_key = getQParamInt("menuitem_key", -1);
var mobilemenu = S("mobile_enabled") && getQParamInt("mobile", 0) == 1;

if (menu_key > -1)
{
    var sql = "SELECT m.fac_menu_altlabel menu_label, "
            + "       mi.fac_menuitems_key,"
            + "       mi.fac_menuitems_label menuitems_label,"
            + "       mi.fac_menuitems_module,"
            + "       COALESCE(m.fac_menu_altgroep, mi.fac_menuitems_groep) groep,"
            + "       m.fac_menu_level,"
            + "       m.fac_menu_volgnr,"
            + "       COALESCE(m.fac_menu_alturl, mi.fac_menuitems_url) url,"
            + "       mi.fac_menuitems_srtdisc,"
            + "       mi.fac_menuitems_disc,"
            + "       mi.fac_menuitems_rw,"
            + "       m.fac_functie_key                         extFkey,"
            + "       f2.fac_functie_module                     extFmod,"
            + "       m.ins_srtdiscipline_key,"
            + "       m.ins_discipline_key,"
            + "       mi.fac_functie_key,"
            + "       f1.fac_functie_code,"
            + "       f1.fac_functie_module,"
            + "       lcl.l (f1.fac_functie_omschrijving, 1)     fac_functie_omschrijving,"
            + "       COALESCE(m.fac_menu_info, mi.fac_menuitems_oms) uitleg,"
            + "       m.fac_menu_message,"
            + "       m.fac_menu_portal,"
            + "       COALESCE(m.fac_menu_image, mi.fac_menuitems_image) image"
            + "  FROM fac_menu m, fac_menuitems mi, fac_functie f1, fac_functie f2"
            + " WHERE     m.fac_menuitems_key = mi.fac_menuitems_key(+)"
            + "       AND mi.fac_functie_key = f1.fac_functie_key(+)"
            + "       AND m.fac_functie_key = f2.fac_functie_key(+)"
            + "       AND m.fac_menu_key = " + menu_key;
    var oRs = Oracle.Execute(sql);

    var module = oRs("fac_menuitems_module").Value;
    var groep = oRs("groep").Value;
    mobilemenu |= S("mobile_enabled") && groep == 3;
    var niveau = oRs("fac_menu_level").Value;
    var volgnr = oRs("fac_menu_volgnr").Value;
    var url = oRs("url").Value;
    var urlType = "path";
    if ((url || "").match(/[\?\\\/:]/g) === null) { // Het is een url als het 1 van de volgende tekens bevat; Forward slash (/), backslash (\) of een colon (:)
        urlType = "file";
    }

    menuitem_key = oRs("fac_menuitems_key").Value || menuitem_key;

    // Systeem autorisatieFunctie
    var sysFkey = oRs("fac_functie_key").Value || -1;
    var sysFsrtdisc = oRs("fac_menuitems_srtdisc").Value;
    var sysFdisc = oRs("fac_menuitems_disc").Value;
    var sysFrw = oRs("fac_menuitems_rw").Value;
    var sysFunc = sysFkey > -1 ? oRs("fac_functie_omschrijving").value + " (" + oRs("fac_functie_code").value + ")" : "";
    var sysFmod = oRs("fac_functie_module").Value;

    if (oRs("menu_label").Value)
    {
        var label_db = oRs("menu_label").Value;
        var label = L(label_db, { autolcl: true });
    }
    else
    {
        var label_db = oRs("menuitems_label").Value;
        var label = L(label_db, { autolcl: true });
        if (sysFsrtdisc == 1)
            label += " (+ " + L("lcl_vakgroup_type") + ")";
        if (sysFdisc == 1)
            label += " (+ " + L("lcl_discipline") + ")";
    }

    // Extra autorisatieFunctie
    var extFkey = oRs("extFkey").value || -1;
    var extFsrtdisc_key = oRs("ins_srtdiscipline_key").value || -1;
    var extFdisc_key = oRs("ins_discipline_key").value || -1;
    var extFmod = oRs("extFmod").value;

    var uitleg = oRs("uitleg").Value;
    var alert = oRs("fac_menu_message").Value;
    var portal = oRs("fac_menu_portal").Value;
    var image = oRs("image").Value;
    oRs.Close();
}

%>
<html>
  <head>
<%  FCLTHeader.Generate(); %>
    <script type="text/javascript" >

        function checkInput () {
            // Laten we er maar even vanuit gaan dat als ze beiden ingevuld zijn, het bestand mag prevaleren
            if ($("[type=hidden][id=url]").val()) {
                $("[id=url]:visible").val(""); // Dan maken we de url-tekst leeg
            }
            var hasUrl = false;
            $("[id=url]").each((i, elem) => { // Loop door alle velden met id=url
                var hasVal = !!$(elem).val();
                hasUrl |= hasVal;
            });
            var niveau = $("#level").val(); // Alleen bij niveau 2 (submenu) is de url verplicht
            if (niveau == 2 && !hasUrl) {
                FcltMgr.alert(L("lcl_menu_url_or_file_required"));
                return false;
            }
            // Waardes zijn geldig; stuur het juiste veld op om op te slaan (en disable de andere)
            $("[id=url]").each((i, elem) => {
                var hasVal = !!$(elem).val();
                $(elem).attr("disabled", !hasVal);
            });
            return true;
        }

        async function doSubmit()
        {
            // Standaard checks op verplichte velden, datum formaat, numeriek en float formaat, currency formaat.
            if (!await validateForm("u2"))
                return false;

            if (!checkInput())
                return false;

            document.forms.u2.submit();
        }

        function doCancel()
        {
            FcltMgr.closeDetail(window, { cancel: true } );
        }

        function onchangeAltfunctie()
        {
            var altfunc = $("#altfunctie_show");
            var module = altfunc.attr("module");
            var cnt_srtdisc = altfunc.attr("cnt_srtdisc") == "" ? 0 : altfunc.attr("cnt_srtdisc");
            var has_srtdisc = (cnt_srtdisc > 0 ? 1 : 0);

            $("#srtdisckey")[0].disabled = !(has_srtdisc == 1);
            $("#srtdisckey").val(-1);
            $("#disckey")[0].disabled = (has_srtdisc == 1);
            $("#disckey").val(-1);

            $.getJSON( "../fac/get_fac_info_ajax.asp",
                {   req_info: "menu",
                    module: module,
                    soort: has_srtdisc,
                    parent_key: -1,
                    init_key: -1
                },
                process_info);
        }

        function onchangeSrtdisc()
        {
            var altfunc = $("#altfunctie_show");
            var module = altfunc.attr("module");
            var srtdisc = $("#srtdisckey").val();
            $("#disckey").val(-1);
            fill_url("srtdisc");
            $.getJSON( "../fac/get_fac_info_ajax.asp",
                {   req_info: "menu",
                    module: module,
                    soort: 0,
                    parent_key: srtdisc,
                    init_key: -1
                },
                process_info);
        }

        function fill_url(org)
        {
            if (org == "srtdisc") { $("#disckey").val(-1); }
            if (org == "disc")    { $("#srtdisckey").val(-1); }

            var altfunc = $("#altfunctie_show");
            var module = altfunc.attr("fac_functie_code").substr(4,3);
            if ((altfunc.attr("disc") != 0 && $("#disckey").val() > 0) ||
                (altfunc.attr("srtdisc") != 0 && $("#srtdisckey").val() > 0))
            {
                var urole = "";
                switch (altfunc.attr("fac_functie_code"))
                {
                    case "WEB_BESUSE":
                    case "WEB_MLDUSE":
                    case "WEB_RESUSE":
                        urole = "fe";
                        break;
                    case "WEB_BESFOF":
                    case "WEB_MLDFOF":
                    case "WEB_RESFOF":
                        urole = "fo";
                        break;
                }

                var module = altfunc.attr("module");
                if ($("#disckey").val() > 0 && module == "BES")
                    $("#url").val("appl/bes/bes_bestelling.asp?urole=" + urole);
                else if ($("#disckey").val() > 0 && module == "RES")
                    $("#url").val("appl/res/res_reservering.asp?urole=" + urole);
                else if ($("#srtdisckey").val() > 0)
                    $("#url").val("appl/mld/mld_melding.asp?urole=" + urole);
            }
        }

        function menuitemChanged(init_key, reado)
        {
            var new_menuitem_key = init_key || parseInt($("#fac_menuitems_key :SELECTED").val(), 10);
            if (new_menuitem_key > -1)
            {
                $.getJSON( "../fac/get_fac_info_ajax.asp",
                        {   req_info: "menuitem",
                            menuitem_key: new_menuitem_key
                        },
                        data => { process_menuitem_info(data, reado); });
            }
            else
            {
                // Alleen de readonly velden leegmaken;
                $("#module, #sysFunc, #sysFrw").val("").closest("tr").hide();
                FcltMgr.resized();
            }
        }

<%      if (menuitem_key > -1)
        { %>
        menuitemChanged(<%=menuitem_key%>, <%=menu_key > -1 ? 1 : 0%>);
<%      } %>

        function process_menuitem_info(data, reado)
        {
            if (data)
            {
                // Rewritable velden;
                if (!reado) {
                    $("#label").val(data.label)
                               .trigger("change");
                    $("#groep").val(data.groep);
                    $("#url").val(data.url);
                    $("#image").val(data.image);
                    $("#alert").val(data.alert);
                }

                // Readonly velden;
                $("#module").val(data.module).closest("tr").show();
                $("#sysFunc").val(data.sysFunc).closest("tr").show();
                $("#sysFrw").val(data.sysFrw).closest("tr").show();

                var warning = "";
                if (data.sysFsrtdisc == 1 && data.sysFmod == "MLD")
                    warning = L("lcl_fac_menuexplode") + " " + L("lcl_vakgroup_type");
                else if (data.sysFsrtdisc == 1 && data.sysFmod == "RES")
                    warning = L("lcl_fac_menuexplode") + " " + L("lcl_srtactivity");
                else if (data.sysFdisc == 1)
                    warning = L("lcl_fac_menuexplode") + " " + L("lcl_bes_discipline");
                $("#explode-warning").html(warning ? I("fa-info-circle") + " " + safe.html(warning) : "");
            }
            else if (!reado)
            {
                // Alleen de readonly velden leegmaken;
                $("#module, #sysFunc, #sysFrw").val("").closest("tr").hide();
            }
            FcltMgr.resized();
        }

        function process_info(data)
        {
            var $select = (data.soort == 1 ? $("#srtdisckey") : $("#disckey") );
            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";

                    if (opt.sel == opt.key)
                        sel_key = opt.key;
                    $select.append($new_lov);
                }
                $select.prop("disabled", false);
            }
            else
            {
                $select.prop("disabled", true);
            }

            if (sel_key > -1)
            {
                $select.val(sel_key);
            }

            if ($("#disckey").val() == -1 && $("#srtdisckey").val() == -1)
                $("#url").prop("readonly", false);
            else // Catalogus of vakgroeptype heeft een waarde. Url aanpassen.
                fill_url("");
        }

        function menuoptionChanged()
        {
            var menuopt = $("#label").val();
            var menulbl = "";
            if (menuopt.length > 0)
            {
                if ( menuopt.slice(0,4) == "lcl_" )
                {
                    try {
                        menulbl = L(menuopt, {hide_error: true});
                    }
                    catch(e) { /* Val terug op lcl_tekst */ };
                }
                else
                {
                    menulbl = menuopt;
                }
            }
            $("#menu_lbl").text(menulbl);
        }

        $(function()
        {
            $("#label").change(menuoptionChanged);
            // ipv suppressEmpty zodat ze later weer aan getoggled kunnen worden;
            var $hideTheseTR = $("#module, #sysFunc, #sysFrw").filter("[value='']").closest("tr");
            $hideTheseTR.hide();
            if ($hideTheseTR.length)
                FcltMgr.resized();
        });

    </script>
  </head>

  <body class="editmode">
<%
    SUBFRAME_START();
    var buttons = [];

    buttons.push({ title: L("lcl_submit"), icon: "fa-fclt-save",    action: "doSubmit()" });
    buttons.push({ title: L("lcl_cancel"), icon: "fa-fclt-cancel",  action: "doCancel()" });

    IFRAMER_HEADER(L("lcl_fac_menuoptie"), buttons);
%>
      <form name="u2"
            method="post"
            action="fac_edit_menu_save.asp?menu_key=<%=(copy ? -1 : menu_key)%>&menuitem_key=<%=menuitem_key%>"
            target="hidFrameSubmit"
            onSubmit="doSubmit();">
<%
        BLOCK_START("menuOptie", L("lcl_menu_menublock"), { icon: "fa-clipboard-list" });

            sql = "SELECT fac_menuitems_key, "
                + (mobilemenu
                    ? ""
                    : "    DECODE(fac_menuitems_groep "
                        + "     , 0, "+ safe.qL("lcl_menu_pers")
                        + "     , 1, "+ safe.qL("lcl_menu_prof")
                        + "     , 2, "+ safe.qL("lcl_menu_config")
                        + " ) || ': ' ||")
                + "       COALESCE(fac_locale_xsl_tekst, ' (' || fac_menuitems_label || ')'),"
                + "       fac_menuitems_label"
                + "  FROM fac_menuitems, fac_locale_xsl xsl"
                + " WHERE xsl.fac_locale_xsl_label(+) = fac_menuitems_label"
                + "   AND xsl.fac_locale_xsl_lang(+) = " + safe.quoted_sql(user.lang())
                + (mobilemenu
                    ? " AND fac_menuitems_groep = 3"
                    : " AND fac_menuitems_groep IN (0, 1, 2)")
                + " ORDER BY fac_menuitems_groep, 2";

            FCLTselector("fac_menuitems_key",
                            sql,
                            {   label: L("lcl_fac_menuitem_opties"),
                                initKey: menuitem_key,
                                titleCol: "fac_menuitems_label",
                                emptyOption: "",
                                onChange: "menuitemChanged()"
                            });

            RWFIELDTR("label", "fld", L("lcl_fac_menuoptie"), label_db, { required: true, maxlength: 30, reartext: "<i id='explode-warning'></i>"});
            ROFIELDTR("fld", L("lcl_fac_menuoptie_label"), label, {id: "menu_lbl"});

            // Is dit nodig?
            RWFIELDTR("module", "fld", L("lcl_menu_module"), module, { readonly: true });

            // Tabblad
            if (mobilemenu)
            {
                ROFIELDTR("fld", L("lcl_menugroep"), L("lcl_menu_mobile"));
%>
                <input type="hidden" name="groep" value="3">
<%
            }
            else
            {
                sql = "SELECT 0, " + safe.qL("lcl_menu_pers")   + " FROM DUAL UNION ALL "
                    + "SELECT 1, " + safe.qL("lcl_menu_prof")   + " FROM DUAL UNION ALL "
                    + "SELECT 2, " + safe.qL("lcl_menu_config") + " FROM DUAL";
                FCLTselector("groep",
                                sql,
                                {   label: L("lcl_menugroep"),
                                    initKey: groep,
                                    emptyOption: "",
                                    required: true
                                });
            }

            sql = "SELECT 1, " + safe.qL("lcl_menu_level1") + " FROM DUAL UNION ALL "
                + "SELECT 2, " + safe.qL("lcl_menu_level2") + " FROM DUAL";
            FCLTselector("level",
                        sql,
                        {  label: L("lcl_menu_level"),
                            initKey: niveau,
                            emptyOption: "",
                            required: true
                        });

            RWFIELDTR("volgnr", "fld", L("lcl_menuvolgnr"), volgnr, { required: true, maxlength: 5 });

            RWFIELDTR("url", "fld", L("lcl_menu_fac_url"), urlType === "path" ? url : "");
            FILEPICKERTR("url", L("lcl_menu_or_file"), urlType === "file" ? url : "", { "module": "MENUURL", "key": menu_key, "icon": "fa-file-lines", "defaultValue":  L("lcl_menu_document") });

        BLOCK_END();

        BLOCK_START("menuAuth", L("lcl_menu_authblock"), { icon: "fa-portal-enter" });
            RWFIELDTR("sysFunc", "fld", L("lcl_fac_menusysautorisatie"), sysFunc, { readonly: true });
            RWFIELDTR("sysFrw", "fld", L("lcl_menu_fac_rw"), sysFrw, { readonly: true });

            FCLTautorisatieselector("altfunctie",
                                    "sgAutorisatie",
                                    {   label: L("lcl_fac_menuautorisatie"),
                                        autorisatieKey: extFkey ? extFkey : -1,
                                        startwithcode: true,
                                        extracode: "DISC",
                                        extraParamValue: "disc, srtdisc, fac_functie_code, module, cnt_srtdisc",    // Initiële waarden voor de extra value parameters worden via de initiële query bepaald.
                                                                                                                    // De parameter extraParamValueInit hoeft dan niet meegegeven te worden.
                                        onChange: "onchangeAltfunctie",
                                        whenEmpty: ""
                                    });

            // Bepaal of de fac_menuitems_disc en fac_menuitems_srtdisc gezet zijn voor bovenstaande altfunctie
            // Dit houdt geen rekening met Mobile [*1] en is te bot zo.
            var disc = 0;
            var srtdisc = 0;
            if (extFkey)
            {
                sql = "SELECT MAX(fac_menuitems_disc) disc"
                    + "     , MAX(fac_menuitems_srtdisc) srtdisc"
                    + "     , MAX(fac_menuitems_module) module"
                    + "  FROM fac_menuitems"
                    + " WHERE fac_functie_key = " + extFkey;
                var oRs = Oracle.Execute(sql);
                disc = (oRs("module").Value == "RES" ? oRs("srtdisc").Value : oRs("disc").value);
                srtdisc = oRs("srtdisc").value;
                oRs.Close();
            }

            sql = "SELECT ins_srtdiscipline_key"
                + "     , " + lcl.xsqla("ins_srtdiscipline_omschrijving", "ins_srtdiscipline_key", "ins_srtdiscipline_omschrijving")
                + " FROM ins_v_aanwezigsrtdiscipline";
            if (menu_key > -1)
                sql += " WHERE ins_srtdiscipline_module = " + safe.quoted_sql_upper(extFmod)
            sql += " ORDER BY 2";
            FCLTselector("srtdisckey",
                        sql,
                        {   label: L("lcl_mld_vakgroeptype"),
                            initKey: extFsrtdisc_key,
                            onChange: "onchangeSrtdisc()",
                            disable: !extFkey || extFkey == -1,
                            emptyOption: ""
                        });

            sql = "SELECT ins_discipline_key"
                + ", " + lcl.xsqla("ins_discipline_omschrijving", "ins_discipline_key", "ins_discipline_omschrijving")
                + "  FROM ins_tab_discipline"
                + " WHERE ins_discipline_verwijder IS NULL";
            if (menu_key > -1)
                sql += "  AND ins_discipline_module = " + safe.quoted_sql_upper(extFmod);
            if (extFsrtdisc_key > -1)
                sql += "   AND ins_srtdiscipline_key = " + extFsrtdisc_key;
            sql += " ORDER BY ins_discipline_module, 2";
            FCLTselector("disckey",
                        sql,
                        {   label: L("lcl_bes_discipline"),
                            initKey: extFdisc_key,
                            onChange: "fill_url('disc')",
                            disable: !extFkey || extFkey == -1,
                            emptyOption: ""
                        });
        BLOCK_END();

        BLOCK_START("menuMore", L("lcl_menu_moreblock"), { icon: "fa-cogs" });
            RWFIELDTR("uitleg", "fld", L("lcl_menuinfo"), uitleg, { maxlength: 1024 });
            RWFIELDTR("alert", "fld", L("lcl_menumessage"), alert, { maxlength: 1024 });

            RWCHECKBOXTR("portal", "fldcheck", mobilemenu ? L("lcl_menu_app") : L("lcl_menuportal"), portal);

            RWSYMBOLTR("image", L("lcl_image"), image, { "module": "MENU", "key": menu_key });
        BLOCK_END();

IFACE.FORM_END();
%>
      </form>
      <% SUBFRAME_END(); %>
      <iframe src="../Shared/empty.html" name="hidFrameSubmit" style="display:none"></iframe>
  </body>
</html>
<% ASPPAGE_END(); %>
