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

    File:        opdr_search.asp (formerly orders_search.asp;35, ComplainsReportAll.asp;72)
    Description:   Toont zoekvelden voor lijst van opdrachten
    Parameters:    {NADER UITWERKEN}
      urole        gebruikers rol (fe|fo|bo|mi) REQUIRED
      accept = 1   als ik MLDBO3 autorisatie heb, mag ik alleen accepteren
      close = 1    als ik MLDBO2 autorisatie heb, mag ik de melding alleen afsluiten
      mld_key      melding key van de melding
      cnt          aanroep vanuit een contract
      skey         x
      ckey         contract key
      pkey         melder (key)van de melding
      bes          x
      locatie_key  initiële locatie key
      gebouw_key   initiële gebouw key
    Context:       Vanuit portal, melding, of cnt_list, of..
    Note:          In principe kan voor elk veld een parameter worden gegeven (conventies hanteren!)
                   Note: Toevoegen gaat niet meer hier vandaan, dus er is heel wat verdwenen
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/calendar.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/plaatsselector.inc" -->
<!-- #include file="../Shared/uitvoerendeselector.inc" -->
<!-- #include file="../Shared/contactpersoonselector.inc" -->
<!-- #include file="../Shared/adresselector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/xd.inc" -->
<!-- #include file="mld.inc" -->

<%
// suggest en jQuery worden door persoonselector.inc, plaatsselector.inc en afdelingselector.inc al als plugin toegevoegd
// plaatsselector.js wordt door plaatsselector.inc als js script toegevoegt
FCLTHeader.Requires({ plugins:["jQuery", "kenmerk"],
                      js: ["../MLD/opdr_search.js"]
                    });

/***** Get webform parameters *****/
var urole = getQParamSafe("urole");

// FSN#674 Intention: backo may fully handle its orders (including Add), fronto has limited rights
var fronto = urole == "fo";
var backo = urole == "bo";
var minfo = urole == "mi"; // NOT APPLICABLE?
var bgtmode  = (urole == "bgt");
var frontend = (urole == "fe" || (!fronto && !backo && !minfo && !bgtmode));

// LET OP: voorheen keken we of MLDBO2 of MLDBO3 wellicht gold als MLDBOF
// niet geldig was. Nu doen we dat door parameters
var justClose  = (urole == "b2");

// PREFILL PARAMETERS:
var mld_key = getQParamInt("mld_key", -1);
var autosearch = getQParamInt("autosearch", 0);
var planbord = getQParamInt("planbord", 0) == 1;
var opdr_num = getQParam("opdr_key", -1); // unsafe
var cnt = (getQParamInt("cnt", 0) == 1);
var bes = (getQParamInt("bes", 0) == 1);
var offerte = getQParamInt("offerte", -1); // Opdrachttype is een offerteaanvraag. Kan -1:don't care, 0:niet, 1:wel zijn.
var cnt_key = getQParamInt("ckey", -1);
var pkey = (frontend ? user_key : -1);
var handleropdr_key = getQParamInt("behandel_key", -1); // Opdracht Behandelaar
var beh_key_arr = getQParamIntArray("beh_key_arr", []); // Opdracht Behandelaars (planbord=1)
var locatie_key = getQParamInt("locatie_key", -1);
var gebouw_key = getQParamInt("gebouw_key", -1);
var opdrtype_key = getQParamInt("opdrtype_key", -1);
var startdate_from = getQParamDate("startdate_from", null);
var startdate_to = getQParamDate("startdate_to", null);
var enddate_from = getQParamDate("enddate_from", null);
var enddate_to = getQParamDate("enddate_to", null);
var plandate_from = getQParamDate("plandate_from", null);
var plandate_to = getQParamDate("plandate_to", null);
var contactpersoon_key = getQParamInt("contactpersoon_key", -1);
var handler_key = getQParamInt("handler_key", -1); // Uitvoerende
var uitv_type = getQParam("uitv_type", (planbord? "I" : "IE")); // Uitvoerende type (I(ntern) en/of E(xtern)).
var FreezeHandler = getQParamInt("fh", -1) ==  1; // FreezeHandler
var searchtekst = getQParam("searchtekst", ""); // Zoektekst
var verantw_key = getQParamInt("verantw", -1); // Gebouw verantwoordelijke

// Voor het praktisch toepassen moet er ook een handler zijn voor initKey
FreezeHandler = FreezeHandler && (handler_key != -1 || (frontend && !justClose));

var alg_startlevel = getQParamInt("alg_startlevel", (bes? 3 : 2)); // Startlevel van plaatsselector (Regio/Locatie). Standaard is locatie (2) of gebouw (3)
var srtdisc_key_arr = getQParamIntArray("srtdisc_key_str", []); // Soort melding
var disc_key_arr = getQParamIntArray("disc_key_str", []); // Productgroep
var meldinggrp_key = getQParamInt("meldinggrp_key", -1); // Meldinggroep
var behandelgrp_key = getQParamInt("behandelgrp_key", -1); // Behandelgroep
var stdm_arr = getQParamIntArray("stdm_str", []); // Melding (Stdmelding)
var bosort = getQParamInt("bosort", S("mld_ord_bo_sort_descending"));

var alg_eindlevel = getQParamInt("alg_eindlevel", 3); // eindlevel tbv plaatsselector. Standaard Gebouw

if (stdm_arr.length != 0 && disc_key_arr.length == 0 && srtdisc_key_arr.length == 0)
{
  sql = "SELECT mld_ins_discipline_key"
      + ", ins_srtdiscipline_key"
      + " FROM mld_stdmelding s"
      + ", mld_discipline m"
      + " WHERE s.mld_ins_discipline_key = m.ins_discipline_key"
      + " AND mld_stdmelding_key IN (" + stdm_arr.join(",") + ")";
  oRs = Oracle.Execute(sql);
  if (!oRs.eof)
  {
    disc_key_arr = [oRs("mld_ins_discipline_key").value];
    srtdisc_key_arr = [oRs("ins_srtdiscipline_key").value];
  }
}

if (opdrtype_key > 0)
    lcl.set_dialect(opdrtype_key, "MLD_TYPEOPDR_KEY");

/***** End get webform parameters *****/

// So what authorization must we check?
var autfunction = {fe: "WEB_MLDORD", bo: "WEB_ORDBOF", b2: ["WEB_EXTORD","WEB_ORDBO2"], bgt: "WEB_BGTORD"}[urole];
var sql_autfunction = (typeof autfunction == "object" && autfunction instanceof Array? safe.quoted_sql_join(autfunction) : safe.quoted_sql(autfunction));

//@@@ Er stond in 4.81 ook nog:   if (func_enabled[cnt? "WEB_CNTMAN" : autfunction]) ...
// MGE: Je hebt dus WEB_CNTMAN rechten nodig als je wordt aangeroepen vanuit contracten => Ook even checken of je die wel hebt
if (cnt)
  var authparams = user.checkAutorisation("WEB_CNTUSE"); // Stelling: Als je WEB_CNTMAN rechten hebt moet je ook dezelfde WEB_CNTUSE rechten hebben/krijgen.
var authparams = user.checkAutorisation(autfunction);

var authparamsORDBO2 = user.checkAutorisation("WEB_ORDBO2", true);

// Fast check to see if we have anything to do with geographics
var min_plaats = -1;
sql= "SELECT MIN (ins_srtdiscipline_alg) min_plaats FROM ins_srtdiscipline WHERE ins_srtdiscipline_alg > 0 AND ins_srtdiscipline_verwijder IS NULL";
oRs = Oracle.Execute(sql);
min_plaats = oRs("min_plaats").Value;
oRs.close();

// Fast check to see if we have anything to do with call groups
sql= "SELECT 1 FROM mld_stdmeldinggroep WHERE ROWNUM = 1";
oRs = Oracle.Execute(sql);
var anymldgroup = !oRs.eof;
oRs.close();

// Fast check to see if we have any delivery adresses
sql= "SELECT 1 FROM mld_adres WHERE mld_adres_verwijder IS NULL AND mld_adres_afleveradres IS NOT NULL AND ROWNUM = 1";
oRs = Oracle.Execute(sql);
var anydeladr = !oRs.eof;
oRs.close();

%>

<html>
  <head>
    <% FCLTHeader.Generate(); %>

    <script type="text/javascript">
      var timeoutHandle;

      function doSubmit(mode) // 0=lijst, 1=planbord
      {
<%      if (xd.enabled())
        { %>
          if ($("#xd").is(":checked"))
          {
                $("form[name=u2]").attr("action", "opdr_search_list_xd.asp");
          } else {
                $("form[name=u2]").attr("action", "opdr_search_list.asp");
          }
<%      } %>
        $("#planb").val(mode);
        doSubmitWithKenmerken();
<%      if (autosearch >= 300)
        { %>
        // Autorefresh the dashboard when autosearch >= 300 and after first user-submit
          if (timeoutHandle) {
            window.clearTimeout(timeoutHandle);
          }
          timeoutHandle = window.setTimeout(function() {
            doSubmit(mode);
          }, <%=autosearch%> * 1000);
<%      } %>
      }
<%    if (xd.enabled())
      { %>
        function xdclicked()
        {
          var doxd = document.getElementById("xd").checked;
          $(".noxd").toggle(!doxd);
          $(".onlyxd").toggleClass('hidden', !doxd);
          iface_toggleSecondarySearchblock(false); // altijd uitschakelen
        }
<%    } %>
      async function myModal(init)
        {
          var key = $('#opdrtype').val();
          var url = "load_kenmerk.asp?opdr_type=" + $('#opdrtype').val()
                  + "&urole=<%=urole%>"
                  + "&advanced=1"
                  + "&hasFilter=1"
                  + "&niveau=O";
          var titel = L("lcl_mld_ord_kenmerken");
          await showKenmerkModal(url, titel, init)
        }
<%
      if (autosearch)
      {
%>      window.afterfiltersready = function () { doSubmit(0) };
<%    } %>
    </script>
  </head>

  <body id="searchbody">
    <form action="opdr_search_list.asp" method="get" name="u2" target="workFrame">
<%    SEARCH_PAGE_START({ header: L("lcl_filterblok") });
        SEARCH_BLOCK_START();%>
        <input type="hidden" name="urole" value="<%=urole%>">
        <input type="hidden" name="user_key" value="<%=user_key%>">
        <input type="hidden" name="bes" value="<%=bes? 1 : 0%>">
        <input type="hidden" name="offerte" id="offerte" value="<%=offerte%>">
        <input type="hidden" name="planb" id="planb" value="0">
<%
            if (xd.enabled())
                RWCHECKBOXTR("xd", "fldxd", L("lcl_xd_crossdomain"), false, {html: "onclick='xdclicked()'"});
%>
            <tr class="primsearch">
              <!-- Opdrachtnummer -->
              <td class="label"><label for="opdr_key"><%=L("lcl_mld_order_nr")%></label></td>
              <td>
                <input type="text" class="fldshort" name="opdr_key" <%=(opdr_num != -1) ? "value='" + safe.htmlattr(opdr_num) + "'" : ""%>>
              </td>
            </tr>

<%          var sql = "SELECT mld_opdr_key"
                    + "  FROM mld_opdr o"
                    + " WHERE mld_opdr_id IS NOT NULL"
                    + " AND ROWNUM = 1";
            var oRs = Oracle.Execute(sql);
            var has_opdr_id = !oRs.EOF;
            oRs.Close();
            if (has_opdr_id)
            {
%>
            <tr class="primsearch">
              <!-- Opdrachtnummer -->
              <td class="label"><label for="opdr_id"><%=L("lcl_opdr_id")%></label></td>
              <td>
                <input type="text" class="fldshort" name="opdr_id">
              </td>
            </tr>
<%
            }

            if (cnt)
            { // <!-- Extern nummer -->
                sql = "SELECT c.cnt_contract_key"
                    + ", c.cnt_contract_nummer || ' - ' || b.prs_bedrijf_naam"
                    + " FROM cnt_v_aanwezigcontract c"
                    + ", prs_v_aanwezigbedrijf b"
                    + " WHERE c.cnt_prs_bedrijf_key = b.prs_bedrijf_key"
                    + "    AND c.cnt_contract_status IN (0, 1)"
                    + " ORDER BY 2";

                FCLTselector("contract",
                             sql,
                             { initKey: cnt_key,
                               label: L("lcl_cnt_contractnr"),
                               emptyOption: "",
                               trclass:"primsearch noxd",
                               initEmpty: true, // Altijd lege waarde tonen, ook als er maar 1 waarde is.
                               readonly: (cnt_key > 0)
                             })
%>
              <!-- Contractnummer -->
              <tr class="primsearch noxd">
                <td class="label"><label for="cntnr"><%=L("lcl_cnt_intern_nr")%></label></td>
                <td>
                  <input type="text" class="fldshort<%=cnt_key > 0? " readonly" : ""%>" name="cntnr" <%=cnt_key != -1? 'value="' + cnt_key + '"':''%> <%=cnt_key > 0? "readonly" : ""%>>
                </td>
              </tr>
<%          } // cnt
%>
            <!-- Zoektekst -->
            <tr class="primsearch">
              <td class="label"><label for="searchtekst"><%=L("lcl_search_diff_fields")%></label></td>
              <td>
                <input type="text" class="fld wildcard" name="searchtekst" value="<%=safe.htmlattr(searchtekst)%>">
              </td>
            </tr>
<%
            // <!-- Opdrachttype -->
%>
                <tr class="primsearch onlyxd hidden">
                  <td class="label"><label for="ordertypetekst"><%=L("lcl_mld_typeopdr")%></label></td>
                  <td>
                    <input type="text" class="fld wildcard" name="ordertypetekst" value="">
                  </td>
                </tr>

<%
           if (opdrtype_key == -1)
           {
             sql = "SELECT t.mld_typeopdr_key"
                  + ",   "+ lcl.xsqla('t.mld_typeopdr_omschrijving', 't.mld_typeopdr_key')
                  + "  FROM mld_typeopdr t"
                  + (offerte >= 0
                    ? " WHERE t.mld_typeopdr_isofferte = " + offerte
                    : "")
                  + " ORDER BY 2";

              var sqlcnt = "SELECT COUNT ( * ) nropdrtype"
                         + "  FROM ("  + sql + ")";

              var oRs2 = Oracle.Execute(sqlcnt);
              if (oRs2("nropdrtype").Value == 1)
              {
                var oRs = Oracle.Execute(sql);
                opdrtype_key = oRs("mld_typeopdr_key").Value;
                oRs.close();
              }
              oRs2.close();

              if (opdrtype_key == -1)
              {
                FCLTselector("opdrtype",
                             sql,
                             { initKey: opdrtype_key,
                               label: L("lcl_mld_typeopdr"),
                               trclass:"primsearch noxd",
                               emptyOption: ""
                             });
              }
           }

          if (opdrtype_key > -1)
          {
            %><input type='hidden' id='opdrtype' name='opdrtype' value='<%=opdrtype_key%>'><%
          }

            // <!-- Uitvoerende -->
            // Ben ik toevallig een contactpersoon van een extern bedrijf? Dan mag ik automatisch
            // alleen de opdrachten van mijn bedrijf/bedrijven zien (AADS#)
            var exhandler = false;
            if (justClose && !authparamsORDBO2)
              exhandler = user.iamContact();

            if (FreezeHandler)
            { // Uitvoerende is vast
                %><input name="handler" id="handler" type="hidden" value="<%=(handler_key != -1 ? handler_key : user_key)%>"><%
            } else {
%>
                <tr class="primsearch onlyxd hidden">
                  <td class="label"><label for="suppliertekst"><%=L("lcl_handler")%></label></td>
                  <td>
                    <input type="text" class="fld wildcard" name="suppliertekst" value="">
                  </td>
                </tr>

<%              FCLTuitvoerendeselector("handler",
                                       "sgUitv",
                                       { uitvoerendekey: handler_key,
                                         label: L("lcl_handler"),
                                         trclass:"primsearch noxd",
                                         autlevel: authparams.PRSreadlevel,
                                         whenEmpty: L("lcl_search_generic"),  // want filter
                                         filtercode: "M",
                                         lutype: "B",   // Eeh, filtercode en lutype hebben toch alles met elkaar te maken, lutype wegwerken?
                                         exhandler: exhandler
                                       });

          // <!-- Contactpersoon -->
          FCLTcontactpersoonselector("contactpers",
                                    "sgCntPersUitv",
                                    { contactpersoonKey: contactpersoon_key,
                                      label: L("lcl_mld_contactpersoon"),
                                      trclass: "secsearch noxd",
                                      filtercode: "U",
                                      urlAdd: [{urlParam: "uitv_key", field: "handler"}],
                                      autlevel: authparams.PRSreadlevel,
                                      whenEmpty: L("lcl_search_generic")  // want filter
                                    });

            // Als een srtdisc_key meegegeven dan geen lege optie
            sql = "SELECT DISTINCT sd.ins_srtdiscipline_key"
                + "     , " + lcl.xsqla('sd.ins_srtdiscipline_omschrijving', 'sd.ins_srtdiscipline_key')
                + "  FROM ins_srtdiscipline sd"
                + (offerte >= 0
                  ? "       , mld_typeopdr_srtdiscipline tsd"
                    + "     , mld_typeopdr mto"
                    + " WHERE sd.ins_srtdiscipline_key = tsd.ins_srtdiscipline_key"
                    + "   AND tsd.mld_typeopdr_key = mto.mld_typeopdr_key"
                    + "   AND mto.mld_typeopdr_isofferte = " + offerte
                  : " WHERE 1 = 1")
                + "   AND EXISTS (SELECT 'x'"
                  + "               FROM mld_stdmelding ms"
                  + "                  , mld_v_aanwezigdiscipline m1"
                  + "              WHERE m1.ins_discipline_key = ms.mld_ins_discipline_key"
                  + "                AND ms.mld_stdmelding_verwijder IS NULL)"
                + "   AND EXISTS (SELECT 'y'"
                  + "               FROM fac_v_my_disciplines md"
                  + "                  , mld_v_aanwezigdiscipline m1"
                  + "              WHERE fac_functie_code IN (" + sql_autfunction + ")"
                  + "                AND prs_perslid_key = " + user_key
                  + "                AND m1.ins_srtdiscipline_key = sd.ins_srtdiscipline_key"
                  + "                AND md.ins_discipline_key = m1.ins_discipline_key"
                  + ")"
                + (srtdisc_key_arr.length != 0
                  ? " AND ins_srtdiscipline_key IN(" + srtdisc_key_arr.join(",") + ") "
                  : " ")
                + " ORDER BY 2"
            FCLTselector("srtdiscmulti",
                         sql,
                         { initKey: srtdisc_key_arr.join(","),
                           label: L("lcl_vakgroup_type"),
                           trclass: "secsearch noxd",
                           onChange: 'updateDisc("' + urole + '", "' + (typeof autfunction == "object" && autfunction instanceof Array? autfunction.join(",") : autfunction) + '");',
                           multi: true,
                           emptyOption: (srtdisc_key_arr.length == 0? L("lcl_search_generic") : null) // Als een srtdisc_key is meegegeven dan geen lege optie
                         }) %>

            <!-- Productgroep -->
<%          // LET OP!!
            // De options van deze selector wordt on-change dynamisch vervangen door ../shared/loadDisc.asp!
            // Wat hier staat is dus alleen de initiele situatue.
            // SQL-queries uit loadDisc:
            var discsql_aut = "SELECT ins_discipline_key"
                        + "  FROM fac_v_webgebruiker g"
                        + ", fac_functie f"
                        + " WHERE g.prs_perslid_key = " + user_key
                        + " AND f.fac_functie_key = g.fac_functie_key"
                        + " AND f.fac_functie_code IN (" + sql_autfunction + ")"
                        + " AND g.fac_gebruiker_alg_level_read < 9"; // MGE: Als alg_level_read = 9 dan komt waarde niet meer voor in fac_v_webgebruiker. Regel zou dus weg kunnen

            var discsql = "SELECT DISTINCT m1.ins_discipline_key"
                    + ", CASE "
                      + " WHEN sd.ins_srtdiscipline_prefix IS NULL"
                      + " THEN ''"
                      + " ELSE sd.ins_srtdiscipline_prefix || '-'"
                      + " END"
                      + " || "+lcl.xsqla('m1.ins_discipline_omschrijving', 'm1.ins_discipline_key')
                    + " FROM mld_v_aanwezigdiscipline m1"
                    + ", ins_srtdiscipline sd"
                    + ", mld_disc_params dp"
                    + (offerte >= 0
                      ? "   , mld_typeopdr_srtdiscipline tsd"
                        + " , mld_typeopdr mto"
                      : "")
                    + " WHERE m1.ins_srtdiscipline_key = sd.ins_srtdiscipline_key(+)"
                    + "   AND dp.mld_ins_discipline_key = m1.ins_discipline_key"
                    + "   AND BITAND(dp.mld_disc_params_srtgroep, 1) = 1" // Alleen primaire
                    + (offerte >= 0
                      ? " AND sd.ins_srtdiscipline_key = tsd.ins_srtdiscipline_key"
                        + " AND tsd.mld_typeopdr_key = mto.mld_typeopdr_key"
                        + " AND (tsd.ins_discipline_key IS NULL OR tsd.ins_discipline_key = m1.ins_discipline_key)"
                        + " AND mto.mld_typeopdr_isofferte = " + offerte
                      : "")
                    + " AND EXISTS (SELECT 'x'"
                      + " FROM mld_stdmelding ms"
                      + " WHERE m1.ins_discipline_key = ms.mld_ins_discipline_key"
                      + " AND ms.mld_stdmelding_verwijder IS NULL)"
                    + " AND m1.ins_discipline_key IN (" + discsql_aut + ")"
                    + (srtdisc_key_arr.length != 0
                      ? " AND m1.ins_discipline_key IN (SELECT ins_discipline_key"
                        + " FROM mld_discipline"
                        + " WHERE ins_srtdiscipline_key IN (" + srtdisc_key_arr.join(",") + "))"
                      : "")
                    + (disc_key_arr.length != 0
                      ? " AND m1.ins_discipline_key IN (" + disc_key_arr.join(",") + ")"
                      : "")
                    + " ORDER BY 2"

            FCLTselector("discmulti",
                         discsql,
                         { initKey: disc_key_arr.join(","),
                           label: L("lcl_vakgroup"),
                           onChange: 'updateStdm("' + urole + '", "' + (typeof autfunction == "object" && autfunction instanceof Array? autfunction.join(",") : autfunction) + '");',
                           trclass: "secsearch noxd",
                           multi: true,
                           emptyOption: (disc_key_arr.length == 0? L("lcl_search_generic") : null) // Als een disc_key_arr is meegegeven dan geen lege optie
                         }) %>

            <!-- Melding (Stdmelding) -->
<%          // LET OP!!
            // deze selector wordt on-change dynamisch en totaal vervangen door ../Shared/loadStdmelding.asp!
            // Wat hier staat is dus alleen de initiele situatie.
            // SQL-queries uit loadStdmelding:
            var stdmsql_aut = "SELECT ins_discipline_key"
                            + "  FROM fac_v_webgebruiker g"
                            + ", fac_functie f"
                            + " WHERE g.prs_perslid_key = " + user_key
                            + " AND f.fac_functie_key = g.fac_functie_key"
                            + " AND f.fac_functie_code IN (" + sql_autfunction + ")"
                            + " AND g.fac_gebruiker_alg_level_read < 9"; // MGE: Als alg_level_read = 9 dan komt waarde niet meer voor in fac_v_webgebruiker. Regel zou dus weg kunnen

            var stdmsql = "SELECT DISTINCT s.mld_stdmelding_key"
                        + ", " + lcl.xsqla('s.mld_stdmelding_omschrijving','s.mld_stdmelding_key')
                        + ", s.mld_ins_discipline_key"
                        + " FROM mld_stdmelding s"
                        + ", mld_discipline d"
                        + (offerte >= 0
                          ? ", ins_srtdiscipline sd"
                            + ", mld_typeopdr_srtdiscipline tsd"
                            + ", mld_typeopdr mto"
                          : "")
                        + " WHERE s.mld_ins_discipline_key = d.ins_discipline_key"
                        + (offerte >= 0
                          ? " AND d.ins_srtdiscipline_key = sd.ins_srtdiscipline_key"
                            + " AND sd.ins_srtdiscipline_key = tsd.ins_srtdiscipline_key"
                            + " AND (tsd.ins_discipline_key IS NULL OR tsd.ins_discipline_key = d.ins_discipline_key)"
                            + " AND tsd.mld_typeopdr_key = mto.mld_typeopdr_key"
                            + " AND mto.mld_typeopdr_isofferte = " + offerte
                          : "")
                        + " AND s.mld_stdmelding_verwijder IS NULL"
                        + " AND d.ins_discipline_verwijder IS NULL"
                        + (fronto || backo
                          ? ""
                          : " AND s.mld_stdmelding_notfrontend = 0")
                        // srtdisc_key wordt impliciet afgedwongen via afhankelijkheid
                        + (disc_key_arr.length != 0
                          ? " AND s.mld_ins_discipline_key IN (" + disc_key_arr.join(",") + ")"
                          : "")
                        + " AND s.mld_ins_discipline_key IN (" + stdmsql_aut + ")"
                        + " ORDER BY "+ lcl.xsql('s.mld_stdmelding_omschrijving','s.mld_stdmelding_key');

            FCLTselector("sm", // heette stdmmulti maar nu korte naam om url kort te houden
                         stdmsql,
                         { initKey: stdm_arr.join(","),
                           label: L("lcl_complain"),
                           trclass: "secsearch noxd",
                           multi: true,
                           emptyOption: L("lcl_search_generic")
                         });

            // Meldinggroep
            // Laat alle meldinggroepen zien die voorkomen onder de disciplines die ik mag zien.
            var grpsql_aut = "SELECT ins_discipline_key"
                           + "  FROM fac_v_webgebruiker g"
                           + ", fac_functie f"
                           + " WHERE g.prs_perslid_key = " + user_key
                           + " AND f.fac_functie_key = g.fac_functie_key"
                           + " AND f.fac_functie_code IN (" + sql_autfunction + ")"
                           + " AND g.fac_gebruiker_alg_level_read < 9"; // MGE: Als alg_level_read = 9 dan komt waarde niet meer voor in fac_v_webgebruiker. Regel zou dus weg kunnen

            var grpsql = "SELECT G.mld_stdmeldinggroep_key akey"
                       + ", " + lcl.xsqla('G.mld_stdmeldinggroep_naam','G.mld_stdmeldinggroep_key')
                       + " FROM mld_stdmelding M"
                       + "    , mld_stdmeldinggroep G"
                       + " WHERE M.mld_stdmeldinggroep_key = G.mld_stdmeldinggroep_key"
                       + "   AND M.mld_stdmelding_verwijder IS NULL"
                       + " AND M.mld_stdmeldinggroep_key IS NOT NULL"
                       + (srtdisc_key_arr.length != 0
                         ? " AND mld_ins_discipline_key IN (SELECT ins_discipline_key"
                           + " FROM mld_discipline"
                           + " WHERE ins_srtdiscipline_key IN (" + srtdisc_key_arr.join(",") + "))"
                         : "")
                       + (disc_key_arr.length != 0
                         ? " AND mld_ins_discipline_key IN (" + disc_key_arr.join(",") + ")"
                         : "")
                       + " AND mld_ins_discipline_key IN (" + grpsql_aut + ")"
                       + " GROUP BY G.mld_stdmeldinggroep_key, mld_stdmeldinggroep_naam"
                       + " ORDER BY 2";

            if (anymldgroup)
            {
            FCLTselector("meldinggrp_key",
                          grpsql,
                          { initKey: meldinggrp_key,
                            label: L("lcl_mld_meldinggroep"),
                            trclass: "secsearch noxd",
                            emptyOption: ""
                          });
            }

            // Behandelgroep-filter (indien die er zijn)
            var behsql = "SELECT mld_behandelgroep_key,"
                       + lcl.xsqla('mld_behandelgroep_naam', 'mld_behandelgroep_key')+", "
                       + lcl.xsqla('mld_behandelgroep_oms', 'mld_behandelgroep_key')
                       + "  FROM mld_behandelgroep";
            oRs = Oracle.Execute(behsql);
            if (!oRs.eof)
            {
                FCLTselector("behandelgrp_key",
                              behsql,
                              { initKey: behandelgrp_key,
                                label: L("lcl_mld_behandelgroep"),
                                trclass: "secsearch noxd",
                                emptyOption: ""
                              });
            }

            // prioriteit
            sql = "SELECT -1, '' FROM DUAL UNION "
                + "SELECT 1, " + safe.qL("lcl_mld_urg_kritiek") + " FROM DUAL UNION "
                + "SELECT 2, " + safe.qL("lcl_mld_urg_hoog")    + " FROM DUAL UNION "
                + "SELECT 3, " + safe.qL("lcl_mld_urg_normaal") + " FROM DUAL UNION "
                + "SELECT 4, " + safe.qL("lcl_mld_urg_laag")    + " FROM DUAL";
            FCLTselector("priority",
                         sql,
                         { initKey: -1,
                           label: L("lcl_mld_urg"),
                           trclass: "secsearch noxd",
                           multi: true
                         });

            if (backo || justClose)
            {
              var sortsql = "SELECT 0, " + safe.qL("lcl_mld_firstready")    + ", 0 FROM DUAL UNION "
                          + "SELECT 1, " + safe.qL("lcl_mld_newfirst")      + ", 1 FROM DUAL UNION "
                          + "SELECT 2, " + safe.qL("lcl_mld_laatste_actie") + ", 2 FROM DUAL "
                          + "ORDER BY 3";
              FCLTselector("bosort",
                            sortsql,
                            { initKey: bosort,
                              label: L("lcl_mld_sort"),
                              trclass: "secsearch noxd"
                            });
            }

            // Opdracht bedrag
            RWFIELDTR("bedragboven",
                      "fldshort",
                      L("lcl_opdr_bedrag_boven") + " " + S("currency_pref"),
                      "",
                      { datatype: "currency",
                        trclass: "secsearch",
                        maxlength: 9,
                        html: 'onBlur="checkbedragboven()"'
                      });
            RWFIELDTR("bedragonder",
                      "fldshort",
                      L("lcl_opdr_bedrag_onder") + " " + S("currency_pref"),
                      "",
                      { datatype: "currency",
                        trclass: "secsearch",
                        maxlength: 9,
                        html: 'onBlur="checkbedragonder()"'
                      });

                sql = "SELECT 'x'"
                    + " FROM prs_bedrijf"
                    + " WHERE     prs_bedrijf_verwijder IS NULL"
                    + "       AND prs_bedrijf_uitvoerende = 1"
                    + "       AND prs_bedrijf_intern = 1"
                    + "       AND ROWNUM = 1 ";
                oRs = Oracle.Execute(sql);
                var anyInternalHandler = !oRs.eof;
                oRs.close();
                if (!anyInternalHandler) {
                  sql = "SELECT 'x'"
                      + "  FROM mld_opdr o, prs_perslid p"
                      + " WHERE p.prs_perslid_key = o.mld_uitvoerende_keys";
                  oRs = Oracle.Execute(sql);
                  anyInternalHandler = !oRs.eof;
                  oRs.close();
                }
                if (anyInternalHandler)
                { %>
                  <tr>
                    <td></td>
                    <td>
                      <div id="ieuitboxes">
                          <input type="hidden" name="has_opdrXUit" value="1">
                          <input type="checkbox" name="opdrIUit" id="opdrIUit" onClick="checkieuitv();" value="1" <%=uitv_type == "IE" || uitv_type == "I"? "CHECKED" : ""%>><label for="opdrIUit"><%=L("lcl_opdr_internuit")%></label>
                          <input type="checkbox" name="opdrEUit" id="opdrEUit" onClick="checkieuitv();" value="1" <%=uitv_type == "IE" || uitv_type == "E"? "CHECKED" : ""%>><label for="opdrEUit"><%=L("lcl_opdr_externuit")%></label>
                      </div>
                    </td>
                  </tr>
<%              }
            }
            if ((!justClose || S("mld_performer_can_change_flags")) && S("mld_opdracht_flags") > 1 && (!frontend || S("mld_performer_can_change_flags"))) // Flags checkboxen -->
            {
                for (flagkey=0; flagkey < S("mld_opdracht_flags"); flagkey++)
                {
                    var label = "<label for='flag" + flagkey + "'>"
                              + "  <span class='opdrflag" + flagkey + " opdrs'>"
                              +      I("fa-fclt-flag" + (flagkey == 0 ? "0" : ""))
                              + "  </span> " + safe.html(L("lcl_opdr_flag" + flagkey))
                              + "</label>";
                    RWCHECKBOXTR("flag" + flagkey, "fldcheck", (flagkey == 0 ? L("lcl_opdr_flags") : ""), 1, { twocols: true, posthtml: label });
                }
            }

            if (S("mld_opdr_actiecode") > 0) {
                if (exhandler) { // Ben ik externe uitvoerder? Dan wil ik op 'Actie bij uitvoerder' kunnen filteren, dat kan door onderstaande uit te vinken
                    RWCHECKBOXTR("actiecodeBO", "fldcheck", "", 1,   { trclass: "primsearch noxd", twocols: true, posthtml: "<label for='actiecodeBO'> " + I("fa-user-cog", { fastyle: "fas" }) + " " + L("lcl_opdr_actiecodeBOchk") + "</label>" });
                } else {
                    RWCHECKBOXTR("actiecodeUITV", "fldcheck", "", 1,   { trclass: "primsearch noxd", twocols: true, posthtml: "<label for='actiecodeUITV'> " + I("fa-comment-smile fa-flip-horizontal") + " " + L("lcl_mld_actiecodeUITVchk") + "</label>" });
                }
            }
            // Ik wil (altijd) kunnen filteren op Attentie (bij mij)
            RWCHECKBOXTR("actiecodeATT", "fldcheck", "", 0, { trclass: "primsearch noxd", twocols: true, posthtml: "<label for='actiecodeATT'> " + I("fa-bell", { fastyle: "fas" }) + " " + L("lcl_mld_actiecodeATTchk") + "</label>" });

        SEARCH_BLOCK_END();
        SEARCH_BLOCK_START();

          // <!-- Soort melding -->
            // <!-- Begindatum van -->
            FCLTcalendar("startdate_from",
                         { label: L("lcl_start_date_from"),
                           trclass: "primsearch",
                           initEmpty: (startdate_from ? false : true),
                           date: startdate_from
                         });

            // <!-- Begindatum t/m -->
            FCLTcalendar("startdate_to",
                         { label: L("lcl_start_date_to"),
                           trclass: "secsearch",
                           initEmpty: (startdate_to ? false : true),
                           date: startdate_to
                         });

            // <!-- Einddatum van -->
            FCLTcalendar("enddate_from",
                         { label: L("lcl_end_date_from"),
                           trclass: "secsearch",
                           initEmpty: (enddate_from ? false : true),
                           date: enddate_from
                         });

            // <!-- Einddatum t/m -->
            FCLTcalendar("enddate_to",
                         { label: L("lcl_end_date_to"),
                           trclass: "primsearch",
                           initEmpty: (enddate_to ? false : true),
                           date:enddate_to
                         });

            // <!-- Plandatum van -->
            FCLTcalendar("plandate_from",
                         { label: L("lcl_plan_date_from"),
                           trclass: "secsearch",
                           initEmpty: (plandate_from ? false : true),
                           date: plandate_from
                         });

            // <!-- Plandatum t/m -->
            FCLTcalendar("plandate_to",
                         { label: L("lcl_plan_date_to"),
                           trclass: "secsearch",
                           initEmpty: (plandate_to ? false : true),
                           date: plandate_to
                         });

            // <!-- Behandelaar Opdracht -->
            if (planbord)
            {
              var filtClause = getFiltClausePersoon(justClose && exhandler? "BEHOC" : "BEHO", {planbord: true, justClose: justClose});

              // Dan alleen die personen tonen die vallen onder de afdelingen die behoren bij de kostenplaatsen waarvoor ik gemandateerd ben
              if (authparams.PRSreadlevel == 0) // Bedrijf niveau zit niet in prs_v_afdeling_familie
              {
                filtClause += " AND p.prs_afdeling_key IN"
                            + "    (SELECT a.prs_afdeling_key FROM prs_v_afdeling a"
                            + "      WHERE a.prs_bedrijf_key = " + user.afdeling().prs_bedrijf_key() + " )";
              }

              // PRS autorisatie
              if (authparams.PRSreadlevel > 0) // Efficiente versie van FAC_V_MY_PRS_AFDELINGEN_WRITE
              {
                filtClause +=" AND p.prs_afdeling_key IN "
                           + "    (SELECT prs_afdeling_key FROM prs_v_afdeling_familie a"
                           + "      WHERE a.prs_afdeling_elder_key IN"
                           + "        (SELECT aa.prs_afdeling_elder_key"
                           + "           FROM prs_v_afdeling_familie aa"
                           + "          WHERE aa.prs_afdeling_key = " + user.prs_afdeling_key()
                           + "            AND aa.niveau = " + authparams.PRSreadlevel + "))";
              }

              prssql = "SELECT prs_perslid_key"
                     + "     , " + S("prs_pers_string") + " naam"
                     + " FROM prs_perslid p"
                     + ", prs_v_afdeling d"
                     + " WHERE p.prs_afdeling_key = d.prs_afdeling_key"
                     + "   AND (prs_perslid_oslogin IS NULL OR prs_perslid_oslogin NOT LIKE '\\_%' ESCAPE '\\')"
                     + "   AND BITAND(prs_perslid_flags, 2) = 0"
                     + "   AND prs_perslid_verwijder IS NULL"
                     + filtClause
                     + " ORDER BY 2";

              FCLTselector("opdrbehmulti",
                           prssql,
                           { initKey: beh_key_arr.join(","),
                             label: L("lcl_mld_behandelaar"),
                             trclass: "primsearch noxd",
                             multi: true,
                             emptyOption: (beh_key_arr.length == 0? L("lcl_search_generic") : null) // Als een beh_key_arr is meegegeven dan geen lege optie.
                           });
            }
            else
              FCLTpersoonselector("uitvopdr_key",
                                  "sgPersonOpdr",
                                  { perslidKey: handleropdr_key,
                                    label: L("lcl_mld_behandelaar"),
                                    filtercode: justClose && exhandler? "BEHOC" : "BEHO",
                                    trclass: "primsearch noxd", /* als wel xd: _self zou leuk zijn */
                                    autlevel: authparams.PRSreadlevel,
                                    autlevelALG: authparams.ALGreadlevel,
                                    initEmpty: true, // Altijd lege waarde tonen, ook als er maar 1 waarde is.
                                    whenEmpty: L("lcl_search_generic")  // want filter
                                  });

            //  Melderfilter, niet voor externe contactpersonen (geeft alle melders bloot)
            if (!exhandler) {
                FCLTpersoonselector("sName_key",
                                    "sgPerson",
                                    { label: L("lcl_caller"), // L("lcl_name")
                                      filtercode: "O",
                                      trclass: "secsearch noxd",
                                      autlevel: authparams.PRSreadlevel,
                                      whenEmpty: L("lcl_search_generic")  // want filter
                                    });
            }

            if (min_plaats > 0)
            {
              switch(min_plaats)
              {
                case 7: alg_eindlevel = 2; break; // Locatie
                case 5: alg_eindlevel = 3; break; // Gebouw
                case 3: alg_eindlevel = (minfo?4:alg_eindlevel); break; // Voor minfo Verdieping, anders maximaal Gebouw.
                case 1: alg_eindlevel = (minfo?5:alg_eindlevel); break; // Voor minfo Ruimte, anders maximaal Gebouw.
              }
              FCLTplaatsselector(authparams.ALGreadlevel, { locatiekey: locatie_key,
                                                            gebouwkey: gebouw_key,
                                                            multitoggle: 3,
                                                            startlevel: alg_startlevel,
                                                            eindlevel: alg_eindlevel,
                                                            trclass: "noxd",
                                                            filtercode: (alg_eindlevel <= 2 ? "" : "FACMLD"),
                                                            whenEmpty: L("lcl_search_generic")  // want filter
                                                          });

              // Gebouw verantwoordelijke
              // Dit veld is alleen zichtbaar indien er minimaal één gebouwverantwoordelijke geconfigureerd is (suppressNoValues).
              FCLTpersoonselector("verantw",
                             "sgVerantw",
                              { perslidKey: verantw_key,
                                label: L("lcl_bld_ter_verantw"),
                                filtercode: "GTV", // Gebouw Verantwoordelijke
                                trclass: "primsearch noxd",
                                suppressNoValues: true,
                                whenEmpty: L("lcl_search_generic")  // want filter
                              });
            }

            if (anydeladr)
            {
              // Afleveradres
              FCLTadresselector("adr_key", "sgAdres",
                {
                label: L("lcl_delivery_address"), /* zelfde als lcl_bes_del_place */
                whenEmpty: L("lcl_search_generic"),
                filtercode: "A",
                trclass: "secsearch"
              }) ;
            }

        if (S("mld_plandate_in_list") == 1)
        {
%>
          <tr class="secsearch">
            <td></td>
            <td>
              <div id="plannedboxes">
                  <input type="hidden" name="has_opdrPlan" value="1">
                  <input type="checkbox" name="opdrPlanned" id="opdrPlanned" onClick="checkplanned();" value="1" CHECKED><label for="opdrPlanned"><%=L("lcl_opdr_planned")%></label>
                  <input type="checkbox" name="opdrUnplanned" id="opdrUnplanned" onClick="checkplanned();" value="1" CHECKED><label for="opdrUnplanned"><%=L("lcl_opdr_unplanned")%></label>
              </div>
            </td>
          </tr>
<%      }

SEARCH_BLOCK_END();
SEARCH_BLOCK_START({wide: true});%>
        </tr>

        <!-- Status checkboxen -->
<%
    // Alleen lastigvallen met Afgerond vinkje als *iemand* WEB_ORDAFR heeft en dat vinkje ooit heeft kunnen zetten.
    var sql = "SELECT 1"
            + "  FROM fac_v_webgebruiker fw, "
            + "       fac_functie ff"
            + " WHERE fw.fac_functie_key = ff.fac_functie_key"
            + "   AND fac_functie_code = 'WEB_ORDAFR'";
    var oRs = Oracle.Execute(sql);
    var anyORDAFR = !oRs.Eof;
    oRs.Close();
%>
        <tr>
          <td colspan="2">
            <div id="statusboxes">
              <label><%=L("lcl_opdr_statusfilters")%></label>
                <input type="checkbox" name="opdrNew" id="opdrNew" value="1"    CHECKED><label for="opdrNew" ><%=L("lcl_opdr_chk_bo_opdrNew")%></label>
                <input type="checkbox" name="opdrBusy" id="opdrBusy" value="1" CHECKED><label for="opdrBusy"><%=L("lcl_opdr_chk_bo_opdrBusy")%></label>
                <input type="checkbox" name="opdrRej" id="opdrRej" value="1" ><label for="opdrRej"><%=L("lcl_opdr_chk_bo_opdrRej")%></label>
                <input type="checkbox" name="opdrAfm" id="opdrAfm" value="1" ><label for="opdrAfm"><%=L("lcl_opdr_chk_bo_opdrAfm")%></label>
<% if (anyORDAFR) { %>
                <input type="checkbox" name="opdrAfr" id="opdrAfr" value="1" ><label for="opdrAfr"><%=L("lcl_opdr_chk_bo_opdrAfr")%></label>
<% } %>
                <input type="checkbox" name="opdrVer" id="opdrVer" value="1" ><label for="opdrVer"><%=L("lcl_opdr_chk_bo_opdrVer")%></label>
            </div>
          </td>
<%      SEARCH_BLOCK_END();
      var buttons = [];
      if (!planbord)
        buttons.push ( { title: L("lcl_overview_list"), action: "doSubmit(0);", importance: 1, icon: "fa-clipboard-list"} );
      else
        buttons.push ( { title: L("lcl_opdr_planboard"), action: "doSubmit(1);", xclass: "noxd", importance: 1, icon: "fa-chart-tree-map"} );
      if (!bgtmode)
      {
        buttons.push ( {title: L("lcl_shared_more"),  action:"iface_toggleSecondarySearchblock()", id : "btnMoreLess", xclass: "noxd", importance: 3, icon: "fa-chevron-right" } );
        buttons.push({ title: L("lcl_shared_advanced"), action: "myModal()", xclass: "noxd", importance: 3, icon: "fa-filter"});
      }
      SIMPLE_BLOCK_START();
        CreateButtons(buttons, { entersubmit: true, showIcons: true });
      SIMPLE_BLOCK_END();
      SEARCH_PAGE_END();
%>
      </form>

    <div id="result">
      <iframe width="100%" height="100%"
              src="../Shared/empty.asp"
              name="workFrame" id="workFrame"
              onload="FcltMgr.iframeLoaded(this <% if (planbord) { %> , {noLimitWidth: true} <% } %>)"
              frameborder="0" scrolling="<%=(planbord ? "yes" : "no")%>">
      </iframe>
    </div>
  </body>
</html>
<% ASPPAGE_END(); %>
