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

    File:               res_edit_objcat.asp
    Remark:             allow adding of res_deel and res_artikel

    Parameters:
        rsv_ruimte_key  required, existing rsv_ruimte_key. Al het andere zoeken we er zelf bij
        urole           required
    Context:            iframe van res_reservering.asp

*/
 %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../shared/iface.inc" -->
<!-- #include file="../Shared/discxalg3d.inc" -->
<!-- #include file="../shared/kpl_ksrt_validate.inc" -->
<!-- #include file="res.inc" -->
<!-- #include file="../ins/ins.inc" -->
<!-- #include file="res_flexkenmerk_art.inc" -->
<!-- #include file="res_plan_obj_v2.inc" -->
<!-- #include file="res_cat.inc" -->

<%
FCLTHeader.Requires({ plugins: ["jQuery", "suggest"],
                      js: ["date.js", "jquery.timepicker-table.js", "jquery-ui.js", "../res/res_plan.js"],
                     css: ["../res/res.css", "timePicker-table.css"]});

var urole = getQParamSafe("urole");
var rsv_ruimte_key = getQParamInt("rsv_ruimte_key");
var res_artikel_key = getQParamInt("res_artikel_key", -1);
var verynew = getQParamInt("verynew", 0);
res.res_set_dialect(rsv_ruimte_key);

var res_deel_key = getQParamInt("res_deel_key", -1); // Default
var disc_key = getQParamInt("disc_key", -1);  // Auto openklappen

if (res_deel_key > 0)
{
  sql = "SELECT res_discipline_key"
      + "  FROM res_deel"
      + " WHERE res_deel_key = " + res_deel_key;
  oRs = Oracle.Execute(sql);
  disc_key = oRs("res_discipline_key").value;
}

// Zo snel mogelijk relevante basisinformatie opzoeken
sql = "SELECT res_reservering_key"
    + "     , res_rsv_ruimte_verwijder"
    + "     , alg_ruimte_key, res_ruimte_opstel_key"
    + "     , mld_opdr_key"
    + "     , res_rsv_ruimte_van, res_rsv_ruimte_tot"
    + "     , res_rsv_ruimte_bezoekers"
    + "     , trunc(res_rsv_ruimte_tot) - trunc(res_rsv_ruimte_van) meerdaags"
    + "     , prs_kostenplaats_key"
    + "     , res_activiteit_key"
    + "  FROM res_rsv_ruimte"
    + " WHERE res_rsv_ruimte_key = " + rsv_ruimte_key;
oRs = Oracle.Execute(sql);
var resdeleted = (oRs("res_rsv_ruimte_verwijder").value != null);
var res_van = new Date(oRs("res_rsv_ruimte_van").value);
var res_tot = new Date(oRs("res_rsv_ruimte_tot").value);
var res_duur = (res_tot - res_van) / 1000 / 60 / 60; // duration from milliseconds to hours
var res_bezoekers = oRs("res_rsv_ruimte_bezoekers").value;
var res_meerdaags = oRs("meerdaags").value!=0;
var activiteit_key = oRs("res_activiteit_key").value;

if (oRs("alg_ruimte_key").value != null)
  restype = "CV"
else if (oRs("res_ruimte_opstel_key").value != null)
  restype = "R"
else
  restype = "O"

var alg_ruimte_key = oRs("alg_ruimte_key").value || -1;
var mld_opdr_key = oRs("mld_opdr_key").value || -1;
var has_kostenplaats_key = oRs("prs_kostenplaats_key").value != null;
oRs.Close()

var fronto = (urole == "fo");
var backo = (urole == "bo");
var frontend = (urole == "fe");

var portal_alg_ruimte_key = getQParamInt("portal_alg_ruimte_key", -1);

if (urole == "fo")
  var autfunction = "WEB_RESFOF";
else if (urole == "bo")
  var autfunction = "WEB_RESBOF";
else // fe
  var autfunction = "WEB_RESUSE";

var authparams = user.checkAutorisation(autfunction)

%>

<html>
  <head>
<%  FCLTHeader.Generate() %>
<%
    // Bereken dynamisch breedte blokjes
    var width_px = getQParamInt("width_px", 1024);
    var nr_days = Math.round(1 + (res_tot.midnight() - res_van.midnight()) / 24 / 60 / 60 / 1000);

    var hour_px = res.hour_px(width_px - 250, nr_days);

%>
    <script type="text/javascript">
      var hour_px = <%=hour_px%>;
      var res_cat_t1 = <%=safe.jsfloat(S("res_cat_t1"))%>;
      var res_cat_t2 = <%=safe.jsfloat(S("res_cat_t2"))%>;

      // Worden in res_plan.js gebruikt:
      var res_van = new Date(<%=res_van.getTime()%>);
      var res_tot = new Date(<%=res_tot.getTime()%>);
    </script>

<%
    var starttime_room = S("res_t1");
    var endtime_room = S("res_t2");
    sql = "SELECT COALESCE(ru.res_ruimte_begintijd, " + S("res_t1") + ") begintijd"
        + ",      COALESCE(ru.res_ruimte_eindtijd, " + S("res_t2") + ") eindtijd"
        + ",      ro.res_ruimte_key"
        + " FROM res_ruimte ru"
        + ",     res_rsv_ruimte rr"
        + ",     res_ruimte_opstelling ro"
        + " WHERE ru.res_ruimte_key = ro.res_ruimte_key"
        + " AND ro.res_ruimte_opstel_key = rr.res_ruimte_opstel_key"
        + " AND rr.res_rsv_ruimte_key = " + rsv_ruimte_key;
    oRs = Oracle.Execute(sql);
    if (!oRs.eof)
    { // Found, blijkbaar type=='R'
      var starttime_room = oRs("begintijd").value;
      var endtime_room = oRs("eindtijd").value;
      if (starttime_room < S("res_t1")) starttime_room = S("res_t1");
      if (endtime_room > S("res_t2")) endtime_room = S("res_t2");
      if (starttime_room > endtime_room) starttime_room = endtime_room;
      res_ruimte_key = oRs("res_ruimte_key").value;
    }
    else
    {
      res_ruimte_key = -1;
    }
    oRs.Close();
%>

    <script type="text/javascript">
        function doFilter(event)
        {
            function _applyFilter() {
              var $this = $(event.target);
              var valThis = $this.val().toLowerCase();
              // Zolang je *meer* letters tikt hoeven we altijd alleen te hiden
              // Dat is op IE11 veel sneller dan toggle
              var hideOnly = valThis.indexOf(window.lastFilter) == 0;
              if ($this[0].id.indexOf("-allobj") > -1)
              { // Filter over alle objecten.
                // Nieuwe res_plan_obj_v2
                $(".objcatline .labelgrid", $("#resObjList")).each(function()
                    {
                        if ($("label", this).length > 0)
                        {
                            var text = $("label", this)[0].innerText.toLowerCase();
                            var found = text.indexOf(valThis) > -1;
                            if (!found)
                                this.style.display = "none";
                            else if (!hideOnly)
                                $(this).show();
                        }
                    });
              }
              else if ($this[0].id.indexOf("-allcat") > -1)
              { // Filter over alle catering.
                $(".catline", $("#resCatList")).each(function()
                    {
                        if ($("label", this).length > 0)
                        {
                            var text = $("label", this)[0].innerText.toLowerCase();
                            var found = text.indexOf(valThis) > -1;
                            if (!found)
                                this.style.display = "none";
                            else if (!hideOnly)
                                $(this).show();
                        }
                    });
              }
              else
              { // Filter op een specifieke object/catering discipline
                $("tbody tr", $this.closest("table")).each(function()
                    {
                        if ($("label", this).length > 0)
                        {
                            var text = $("label", this)[0].innerText.toLowerCase();
                            var found = text.indexOf(valThis) > -1;
                            if (!found)
                                this.style.display = "none"; // Veel sneller met IE11 dan $(this).hide();
                            else if (!hideOnly)
                                $(this).show();
                        }
                    });
              }
              window.lastFilter = valThis;
              if (typeof updateTableHeaders === "function")
                  updateTableHeaders();
              if (!hideOnly)
                  FcltMgr.resized();
            }

            if (event.which == 27) {
                $(event.target).val("");
            }
            setTimeout(_applyFilter, 200);
        }

        function setFilter() {
          //    $frameHeader.find("#iframerextratitle").after("<input id='autofilter' type='text' placeholder='"+L("lcl_autofilter")+"'>");
              $("[id^=autofilter-").off("keyup").on("keyup", doFilter);
        }
        $(function() {
          setFilter();
        });

      var rsv_ruimte_key = <%=rsv_ruimte_key%>;
      var mld_opdr_key = <%=mld_opdr_key%>;
      var urole = "<%=urole%>";
      var backo = <%=backo? 1 : 0%>;
      var fronto = <%=fronto? 1 : 0%>;
      var frontend = (1 == <%=frontend? 1 : 0%>);

      function res_submit_callback(json)
      {
        if (json.success)
          FcltMgr.closeDetail(window, json);
        else
          iface.button.enable("btn_objcat_submit");
      }

      function checkBulkAmount()
      {
        var returnValue = true;
        function _check()
        {
          var $this = $(this);
          var $labelgrid = $this.parent().prevAll("div.labelgrid").first();
          $this.removeClass("bad");
          var value = parseInt($this.val(), 10);
          var max = parseInt($this.attr("max"), 10);
          if ($("input[type=checkbox]", $labelgrid).prop("checked") &&
                (value > max || value < 0))
          {
            $this.addClass("bad");
            returnValue = false;
          }
        }
        $("input.bulkamount").each(_check);
        return returnValue;
      }

      async function res_submit()
      {
        if (!await validateForm("u2"))
          return false;

        if (checkArtikelen(<%=safe.jsfloat(starttime_room)%>, <%=safe.jsfloat(endtime_room)%>))
        {
          if (checkBulkAmount())
          {
            $.post($("form[name=u2]")[0].action, $("[name=u2]").serialize(), FcltCallbackAndThenAlways(res_submit_callback), "json");
            return true;
          }
          else
          {
            FcltMgr.alert(L("lcl_obj_bad_value"));
            return false;
          }
        }
        else
          return false;
      }

      function res_cancel()
      {
        FcltMgr.closeDetail(window, { cancel: true, verynew: <%=verynew%> } );
      }

var new_item_key = -1;  // Globaal
      function res_addcat(elm)
      {
        new_item_key = new_item_key -1;
        var $tr      = $(elm).closest("tr");
        var $clone   = $tr.clone(true); // Elementdata, flexkenmerken en event handlers klonen.
        var artkey   = $tr.attr("id").substring(3);
        var res_rsv  = artkey + "_" + new_item_key;
        // De clone bijwerken..
        $clone.find(':button').addClass("invisible"); // De toevoegen knop onzichtbaar maken
        $("[id^='inpbh1_c_']", $clone).val("");   // Urenveld leeg maken.
        $("[id^='inpeh1_c_']", $clone).val("");   // Afhalenurenveld leeg maken.
        $("[id^='inpem1_c_']", $clone).val("");   // Afhalenminutenveld leeg maken.
        var id_num = $("[id^='inpbh1_c_']", $clone).attr('id').substring(9);
        // Nieuwe unieke id's aan de velden toekennen.
        $("[id^='inpbd_c_']",  $clone).attr({id: "inpbd_c_"  + res_rsv, name: "inpbd_c_"  + res_rsv, value: ""}); // vrije artikelomschrijving
        $("[id^='inpb_c_']",   $clone).attr({id: "inpb_c_"   + res_rsv, name: "inpb_c_"   + res_rsv}); // Aantal.
        $("[id^='inpbp_c_']",  $clone).attr({id: "inpbp_c_"  + res_rsv, name: "inpbp_c_"  + res_rsv}); // Prijs.
        $("[id^='inpbtp_c_']", $clone).attr({id: "inpbtp_c_" + res_rsv, name: "inpbtp_c_" + res_rsv}); // Totaalprijs.
        $("[id^='inpbh1_c_']", $clone).attr({id: "inpbh1_c_" + res_rsv, name: "inpbh1_c_" + res_rsv}); // Tijd uren.
        $("[id^='inpbm1_c_']", $clone).attr({id: "inpbm1_c_" + res_rsv, name: "inpbm1_c_" + res_rsv}); // Tijd minuten.
        $("[id^='inpeh1_c_']", $clone).attr({id: "inpeh1_c_" + res_rsv, name: "inpeh1_c_" + res_rsv}); // Afhaaltijd uren.
        $("[id^='inpem1_c_']", $clone).attr({id: "inpem1_c_" + res_rsv, name: "inpem1_c_" + res_rsv}); // Afhaaltijd minuten.


        var trflex_all = $tr.find($("[id$='_all']"));
        if (trflex_all)
        { // Er zijn flexkenmerken. Deze staan in één tr.
          // Nieuwe unieke id's aan de velden toekennen.
          for (var flex_num = 1; flex_num <= trflex_all.val(); flex_num++)
          {
            // In res_flexkenmerk_art wordt het id aangepast vlak voor het aanroepen van listKenmerk.
            // Een minteken (nieuw kenmerkwaarde) wordt omgezet naar een underscore. Op deze id's moet gezocht worden.
            res_rsv = res_rsv.replace("-", "_");
            id_num = id_num.replace("-", "_");

            $("[id^='art" + id_num + "_" + flex_num + "val']", $clone).prop({id: "art" + res_rsv + "_" + flex_num + "val", name: "art" + res_rsv + "_" + flex_num + "val"}); // val.
            $("[id^='art" + id_num + "_" + flex_num + "key']", $clone).attr({id: "art" + res_rsv + "_" + flex_num + "key", name: "art" + res_rsv + "_" + flex_num + "key"}); // key.
            $("[id^='art" + id_num + "_" + flex_num + "t']",   $clone).attr({id: "art" + res_rsv + "_" + flex_num + "t",   name: "art" + res_rsv + "_" + flex_num + "t"}); // t.
            $("[id^='art" + id_num + "_" + flex_num + "p']",   $clone).attr({id: "art" + res_rsv + "_" + flex_num + "p",   name: "art" + res_rsv + "_" + flex_num + "p"}); // p.
            $("[id^='art" + id_num + "_" + flex_num + "d']",   $clone).attr({id: "art" + res_rsv + "_" + flex_num + "d",   name: "art" + res_rsv + "_" + flex_num + "d"}); // d.
            $("[id^='art" + id_num + "_" + flex_num + "e']",   $clone).attr({id: "art" + res_rsv + "_" + flex_num + "e",   name: "art" + res_rsv + "_" + flex_num + "e"}); // e.
            $("[id^='art" + id_num + "__"           + "all']", $clone).attr({id: "art" + res_rsv + "__" + "all",           name: "art" + res_rsv + "__"           + "all"}); // e.

            // Aan het hidden checkbox veld has_xxx ook een nieuwe unieke id aan toekennen.
            $("[id^='has_art" + id_num + "_" + flex_num + "val']",   $clone).attr({id: "has_art" + res_rsv + "_" + flex_num + "val",   name: "has_art" + res_rsv + "_" + flex_num + "val"}); // Hidden checkbox veld has_xxx.

            // If the existing field had a timePicker, get the options from that timePicker and remove it from the new field (but remember the settings)
            if (typeof minMax != "undefined" && ("art" + id_num + "_" + flex_num) in minMax)
            {
              $(".fldflexT[id^='art" + res_rsv + "_" + flex_num + "val']", $clone).each(function()
              { // Create new object from the existing timePicker options for later use
                minMax["art" + res_rsv + "_" + flex_num] = $.extend({}, { step: 15,                               // Default options from kenmerk_common
                                                                          startTime: "00:00",
                                                                          endTime  : "23:59",
                                                                          columns  : <%=S("timepickercolumns")%>,
                                                                          onChange : function () {
                                                                            $timeInput = $(this).parents("div.time-holder").prev("input.fldflexT")
                                                                            $timeInput.removeClass("bad");
                                                                            $timeInput.trigger("change");
                                                                          }
                                                                        },
                                                                        minMax["art" + id_num + "_" + flex_num],  // Existing properties from original timepicker
                                                                        { "instantiated": false });               // Re-instantiate this timePicker
                // Remove old timePicker
                $(this).next(".time-holder").remove();
                $(this).off("click");
              });
            }

            $(".fldflexD.hasDatepicker[id^='art" + res_rsv + "_" + flex_num + "val']", $clone).addClass("remakeDatepicker");

          }
        }

        // Voeg de clone onder de huidige regel toe.
        $tr.after($clone);

        // Initiate newly created timePickers
        // minMax holds all (custom) options for timePickers
        // minMax.instantiated = false if the timePicker has not been made yet, if so -> make it now
        if (typeof minMax != "undefined")
          for (x in minMax)
            if (minMax[x].instantiated === false && $("#"+x+"val").length == 1)
            {
              $("#"+x+"val").timePicker(minMax[x]);
              minMax[x].instantiated = true;
            }

        // Remake flex datepickers
        $(".remakeDatepicker").each(function()
        {
            // Just to identify
            $(this).removeClass("remakeDatepicker");

            var $id = $(this).attr("id");
            var dpOptions = $(this).datepicker("option", "all");

            $(this).datepicker("destroy")
                   .datepicker(dpOptions)
                   .next("i.dateklikker").attr({ onclick: "$('#" + $id + "').datepicker('show')" });
        });

        $("[id^='inpbh1_c_']",$clone).focus(); // Zet cursor in urenveld.

        FcltMgr.resized();
        return $clone;
      }

      function showTotPriceArt_ex(elm)
      {
        var $tr     = $(elm).closest("tr");
        var inpb_c  = $("[id^='inpb_c_']",  $tr).attr("id");
        var res_rsv = inpb_c.substr(7);
        showTotPriceArt(res_rsv);
      }

      // add arrangement items
      function extractLastTwo(item) {
        var item_length = (item.length || 0);
        return ("00").concat(item).substr(item_length, item_length +2);
      }
      function changeTimeOfItemAfterLoad(items, arrangement_key) {
        return function() {
          for (var disc_key in items[arrangement_key]) {
            // Clientside invullen
            for (item in items[arrangement_key][disc_key]) {
              if ((itemRow = $("#row"+item)).length) { // when item is available in the list
                // use begin time of item, if any
                if (items[arrangement_key][disc_key][item]) {
                  // split time in hours and minutes
                  arr = String(items[arrangement_key][disc_key][item]).split(".");
                  if (!arr[1])
                  {
                    arr[1] = 0;
                  }
                  else
                  {
                    arr[1] = String(("0." + arr[1]) * 60);
                  }
                  $("[id^='inpbh1_c_']", itemRow).val(extractLastTwo(arr[0]));
                  $("[id^='inpbm1_c_']", itemRow).val(extractLastTwo(arr[1]));
                }
              }
            }
          }
        }
      }
      function addArrangementItems(json) {
        var itemAmt, itemRow, catLine, catLink, catSign;
        var arrangement_key = json.arrangement_key;
        var arrangement_aantal = json.arrangement_aantal;
        var uren = json.uren;
        var minuten = json.minuten;
        var arr = [];

        for (var disc_key in items[arrangement_key])
        {
            var tabel = $("#table_dis" + disc_key);
            if (!tabel.length) // nog niet opengeklapt. Alsnog laden met goede aantallen bij de artikelen
            {
                ItemChoosed_cat($("#objcatline" + disc_key)[0], "div_dis"+disc_key, disc_key, "&" + serializeObj(json), changeTimeOfItemAfterLoad(items, arrangement_key));
            }
            else // else clientside invullen
            {
                for (item in items[arrangement_key][disc_key]) {
                  if ((itemRow = $("#row"+item)).length) { // when item is available in the list
                    catLine = itemRow.closest("div.objcatline");
                    catLink = $("a", catLine);
                    catSign = $("i", catLink);
                    catSign.removeClass("fa-plus-square").addClass("fa-plus-minus");
                    catLine.removeClass("closed").addClass("existing");
                    itemRow.removeClass("notexisting").addClass("existing");
                    itemAmt = $("input.fld_catamount", itemRow);
                    if (itemAmt.val() == 0) {
                      $("input.fld_catamount", itemRow).val(arrangement_aantal);
                      itemAmt.blur();
                    }
                    else
                    {
                      itemRow = res_addcat(itemAmt); // JGL: Twijfel, lang niet alle artikelen mogen meerdere keren voorkomen toch?
                      $("input.fld_catamount", itemRow).val(arrangement_aantal);
                    }
                    // use begin time of item, if any
                    if (items[arrangement_key][disc_key][item]) {
                      // split time in hours and minutes
                      arr = String(items[arrangement_key][disc_key][item]).split(".");
                      if (!arr[1])
                      {
                        arr[1] = 0;
                      }
                      else
                      {
                        arr[1] = String(("0." + arr[1]) * 60);
                      }
                      $("[id^='inpbh1_c_']", itemRow).val(extractLastTwo(arr[0]));
                      $("[id^='inpbm1_c_']", itemRow).val(extractLastTwo(arr[1]));
                    }
                    else
                    {
                      // else use begin time of reservation
                      $("[id^='inpbh1_c_']", itemRow).val(extractLastTwo(uren));
                      $("[id^='inpbm1_c_']", itemRow).val(extractLastTwo(minuten));
                    }
                  }
                }
            }
        }
      }

    </script>
  </head>

  <body class="editmode">
<%  SUBFRAME_START();
    var buttons =  [ {title: L("lcl_submit"), icon: "fa-fclt-save", action:"res_submit()", singlepress: true, id:"btn_objcat_submit" },
                     {title: L("lcl_cancel"), icon: "fa-fclt-cancel", action:"res_cancel()" } ];
    IFRAMER_HEADER(L("lcl_res_frame_voorziening"), buttons);
%>
      <form name="u2" method="post" action="res_edit_objcat_save.asp?urole=<%=urole%>&rsv_ruimte_key=<%=rsv_ruimte_key%>&verynew=<%=verynew%>">
<%

        //    ==========================================================================
        //    Description:        Bouwen van het voorzieningen edit blok voor een reservering

        // Tel in elke catalogus hoeveel objecten in de gekozen ruimte echt gereserveerd kunnen worden.
        // Als dat er nul zijn dan tonen we de discipline namelijk niet.
        var countparams = { alg_ruimte_key : alg_ruimte_key,
                            mld_opdr_key   : mld_opdr_key,
                            res_ruimte_key : res_ruimte_key,
                            select_fields_d: "r.res_discipline_key, COUNT(*) x ",
                            select_fields_p: "dis.ins_discipline_key, COUNT(*) x ",
                            sdisc          : "dis.ins_discipline_key",
                            autfunction    : autfunction,
                            res_tot        : res_tot,
                            group_by_d     : " GROUP BY r.res_discipline_key",
                            group_by_p     : " GROUP BY dis.ins_discipline_key"
                          };
        var sql_aantal = " (SELECT COALESCE(SUM(x), 0) FROM " + get_res_deel_sql(countparams) + " sum_tbl WHERE sum_tbl.ins_discipline_key = dis.ins_discipline_key) aantal ";
        sql= "SELECT dis.ins_discipline_key,"
           + "       "+ lcl.xsqla('dis.ins_discipline_omschrijving','dis.ins_discipline_key') +","
           + "       dis.ins_discipline_kpnverplicht,"
           + "       dis.ins_discipline_image,"
           + "       dis.ins_discipline_min_level,"   // dan kunnen we onderscheid maken
           +         sql_aantal
           + "  FROM res_v_aanwezigdiscipline dis"
           + "  WHERE ins_discipline_min_level IN (1, 4, 5)" // via res_deel (object/planbare persoon/werkplek)
           + "   AND dis.ins_discipline_key IN("
           + "        SELECT g.ins_discipline_key FROM fac_v_webgebruiker g, fac_functie f "
           + "         WHERE g.fac_functie_key = f.fac_functie_key "
           + "           AND f.fac_functie_code = " + safe.quoted_sql(autfunction)
           + "           AND g.fac_gebruiker_alg_level_write < 9"
           + "           AND g.fac_gebruiker_prs_level_write < 9"
           + "           AND g.prs_perslid_key = " + user_key
           + "        )"
           + "   AND EXISTS (SELECT res_discipline_key"
           + "           FROM res_deel r"
           + "          WHERE r.res_deel_verwijder IS NULL"
           + "            AND r.res_discipline_key = dis.ins_discipline_key)"
           + "   AND EXISTS (SELECT res_activiteit_key FROM res_activiteitdiscipline rad"
           + "          WHERE rad.res_discipline_key = dis.ins_discipline_key"
           + "          AND rad.res_activiteit_key = " + activiteit_key
           + "        )";

        if (disc_key > 0 && res_deel_key < 0) sql = sql  + " AND dis.ins_discipline_key = " + disc_key;

        if (S("vis_parking_key") != -1) sql = sql + " AND dis.ins_discipline_key != " + S("vis_parking_key");

        if (S("res_fe_discs_only_in_res") != -1 && !fronto && !backo && restype == 'CV')
          sql = sql  + " AND dis.ins_discipline_key NOT IN (" + S("res_fe_discs_only_in_res") + ") ";

        sql = sql  + " ORDER BY ins_discipline_min_level, ins_discipline_volgnr, 2";
        oRs1 = Oracle.Execute(sql);

        first = true;
        //
        var arrangementDiscs = [];
        var sql = "SELECT DISTINCT ra.res_discipline_key "
                + "FROM   res_arrangement_artikel aa, res_artikel ra "
                + "WHERE  aa.res_artikel_key = ra.res_artikel_key ";
        var oRs = Oracle.Execute(sql);
        while (!oRs.eof) {
          arrangementDiscs.push(oRs("res_discipline_key").Value);
          oRs.MoveNext();
        }
        oRs.close();

        var curr_disc_type = -1;  // als dit type wisselt mag er ook een nieuw block
        while(!oRs1.eof)
        {
          var curr_disc_key = oRs1("ins_discipline_key").value;
          var existing = false; // zodadelijk highlighten
          sql = "SELECT COUNT(res_rsv_deel_key) aantal"
              + "  FROM res_rsv_deel rrd"
              + "     , res_v_aanwezigdeel rd"
              + " WHERE res_rsv_ruimte_key = " + rsv_ruimte_key
              + "   AND res_rsv_deel_verwijder IS NULL"
              + "   AND rrd.res_deel_key = rd.res_deel_key"
              + "   AND res_discipline_key = " + curr_disc_key

          var oRs2 = Oracle.Execute(sql);
          existing = (oRs2("aantal").value > 0);
          if (oRs1("aantal").value != 0)
          {
            if (first || oRs1("ins_discipline_min_level").value != curr_disc_type)
            {
              var buttons1 = [];
              if (first)
                buttons1.push({ title: L("lcl_open_all"), id: "btn_open_allobj", action: "loadAllObjects()", icon: "fa-chevron-right", importance: 3 });
              if (!first) // we gaan over naar een ander type. Logisch is dat de types bij elkaar staan, maar men kan met ins_discipline_volgnr anders besloten hebben
                BLOCK_END();

              if (oRs1("ins_discipline_min_level").value == 5)
                BLOCK_START("resObj", L("lcl_res_wpcat"), { wide: true, buttons: buttons1, icon: "fa-lamp-desk" });
              else if (oRs1("ins_discipline_min_level").value == 4)
                BLOCK_START("resObj", L("lcl_res_persons"), { wide: true, buttons: buttons1, icon: "fa-clipboard-user" });
              else // dat moet dan 1 zijn
                BLOCK_START("resObj", L("lcl_res_objects"), { wide: true, buttons: buttons1, icon: "fa-clipboard-list-check" });

%>
              <tr>
                <td>
<%                if (res_van.midnight().getTime() != res_tot.midnight().getTime())
                  {
                      Response.Write(toDateString(res_van.midnight()));
                      Response.Write(" " + L("lcl_res_totenmet") + " " + toDateString(res_tot.midnight()));
                  }
%>              </td>
              </tr>
<%            first = false;
              curr_disc_type = oRs1("ins_discipline_min_level").value;
            }
%>
            <tr>
              <td>
<%              if (!has_kostenplaats_key && oRs1("ins_discipline_kpnverplicht").value == 1)
                {
                    var loading_txt = L("lcl_select_account_disc");
%>
                  <div class="objcatline notavailable">
                    <%=safe.html(oRs1("ins_discipline_omschrijving").value)%>
                    <%=(existing? " (" + oRs2("aantal").value + ")" : "")%>
<%              }
                else
                {
                    var loading_txt = L("lcl_shared_loading");
%>
                  <div class="objcatline <%=(existing? " existing" : "")%>
                                         <%=disc_key != curr_disc_key? " closed" : ""%>"
                       id="objcatline<%=curr_disc_key%>"
                       onClick="ItemChoosed_obj(this, 'div_dis<%=curr_disc_key%>',<%=curr_disc_key%>, <%=hour_px%>)">
                    <%=I((disc_key == curr_disc_key ? "fa-minus-square" : "fa-plus-square") + " fa-lg") + "&nbsp;" %>
                    <%=oRs1("ins_discipline_image").Value ? I(oRs1("ins_discipline_image").Value + " fa-lg") + "&nbsp;" : "&nbsp;" %>
                    <a>
                      <%=safe.html(oRs1("ins_discipline_omschrijving").value)%>
                      <%=(existing? " (" + oRs2("aantal").value + ")" : "")%>
                    </a>
<%              } %>
                    <div class="objcatdiv" id="div_dis<%=curr_disc_key%>" onClick="FcltMgr.stopPropagation(event)">
<%                    // Hier wordt met Ajax obj_schedule.asp code tussen geplakt bij openklappen
                      if (disc_key == curr_disc_key)
                        make_plan_obj(curr_disc_key, res_van, res_tot,
                                        { hour_px: hour_px,
                                          rsv_ruimte_key: rsv_ruimte_key,
                                          res_deel_key: res_deel_key,
                                          forSelectObj: true,
                                          autfunction: autfunction,
                                          isload: true,
                                          hidefilter: true
                                        });
                      else
                        Response.Write(loading_txt);
%>
                    </div>
                  </div>
              </td>
            </tr>
<%        }
          oRs2.close();
          oRs1.MoveNext();
        }
%>
    <script>
        function loadAllObjects()
        {
            // Van geopende objecten filter verbergen
            $("#resObjList .objcatline").each(function()
            {
                disc_key = $(this)[0].id.substr(10);
                $("#autofilter-"+disc_key).css("display", "none");
            });
            // Alle nog niet geopende objecten openen
            $("#resObjList .objcatline.closed").each(function()
            {
                disc_key = $(this)[0].id.substr(10); // "objcatline" eraf halen
                ItemChoosed_obj($("#objcatline" + disc_key)[0], "div_dis"+disc_key, disc_key, hour_px, "&hidefilter=1");
            });
            //Voeg een globaal filter voor objecten toe.
            $("#resObj").find("div .blockbuttoncontainer").prepend("<input id='autofilter-allobj' type='text' placeholder='<%=safe.htmlattr(L("lcl_autofilter"))%>'>");
            // Verwijder knop "Open alles"
            $("#btn_open_allobj").css("display", "none");
            $("#autofilter-allobj").attr("style", "border-color: red; border: 2px;");
            setFilter();
        }
    </script>
<%
        oRs1.close();
        if (!first)
          BLOCK_END();


        //    ==========================================================================
        //    Description:        Bouwen van het catering edit blok voor een reservering

        // begin: Toon catering

        // Bepaal de catalogie waar wij rechten op hebben en die mogelijk zijn in 'onze' ruimte
        fixed_room = (portal_alg_ruimte_key > 0);

        var sql_fo_catering_scope = "";
        if (!(S("res_fo_catering_scopeless") && (backo || fronto)))
        {
            // RES_V_SRTARTIKEL_ONRGOED i.p.v. res_v_srtartikel_ruimte:
            // niet alleen kijken naar max(prio) 'R' (ruimte) maar ook naar onderliggende prio's 'L' (locatie) en 'G' (gebouw)
            // In de view res_v_srtartikel_ruimte wordt alleen naar de maximale prio gekeken van een bepaalde alg_ruimte_key
            sql_fo_catering_scope = "    AND g.ins_discipline_key IN"
                                  + "(SELECT res_discipline_key"
                                  + "   FROM res_v_srtartikel_onrgoed"
                                  + "  WHERE ( alg_onrgoed_ingangsdatum IS NULL OR alg_onrgoed_ingangsdatum <= {0})".format(res_van.toSQL())
                                  + "    AND ( alg_onrgoed_vervaldatum  IS NULL OR alg_onrgoed_vervaldatum  > {0})".format(res_tot.toSQL())
                                  + ( fixed_room
                                    ? "  AND alg_onrgoed_niveau = 'R'"
                                    : ""
                                    )
                                  + ( alg_ruimte_key > 0
                                    ? "  AND alg_ruimte_key = " + alg_ruimte_key
                                    : "  AND alg_ruimte_key IN"
                                         + "(SELECT alg_ruimte_key"
                                         + "   FROM res_v_rsv_ruimte_2_alg_ruimte "
                                         + "  WHERE res_alg_ruimte_verwijder IS NULL "
                                         + "    AND res_rsv_ruimte_key = " + rsv_ruimte_key
                                         + ")"
                                    )
                                  + ")";
        }

        sql = "SELECT d.ins_discipline_key"
            + "     , "+ lcl.xsqla('d.ins_discipline_omschrijving','d.ins_discipline_key')
            + "     , d.ins_discipline_kpnverplicht"
            + "     , d.ins_discipline_image"
            + "     , rd.res_disc_params_min_deelnmrs, rd.res_disc_params_min_duur"
            + (arrangementDiscs && arrangementDiscs.length
                ? " , CASE WHEN d.ins_discipline_key IN (" + arrangementDiscs.join(",") + ") THEN 1 ELSE 0 END inArrangement"
                : " , 0 inArrangement")
            + "  FROM RES_v_aanwezigDISCIPLINE d, res_disc_params rd"
            + " WHERE ins_discipline_min_level = 2"
            + "   AND rd.res_ins_discipline_key = d.ins_discipline_key"
            + "   AND d.ins_discipline_key IN"
                  + "(SELECT g.ins_discipline_key"
                  + "   FROM fac_v_webgebruiker g"
                  + "      , fac_functie f"
                  + "  WHERE g.fac_functie_key = f.fac_functie_key"
                  + "    AND f.fac_functie_code = " + safe.quoted_sql(autfunction)
                  + "    AND g.prs_perslid_key = " + user_key
                  + "    AND fac_gebruiker_prs_level_write < 9"
                  + "    AND fac_gebruiker_alg_level_write < 9"
                  + sql_fo_catering_scope
                  + ")"
            + "   AND EXISTS"
                  + "(SELECT res_activiteit_key"
                  + "   FROM res_activiteitdiscipline rad"
                  + "  WHERE rad.res_discipline_key = d.ins_discipline_key"
                  + "    AND rad.res_activiteit_key = " + activiteit_key
                  + ")"
            + " ORDER BY ins_discipline_volgnr, 2";
        oRs = Oracle.Execute(sql);

        if (!oRs.eof)
        {
          var buttons2 = [];
          if (arrangementDiscs.length && (res_meerdaags && !S("res_allow_multi_cat")) == false)
              buttons2.push({ icon: "fa-shapes", title: L("res_arrangement"), id: "btn_arrangement", action: "selectArrangement()" });
          buttons2.push({ title: L("lcl_open_all"), id: "btn_open_allcat", action: "loadAllCatering()", icon: "fa-chevron-right", importance: 3 });
          BLOCK_START("resCat", L("lcl_consumable_objects"), { wide: true, buttons: buttons2, icon: "fa-clipboard-list" });
          if (res_meerdaags && !S("res_allow_multi_cat"))
          {
%>	        <div class="warning"><%=L("lcl_res_allow_multi_cat")%></div><%
          }
          else
          {
            var discArr = [];
            while (!oRs.eof)
            {
              var curr_disc_key = oRs("ins_discipline_key").value;
              var existing = false; // zodadelijk highlighten
              // Bepaal aantal artikelen bij een reservering inclusief eventueel meegegeven artikel via res_artikel_key parameter
              if (rsv_ruimte_key > 0)
              { // Hoeveel gereserveerde artikelen zijn er voor deze reservering.
                sql = "SELECT COUNT(*) aantal"
                    + "  FROM res_rsv_artikel rra,"
                    + "       res_artikel ra"
                    + " WHERE rra.res_rsv_ruimte_key = " + rsv_ruimte_key
                    + "   AND res_rsv_artikel_verwijder IS NULL"
                    + "   AND rra.res_artikel_key = ra.res_artikel_key"
                    + "   AND res_discipline_key = " + curr_disc_key
                var oRs2 = Oracle.Execute(sql);
                var aantal = oRs2("aantal").value;
                oRs2.Close();
                if (res_artikel_key > 0)
                { // Zit het meegegeven artikel in deze discipline, dan 1 bij het aantal optellen.
                  sql = "SELECT COUNT(*) aantal"
                      + "  FROM res_artikel ra"
                      + " WHERE res_discipline_key = " + curr_disc_key
                      + "   AND ra.res_artikel_key = " + res_artikel_key;
                  var oRs2 = Oracle.Execute(sql);
                  aantal += oRs2("aantal").value;
                  oRs2.Close();
                }
                existing = (aantal > 0);
              }
%>
              <tr>
                <td>
<%                if (!has_kostenplaats_key && oRs("INS_DISCIPLINE_KPNVERPLICHT").value == 1)
                  {
                    var loading_txt = L("lcl_select_account_disc");
                    var makeCat = false;
%>
                    <div class="objcatline notavailable">
                      <%=safe.html(oRs("ins_discipline_omschrijving").Value)%>
<%                }
                  else if (oRs("res_disc_params_min_deelnmrs").Value > (res_bezoekers || 0) || oRs("res_disc_params_min_duur").Value > res_duur)
                  {
                    var loading_txt = L("lcl_select_account_disc1").format((oRs("res_disc_params_min_deelnmrs").Value || 0), oRs("res_disc_params_min_duur").Value);
                    var makeCat = false;
%>
                    <div class="objcatline notavailable">
                      <%=safe.html(oRs("ins_discipline_omschrijving").Value)%>
<%                }
                  else
                  {
                    var loading_txt = L("lcl_shared_loading");
                    var makeCat = true;
%>
                    <div class="objcatline <%=(existing?" existing ":" closed")%> "
                         id="objcatline<%=curr_disc_key%>"
                         onClick="ItemChoosed_cat(this, 'div_dis<%=curr_disc_key%>', <%=curr_disc_key%>)">
                      <a>
                        <%=I((existing ? "fa-minus-square" : "fa-plus-square") + " fa-lg")%>
                        <%=oRs("ins_discipline_image").Value ? I(oRs("ins_discipline_image").Value + " fa-lg") + "&nbsp;" : "&nbsp;" %>
                        <%=safe.html(oRs("ins_discipline_omschrijving").Value)%>
                      </a>
<%                }%>
                      <div class="objcatdiv" id="div_dis<%=curr_disc_key%>" onClick="FcltMgr.stopPropagation(event)">
                      <% // Hier wordt met Ajax res_load_cat.asp code tussen geplakt bij openklappen
                        if (oRs("inArrangement").Value == 1)
                          discArr.push(curr_disc_key);
                        if (existing && makeCat)
                        {
                          make_cat(curr_disc_key, rsv_ruimte_key, existing, res_artikel_key);
                        }
                        else
                          Response.Write("<span class='resobjtxt'><flex-marker>"+loading_txt+"</flex-marker></span>")
%>
                      </div>
                    </div>
                </td>
              </tr>
<%            oRs.MoveNext();
            }

            // get arrangement items
            var s_items={}; // serverside
%>
        <script>
<%
            if (discArr && discArr.length)
            {
              // initial get of all allowed arrangements and items
              var sql = "SELECT aa.res_arrangement_key, aa.res_artikel_key, ra.res_artikel_begintijd, ra.res_discipline_key "
                      + "  FROM res_arrangement_artikel aa, res_artikel ra "
                      + " WHERE aa.res_artikel_key = ra.res_artikel_key "
                      + "   AND ra.res_discipline_key IN (" + discArr.join(",") + ")"
                      + " ORDER BY res_arrangement_key, res_artikel_key";
              var oRs_arr = Oracle.Execute(sql);
              while (!oRs_arr.eof)
              {
                var arr_key = oRs_arr("res_arrangement_key").Value;
                var disc_key = oRs_arr("res_discipline_key").Value;
                if (!s_items[arr_key])
                  s_items[arr_key] = {};
                if (!s_items[arr_key][disc_key])
                  s_items[arr_key][disc_key] = {};
                s_items[arr_key][disc_key][oRs_arr("res_artikel_key").Value] = oRs_arr("res_artikel_begintijd").Value;
                oRs_arr.MoveNext();
              }
              oRs_arr.close();
            }
            Response.Write("var items = {0};".format(JSON.stringify(s_items)));
%>
        function loadAllCatering()
        {
            // Van geopende catering filter verbergen
            $("#resCatList .objcatline.existing").each(function()
            {
                disc_key = $(this)[0].id.substr(10);
                $("#autofilter-"+disc_key).css("display", "none");
                $("#table_dis"+disc_key).removeClass("compressed");
                var clickvooralles = $("#div_dis"+disc_key).find(".resplanbordlimited");
                $(clickvooralles).click();
            });
            // Alle nog niet geopende catering openen
            $("#resCatList .objcatline.closed").each(function()
            {
                disc_key = $(this)[0].id.substr(10); // "objcatline" eraf halen
                ItemChoosed_cat($("#objcatline" + disc_key)[0], "div_dis"+disc_key, disc_key, "&hidefilter=1");
            });
            //Voeg een globaal filter voor catering toe.
            $("#resCat").find("div .blockbuttoncontainer").prepend("<input id='autofilter-allcat' type='text' placeholder='filter...'>");
            // Verwijder knop "Open alles"
            $("#btn_open_allcat").css("display", "none");
            $("#autofilter-allcat").attr("style", "border-color: red; border: 2px;");
            setFilter();
        }

        function selectArrangement()
        {
          var subject = L("lcl_select_package");
          var url = "../res/res_select_arrangement.asp?tijd=<%=res_van.getHours()%>:<%=res_van.getMinutes()%>&discs=<%=discArr.join(",")%>";
          FcltMgr.openModalDetail(url, subject, {callback: addArrangementItems});
        }
    </script>
<%
          }
          BLOCK_END();
        }
        oRs.Close();
        // einde: Toon catering

        IFACE.FORM_END();
%>
      </form>
<% SUBFRAME_END(); %>
  </body>
</html>
<% ASPPAGE_END(); %>
