<% /*
     $Revision$
     $Id$
    File:               bez_list.inc
    Description:        Show an overview of visitors in list-form,
                        which meets with the given requirements
    Parameters:
        urole           user role (fe, fo, bo, mi)
        outputmode      behave in an output mode, print to 0 = screen, 1 = printer, 2 = excel, etc.
        showall         show all visitors which meets with the given requirements
        showProperties  show the flex properties for all visitors
        afspr_key       search for visitors with the given appointment key
        searchtext      search for visitors with the given text in various descriptions
        datetimefrom    search for visitors at the selected date-month-year-time
        datetimeto      search for visitors at the selected date-month-year-time
        regio_key_arr   search for visitors with the given regio keys
        dist_key_arr    search for visitors with the given district keys
        loc_key_arr     search for visitors with the given location keys
        bld_key_arr     search for visitors with the given building keys
        flr_key_arr     search for visitors with the given floor key
        requestor_key   search for visitors with the given requestor key
        host_key        search for visitors with the given host key
        dep_key         search for visitors with the given department key
        groupbez        groupbez groepeer 1) // district (management info)
                                          2) // locatie (management info)
                                          3) // gebouw (management info)
                                          4) // maand (management info)
                                          5) // week (management info)
                                          6) // dag (management info)
                                          7) // afspraak (frontoffice en backoffice)
        bezPark         search (only) for visitors with a parking place
        bezExpect       search for visitors which are expected
        bezInside       search for visitors which are inside
        bezDepart       search for visitors which are departed
        bezClosed       search for visitors which are in archive
        withflex        display a flex column if there are any

    Context:            Search action from bez_search.asp form
    Note:

            tiny betekent: embedded in een afspraakscherm. Afspraakgegevens zie je dan dus al.

            Merk op dat dit een vrij belachelijk nesting van rollen en modes bevat, wat best helderder mag
*/ %>

<!-- #include file="./bez.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["jquery-ui.js", "../bez/bez_list.js", "../bez/bez.js"]
                    });

function bez_list(pautfunction, params)
{ // VALIDATE AND PREPARE
  // Als een parameter niet gedefinieerd of null is, dan doet-ie niks
  // anders wordt die verondersteld een zinvolle waarde te hebben
  // NB: -1 is vaak geen zinvolle waarde; null had het dan moeten zijn!

  // Valid and supported parameters are:
  // params.urole         : the usuals two-letter lowercase string
  // params.outputmode    : print to 0 = screen, 1 = printer, 2 = excel, etc.
  // params.showall       : boolean (true | false)
  // params.showProperties: boolean (true | false)
  // params.afspr_key     : key
  // params.searchtext    : wildcard string
  // params.datetimefrom  : date + time
  // params.datetimeto    : date + time
  // params.regio_key     : key
  // params.dist_key      : key
  // params.loc_key       : key
  // params.bld_key       : key
  // params.flr_key       : key
  // params.requestor_key : key
  // params.host_key      : key
  // params.dep_key       : key
  // params.groupbez      : key
  // params.bezPark       : boolean (true | false)
  // params.bezExpect     : boolean (true | false)
  // params.bezInside     : boolean (true | false)
  // params.bezDepart     : boolean (true | false)
  // params.bezClosed     : boolean (true | false)
  // params.flags         : intArray [flagkeys {0-9}]
  // params.tiny          : boolean (true | false) voor als de afspraakgegevens niet hoeven
  // params.mobile        : boolean (true | false)

  // De functie checkAutorisation(autfunction) geeft een Response.End indien er geen autorisatie voor autfunction wordt gevonden
  var authparams = user.checkAutorisation(pautfunction);

  var this_bez = bez.func_enabled_parkeerplaats();

  var reado = !(authparams.ALGwritelevel < 9);

  var authparamsFOF = user.checkAutorisation("WEB_BEZFOF", true);
  var canDelete = authparamsFOF && authparamsFOF.ALGwritelevel < 9 && authparamsFOF.PRSwritelevel < 9;

  var urole     = params.urole;
  var fronto    = (urole == "fo");
  var backo     = (urole == "bo");
  var minfo     = (urole == "mi"); // NOT APPLICABLE?
  var frontend  = (urole == "fe");

  // Voor resulttable de globalen zetten; zou ng anders moeten.
  var outputmode      = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var print           = (outputmode == 1 || outputmode == 5);
  var excel           = (outputmode == 2 || outputmode == 6);
  var showall         = params.showall;
  var showProperties  = params.showProperties;
  var tiny            = params.tiny;
  var noPrint         = params.noPrint;
  var afspr_key       = params.afspr_key;
  var searchtext      = params.searchtext;
  var datetimefrom    = params.datetimefrom;
  var datetimeto      = params.datetimeto;
  var regio_key_arr   = params.regio_key_arr;
  var dist_key_arr    = params.dist_key_arr;
  var loc_key_arr     = params.loc_key_arr;
  var bld_key_arr     = params.bld_key_arr;
  var flr_key_arr     = params.flr_key_arr;
  var requestor_key   = params.requestor_key;
  var host_key        = params.host_key;
  var dep_key         = params.dep_key;
  var groupbez        = params.groupbez;
  var action_key      = params.action_key;
  var bezPark         = params.bezPark;
  var bezExpect       = params.bezExpect;
  var bezInside       = params.bezInside;
  var bezDepart       = params.bezDepart;
  var bezClosed       = params.bezClosed;
  var hideUpdated     = params.hideUpdated;
  var flags           = params.flags;
  var withflex        = params.withflex &&
                        ((frontend && (S("bez_show_flex_in_list") & 1)) ||
                         (fronto   && (S("bez_show_flex_in_list") & 2)) ||
                         (backo    && (S("bez_show_flex_in_list") & 4)));
  var anyflex         = false;

  var sql = "SELECT COUNT(alg_gebouw_toon_email) aantal"
          + "  FROM alg_gebouw"
          + " WHERE alg_gebouw_verwijder IS NULL"
          + "   AND (  alg_gebouw_vervaldatum > SYSDATE"
          + "       OR alg_gebouw_vervaldatum IS NULL)"
          + "   AND alg_gebouw_toon_email = 1";
  var oRs = Oracle.Execute(sql);
  var gebouw_toon_email = (oRs("aantal").Value > 0); // Minimaal 1 gebouw waar dit veld gezet is.
  oRs.Close();

  var sql_date = null;
  if (datetimefrom && datetimeto)
  {
    var ora_date1 = datetimefrom.toSQL(true);
    var ora_date2 = datetimeto.toSQL(true);
    sql_date = " BETWEEN " + ora_date1 + " AND " + ora_date2;
  }
  else if (datetimefrom)
  {
    var ora_date1 = datetimefrom.toSQL(true);
    sql_date = " >= " + ora_date1;
  }
  else if (datetimeto)
  {
    var ora_date2 = datetimeto.toSQL(true);
    sql_date = " < " + ora_date2;
  }

  var sql = "SELECT COUNT(*) aantal"
          + "  FROM bez_kenmerk"
          + " WHERE bez_kenmerk_verwijder IS NULL"
          + "   AND BITAND(bez_kenmerk_rolcode, 4) = 4"  //BEZBOF-kenmerken
          //+ "   AND bez_kenmerk_kenmerktype NOT IN ('F','M','E','X')"
          + "   AND 1=" + (user.has("WEB_BEZBOF") ? 1 : 0); // alleen backo mag per bezoeker aanmelden.
  var oRs = Oracle.Execute(sql);
  var hasKenmerk = oRs("aantal").Value;
  oRs.Close();

  if (withflex && !excel && !print)
  {
    // Fast check to see if we have any listable flex at all, to prevent superfluous empty column
    var sql = "SELECT bez_kenmerk_omschrijving"
            + "  FROM bez_kenmerk"
            + " WHERE BITAND (bez_kenmerk_inlijst, 1) = 1"
            + "   AND bez_kenmerk_verwijder IS NULL";
    var oRs = Oracle.Execute(sql);
    anyflex = !oRs.eof;
    if (anyflex)
    {
        var multiflex = false;
        var flexlabel = oRs("bez_kenmerk_omschrijving").Value;
        oRs.MoveNext();
        if (!oRs.Eof)
        {
            multiflex = true;
            flexlabel = L("lcl_flexlist");
        }
    }
    oRs.close();
  }

%>

<html>
 <head>
<%
    if (!params.noHeader)
        FCLTHeader.Generate({ outputmode: outputmode });
%>
  <script type="text/javascript">

    $(function() {
      $(".clickParent").parent().on("click", function(e) { e.stopPropagation(); $(this).find("> .clickParent").trigger("click"); });
    });

    urole = "<%=urole%>";
    contactonly = <%=params.contactonly?1:0%>;
    var todayString = "<%=toDateString(new Date())%>";
    var hasKenmerk = (<%=hasKenmerk%> != 0);
    var s_vis_remark = <%=S("vis_remark")%>;
    var s_bez_show_progress_prop = <%=S("bez_show_progress_prop")%>; // Setting: Tonen afhandelings kenmerken (>900) voor bezoekers {0=nooit | 1=popup tijdens inchecken bezoekers(default) | 2=Inline actie | 4=Uitsluitend tonen in popup}
  </script>
 </head>
 <body<%=(tiny ? '' : ' id="listbody"')%>>
<%

      if (!groupbez || groupbez == 7) // elke individuele bezoeker
      { // geen management info => fe, fo en bo
        sql = "SELECT /*+ CURSOR_SHARING_EXACT */ " // cursor sharing uit zodat index op bez_afspraak_datum beter gebruikt wordt
            + (groupbez
              ? " DISTINCT"
              : "")
            + "       a.bez_afspraak_key afspr_key"
            + "     , rrr.res_rsv_ruimte_key"
            + (!groupbez
              ? "   , COALESCE(b.bez_bezoekers_done, a.bez_afspraak_datum) bez_afspraak_datum"
                + " , COALESCE(b.bez_bezoekers_out, a.bez_afspraak_eind) bez_afspraak_eind"
              : "   , a.bez_afspraak_datum bez_afspraak_datum"
                + " , a.bez_afspraak_eind bez_afspraak_eind")
            + "     , " + S("prs_pers_string") + " pers_naam"
            + "     , a.bez_afspraak_gastheer gastheer"
            + "     , p2.prs_perslid_email gastheer_email"
            + "     , COALESCE(a.bez_afspraak_telefoonnr, p2.prs_perslid_telefoonnr, p2.prs_perslid_mobiel) gastheer_telf_nr"
            + "     , COALESCE(p.prs_perslid_telefoonnr, p.prs_perslid_mobiel) telf_nr"
            + "     , COALESCE(rr.res_ruimte_groep, a.bez_afspraak_ruimte, l.alg_locatie_omschrijving) ruimte"
            + "     , a.bez_afspraak_opmerking"
            + "     , " + lcl.xsql("t.bez_actie_omschrijving", "t.bez_actie_key")+ " actie"
            + "     , t.bez_actie_flags"
            + "     , l.alg_locatie_omschrijving loc_omschr"
            + "     , " + lcl.xsqla("rr.res_ruimte_omschrijving", "rr.res_ruimte_key")
            + "     , fac.DatumTijdPlusUitvoerTijd(SYSDATE, " + S("vis_expire") + ", 'DAGEN') tExpire"
            + "     , rrr.res_rsv_ruimte_omschrijving"
            + "     , rr.res_ruimte_nr  ruimte_nr"
            + "     , rr.res_ruimte_extern_id"
            + "     , rrr.res_rsv_ruimte_externnr"
            + "     , sd.ins_srtdiscipline_prefix"
            + "     , m.mld_melding_key"
            + "     , mo.mld_opdr_bedrijfopdr_volgnr"
            + "     , " + lcl.xsqla("mto.mld_typeopdr_omschrijving", "mto.mld_typeopdr_key");

        sql += ", (SELECT COUNT (ins_deel_key)"
             + "     FROM (SELECT i.ins_deel_key"
             + "                , i.ins_alg_ruimte_key"
             + "                , i.ins_alg_ruimte_type"
             + "             FROM ins_deel i"
             + "                , ins_srtdeel s"
             + "            WHERE s.ins_srtdeel_key = i.ins_srtdeel_key"
             + "              AND i.ins_deel_verwijder IS NULL"
             + "              AND (i.ins_deel_vervaldatum IS NULL OR i.ins_deel_vervaldatum > TRUNC(SYSDATE))"
             + "              AND i.ins_deel_module = 'INS'"
             + "              AND i.ins_deel_parent_key IS NULL"
             + "              AND s.ins_srtdeel_uitleenbaar = 1"
             + "              AND i.ins_alg_ruimte_type = 'P'"
             + "           UNION"
             + "           SELECT i.ins_deel_key"
             + "                , i.ins_alg_ruimte_key"
             + "                , i.ins_alg_ruimte_type"
             + "             FROM ins_deel i"
             + "                , ins_srtdeel s"
             + "            WHERE s.ins_srtdeel_key = i.ins_srtdeel_key"
             + "              AND i.ins_deel_verwijder IS NULL"
             + "              AND (i.ins_deel_vervaldatum IS NULL OR i.ins_deel_vervaldatum > TRUNC(SYSDATE))"
             + "              AND i.ins_deel_module = 'INS'"
             + "              AND i.ins_deel_parent_key IS NULL"
             + "              AND s.ins_srtdeel_uitleenbaar = 1"
             + "              AND i.ins_alg_ruimte_type = 'C'"
             + "          ) x"
             + "    WHERE (x.ins_alg_ruimte_key = b.prs_perslid_key AND x.ins_alg_ruimte_type = 'P')"
             + "       OR (x.ins_alg_ruimte_key = b.prs_contactpersoon_key AND x.ins_alg_ruimte_type = 'C')) nr_of_items_lend";

        sql += ", (SELECT SUM(CASE"
             + "          WHEN b.bez_bezoekers_done IS NOT NULL"
             + "          THEN 1"
             + "          ELSE 0"
             + "          END)"
             + "     FROM bez_bezoekers b"
             + "    WHERE b.bez_afspraak_key = a.bez_afspraak_key) aantaldone";

        if (backo)
        {
          if (authparams.ALGwritelevel == -1)
          {
            sql += ", 1 authorized";  // altijd geautoriseerd tot afmelden
          }
          else if (authparams.ALGwritelevel == 9)
          {
            sql += ", 0 authorized";  // nooit geautoriseerd tot afmelden
          }
          else if (S("vis_afspraak_onrgoed_uses_keys") == 0 || (S("vis_afspraak_onrgoed_uses_keys") == 1 && S("vis_mandatory_alg_level") == 'L'))
          {
            sql += ", (SELECT COUNT(ml.alg_locatie_key)"  // check autorisatie op locatie niveau
                 + "     FROM (SELECT alg_locatie_key"
                   + "           FROM fac_v_my_locations"
                   + "          WHERE prs_perslid_key = " + user_key
                   + "            AND niveau = " + authparams.ALGwritelevel + ") ml"
                   + "  WHERE ml.alg_locatie_key = l.alg_locatie_key) authorized";
          }
          else if (S("vis_mandatory_alg_level") == 'G')  // gebouw is verplicht en dus aanwezig
          {
            sql += ", (SELECT COUNT(mg.alg_gebouw_key)"  // check autorisatie op gebouw niveau
                 + "     FROM (SELECT alg_gebouw_key"
                   + "           FROM fac_v_my_buildings"
                   + "          WHERE prs_perslid_key = " + user_key
                   + "            AND niveau = " + authparams.ALGwritelevel + ") mg"
                 + "        , alg_v_allonroerendgoed aog"
                 + "    WHERE mg.alg_gebouw_key = aog.alg_gebouw_key"
                 + "      AND aog.alg_onroerendgoed_keys = a.alg_onrgoed_keys) authorized";
          }
          else if (S("vis_mandatory_alg_level") == 'V')  // verdieping is verplicht en dus aanwezig
          {
            sql += ", (SELECT COUNT(mv.alg_verdieping_key)"  // check autorisatie op verdieping niveau
                 + "     FROM (SELECT alg_verdieping_key"
                   + "           FROM fac_v_my_floors"
                   + "          WHERE prs_perslid_key = " + user_key
                   + "            AND niveau = " + authparams.ALGwritelevel + ") mv"
                 + "        , alg_v_allonroerendgoed aog"
                 + "    WHERE mv.alg_verdieping_key = aog.alg_verdieping_key"
                 + "      AND aog.alg_onroerendgoed_keys = a.alg_onrgoed_keys) authorized";
          }
          else if (S("vis_mandatory_alg_level") == 'R')  // ruimte is verplicht en dus aanwezig
          {
            sql += ", (SELECT COUNT(mr.alg_ruimte_key)"  // check autorisatie op ruimte niveau
                 + " FROM (SELECT alg_ruimte_key"
                   + " FROM fac_v_my_rooms"
                   + " WHERE prs_perslid_key = " + user_key
                   + " AND niveau = " + authparams.ALGwritelevel + ") mr"
                 + ", alg_v_allonroerendgoed aog"
                 + " WHERE mr.alg_ruimte_key = aog.alg_ruimte_key"
                 + " AND aog.alg_onroerendgoed_keys = a.alg_onrgoed_keys) authorized";
          }
          else
          {
            sql += ", 0 authorized";  // zou niet voor moeten komen dus niet geautoriseerd
          }
        }
        else {
          sql += ", 0 authorized";  // zou niet voor moeten komen dus niet geautoriseerd
        }

        if (!groupbez)
          sql += "     , b.bez_afspraak_naam"
               + "     , b.bez_afspraak_bedrijf bez_bedrijf"
               + "     , b.prs_contactpersoon_key"
               + "     , b.prs_perslid_key"
               + "     , b.bez_bezoekers_opmerking"
               + "     , b.bez_bezoekers_telefoon"
               + "     , b.bez_bezoekers_email"
               + "     , b.bez_bezoekers_kenteken"
               + "     , b.bez_bezoekers_flags"
               + "     , b.bez_bezoekers_done"
               + "     , b.bez_bezoekers_aanmaak"
               + "     , b.bez_bezoekers_out "
               + "     , b.bez_bezoekers_key bez_key"
               + "     , b.bez_bezoekers_flag"
               + "     , b.bez_bezoekers_pasnr badgenr"
               + "     , COALESCE(rd.res_rsv_deel_key, 0) rsv_deel_key"
               + "     , COALESCE(org.alg_gebouw_code, org.alg_terreinsector_code) || ' ' || COALESCE(org.alg_gebouw_naam, org.alg_terreinsector_naam) code"
               + (anyflex
                 ? "   , (SELECT LISTAGG(" + (multiflex?"bez_kenmerk_omschrijving || ':'|| CHR(160) || ":"")
                   + "                   CASE"
                   + "                   WHEN k.bez_kenmerk_kenmerktype = 'R' OR k.bez_kenmerk_kenmerktype = 'r' OR k.bez_kenmerk_kenmerktype = 'S'"
                   + "                   THEN flx.getdomeinwaarde(k.fac_kenmerkdomein_key, kw.bez_kenmerkwaarde_waarde)"
                   + "                   WHEN k.bez_kenmerk_kenmerktype = 'N'"
                   + "                    AND k.bez_kenmerk_lengte = 1 "
                   + "                    AND k.bez_kenmerk_nmin = 0 "
                   + "                    AND k.bez_kenmerk_nmax = 1 "
                   + "                    AND (k.bez_kenmerk_dec = 0 OR k.bez_kenmerk_dec IS NULL) "
                   + "                   THEN DECODE (kw.bez_kenmerkwaarde_waarde, "
                   + "                                0, "+safe.qL("lcl_check_0")+", "
                   + "                                1, "+safe.qL("lcl_check_1")+", "
                   + "                                kw.bez_kenmerkwaarde_waarde)"
                   + "                   ELSE kw.bez_kenmerkwaarde_waarde"
                   + "                   END, CHR(13)) "
                   + "           WITHIN GROUP (ORDER BY k.bez_kenmerk_volgnr) "
                   + "      FROM bez_kenmerk k, bez_kenmerkwaarde kw"
                   + "     WHERE kw.bez_bezoekers_key = b.bez_bezoekers_key"
                   + "       AND k.bez_kenmerk_key = kw.bez_kenmerk_key"
                   + "       AND BITAND(k.bez_kenmerk_inlijst, 1) = 1"
                   + "       AND k.bez_kenmerk_verwijder IS NULL"
                   + "       AND kw.bez_kenmerkwaarde_verwijder IS NULL) flex"
                : "");
        else // groupbez == 7
          sql += "     , (SELECT COUNT(b1.bez_bezoekers_key)"
               + "          FROM bez_bezoekers b1"
               + "         WHERE b1.bez_afspraak_key = b.bez_afspraak_key) bez_aant"
               + "     , (SELECT COUNT(rd1.res_rsv_deel_key)"
               + "          FROM bez_bezoekers b1"
               + "             , res_rsv_deel rd1"
               + "         WHERE b1.bez_afspraak_key = b.bez_afspraak_key"
               + "           AND b1.bez_bezoekers_key = rd1.bez_bezoekers_key(+)) park_aant";
      }

      if (groupbez == 1) // district (management info)
      {
        sql = "SELECT d.alg_district_omschrijving alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 2) // locatie (management info)
      {
        sql = "SELECT l.alg_locatie_omschrijving alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 3) // gebouw (management info)
      {
        sql = "SELECT DECODE(l.alg_locatie_plaats, '', '', l.alg_locatie_plaats||'-')||g.alg_gebouw_naam alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 4) // Maand (management info)
      {
        sql = "SELECT TO_CHAR(a.bez_afspraak_datum, 'YYYY-MM') alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 5) // Week (management info)
      {
        sql = "SELECT TO_CHAR(a.bez_afspraak_datum, 'IYYY-IW') alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }
      if (groupbez == 6) // Dag (management info)
      {
        sql = "SELECT TRUNC(a.bez_afspraak_datum) alg_omschr"
            + "     , COUNT(*) sum_visitors"
            + "     , COUNT(bez_bezoekers_done) sum_checkin"
            + "     , COUNT (bez_bezoekers_out) sum_checkout"
            + "     , COUNT(rd.res_rsv_deel_key) sum_parking";
      }

      sql += " FROM bez_afspraak a"
           + "    , bez_bezoekers b"
           + "    , bez_actie t"
           + "    , prs_perslid p"
           + "    , prs_perslid p2"
           + "    , alg_locatie l"
           + "    , alg_district d"
           + "    , res_rsv_ruimte rrr"
           + "    , res_ruimte_opstelling rro"
           + "    , res_ruimte rr";

      var l_alg_v_onroerendgoed_gegevens = " (SELECT alg_r.alg_ruimte_key ALG_ONROERENDGOED_KEYS"
                                         + ", alg_r.alg_ruimte_key"
                                         + ", alg_r.alg_verdieping_key"
                                         + ", alg_v.alg_gebouw_key"
                                         + ", 'R' alg_type"
                                         + " FROM alg_ruimte alg_r"
                                         + ", alg_verdieping alg_v"
                                         + " WHERE alg_r.alg_verdieping_key = alg_v.alg_verdieping_key"
                                         + " UNION ALL"
                                         + " SELECT alg_v.alg_verdieping_key"
                                         + ", TO_NUMBER (NULL)"
                                         + ", alg_v.alg_verdieping_key"
                                         + ", alg_v.alg_gebouw_key"
                                         + ", 'V'"
                                         + " FROM alg_verdieping alg_v"
                                         + " UNION ALL"
                                         + " SELECT alg_g.alg_gebouw_key"
                                         + ", TO_NUMBER (NULL)"
                                         + ", TO_NUMBER (NULL)"
                                         + ", alg_g.alg_gebouw_key"
                                         + ", 'G'"
                                         + " FROM alg_gebouw alg_g)";

      if (groupbez == 3)
      {
        sql += ", " + l_alg_v_onroerendgoed_gegevens + " og"
             + ", alg_gebouw g";
      }
      else
      {
        sql += (((S("vis_afspraak_onrgoed_uses_keys") == 1) || (groupbez >= 1 && groupbez <= 6))
                 ? ", " + l_alg_v_onroerendgoed_gegevens + " og"
                 : "");
      }

      sql += "     , res_rsv_deel rd"
           + "     , res_deel d"
           + "     , ins_deel id"
           + "     , alg_v_allonrgoed_gegevens org"
           + "     , mld_opdr mo"
           + "     , mld_melding m"
           + "     , mld_stdmelding sm"
           + "     , ins_tab_discipline itd"
           + "     , ins_srtdiscipline sd"
           + "     , mld_typeopdr mto"
           + " WHERE a.bez_afspraak_key = b.bez_afspraak_key"
           + "   AND l.alg_district_key = d.alg_district_key"
           + "   AND t.bez_actie_key(+) = a.bez_actie_key"
           + "   AND a.alg_locatie_key = l.alg_locatie_key"
           + (((S("vis_afspraak_onrgoed_uses_keys") == 1) || (groupbez >= 1 && groupbez <= 6))
             ? " AND og.alg_onroerendgoed_keys(+) = a.alg_onrgoed_keys"
             : "")
           + (dep_key
             ? " AND p.prs_afdeling_key = " + dep_key + " "
             : "")
           + "   AND b.bez_bezoekers_key = rd.bez_bezoekers_key(+)"
           + "   AND p.prs_perslid_key = a.bez_afspraak_contact_key"
           + "   AND p2.prs_perslid_key(+) = a.bez_afspraak_host_key"
           + "   AND a.res_rsv_ruimte_key = rrr.res_rsv_ruimte_key(+)"
           + "   AND rrr.res_ruimte_opstel_key = rro.res_ruimte_opstel_key(+)"
           + "   AND rro.res_ruimte_key = rr.res_ruimte_key(+)"
           + "   AND rd.res_deel_key = d.res_deel_key(+)"
           + "   AND d.res_ins_deel_key = id.ins_deel_key(+)"
           + "   AND id.ins_alg_ruimte_key = org.alg_onroerendgoed_keys(+)"
           + "   AND a.mld_opdr_key = mo.mld_opdr_key(+)"
           + "   AND mo.mld_melding_key = m.mld_melding_key(+)"
           + "   AND m.mld_stdmelding_key = sm.mld_stdmelding_key(+)"
           + "   AND sm.mld_ins_discipline_key = itd.ins_discipline_key(+)"
           + "   AND itd.ins_srtdiscipline_key = sd.ins_srtdiscipline_key(+)"
           + "   AND mo.mld_typeopdr_key = mto.mld_typeopdr_key(+)";
      if (!afspr_key)
        sql += " AND BITAND(b.bez_bezoekers_flags, 8) = 0"; // +8 betekent dat hij niet aan de balie komt

      if (groupbez == 3)
      {
        sql += " AND og.alg_gebouw_key = g.alg_gebouw_key";
      }

      if (afspr_key)
        sql += " AND a.bez_afspraak_key = " + afspr_key;

      if (bezPark)
        sql += " AND id.ins_deel_key is not null ";

      // Kijk of deze database meerdere acties kent
      var actcntsql = "SELECT COUNT(*) cnt FROM bez_actie WHERE bez_actie_verwijder IS NULL"
      oRs = Oracle.Execute(actcntsql);
      var more_actions_exist = oRs("cnt").Value > 1;
      oRs.Close();

      var prsKeys = user.collegakeylist();

      if (authparams.PRSreadlevel >= 0)
      {
        if (authparams.PRSreadlevel == 0)
        {
          bedrKeys = "" + user.afdeling().prs_bedrijf_key();
          if (user.hasCollegas())
          {
            // bepaal de bedrijf keys van de collegas
            sql_afd = "SELECT DISTINCT ab.prs_bedrijf_key"
                    + " FROM prs_v_aanwezigperslid p"
                    + ", prs_afdeling d"
                    + ", prs_v_afdeling_boom ab"
                    + " WHERE p.prs_afdeling_key = d.prs_afdeling_key"
                    + " AND d.prs_afdeling_key = ab.prs_afdeling_key"
                    + " AND p.prs_perslid_key IN (" + prsKeys + ")";
            oRs = Oracle.Execute(sql_afd);
            while (!oRs.eof)
            {
              bedrKeys += "," + oRs("prs_bedrijf_key").value;
              oRs.MoveNext();
            }
          }
        }

        sql += " AND p.prs_afdeling_key IN ("
            + ((authparams.PRSreadlevel == 0)
              ? "SELECT a.prs_afdeling_key"
                + " FROM prs_v_afdeling a"
                + " WHERE a.prs_bedrijf_key IN (" + bedrKeys + ")"
              : "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 + ")")
            + ")";
      }

      if (!frontend)
      { // fo, bo of mi
        if (!afspr_key && searchtext)
        {
           var wildsearchtext = safe.quoted_sql_wild("%" + searchtext + "%");
           sql += " AND (UPPER(b.bez_afspraak_naam)       LIKE" + wildsearchtext
               +  "   OR UPPER(b.bez_afspraak_bedrijf)    LIKE" + wildsearchtext
               +  "   OR UPPER(a.bez_afspraak_ruimte)     LIKE" + wildsearchtext
               +  "   OR UPPER(p.prs_perslid_naam)        LIKE" + wildsearchtext
               +  "   OR UPPER(a.bez_afspraak_gastheer)   LIKE" + wildsearchtext
               +  "   OR UPPER(a.bez_afspraak_opmerking)  LIKE" + wildsearchtext
               +  "   OR UPPER(b.bez_bezoekers_opmerking) LIKE" + wildsearchtext
               +  "   OR UPPER(b.bez_bezoekers_pasnr)     LIKE" + wildsearchtext + ")";
        }

        if (!afspr_key && flags && flags.length > 0 && flags.length < S("bez_bezoekers_flags"))
        {
          var filterNull = false;

          for (var i = 0; i < flags.length; i++)
          {
           if (flags[i] === 0)
           {
             filterNull = true;
           }
          }

          sql += " AND (b.bez_bezoekers_flag IN (" + flags.join(",") + ")";

          if (filterNull)
            sql += " OR b.bez_bezoekers_flag IS NULL";
          sql += ")";
        }

        if (!afspr_key && host_key)
           sql += " AND a.bez_afspraak_host_key = " + host_key;

        if (!afspr_key && requestor_key)
           sql += " AND p.prs_perslid_key = " + requestor_key;

        if (!afspr_key && sql_date)
           sql += " AND a.bez_afspraak_datum " + sql_date;

        if (!afspr_key && action_key)
           sql += " AND a.bez_actie_key = " + action_key;

        if (!afspr_key)
        {
          if (backo || fronto)
          {
            if (S("vis_checkout_enable") == 1)
            {
              // Verwacht (bezExpectH)
              sql1 = " (b.bez_bezoekers_done IS NULL"
                   + "  AND b.bez_bezoekers_out IS NULL)";      // 100

              // Binnen (bezInside)
              sql2 = " (b.bez_bezoekers_done IS NOT NULL"
                   + " AND b.bez_bezoekers_out IS NULL)";     // 010

              // Vertrokken (bezDepart)
              sql3 = " (b.bez_bezoekers_out IS NOT NULL)"; // 001

              if (bezExpect)
                if (bezInside)
                  if (bezDepart)
                    // sql += " AND (" + sql1 + " OR " + sql2 + " OR " + sql3 + ")"; // 111 show everything
                    sql += ""; // de datum filtering is al toegevoegd
                  else
                    sql += " AND (" + sql1 + " OR" + sql2 + ")"; // 110
                else
                  if (bezDepart)
                    sql += " AND (" + sql1 + " OR" + sql3 + ")"; // 101
                  else
                    sql += " AND " + sql1; // 100
              else
                if (bezInside)
                  if (bezDepart)
                    sql += " AND ( " + sql2 + " OR" + sql3 + ")"; // 011
                  else
                    sql += " AND" + sql2; // 010
                else
                  if (bezDepart)
                    sql += " AND" + sql3; // 001
                  else
                    sql += " AND (1=0)" // 000 show nothing
                    // There is always 1 checkbox selected
            }
            else { // S("vis_checkout_enable") == 0
              if (bezExpect)
                if (bezClosed) // Verwerkt (bezClosed)
                  sql +=  ""; // 11 show everything
                else
                  sql += " AND b.bez_bezoekers_done IS NULL"; // 10
              else
                if (bezClosed) // Verwerkt (bezClosed)
                  sql += " AND b.bez_bezoekers_done IS NOT NULL"; // 01
                else
                  sql += " AND (1=0)" // 00 show nothing
                  // There is alway 1 checkbox selected
            }
          }
        }

        if (!afspr_key && regio_key_arr.length && !dist_key_arr.length)
        {
            sql += " AND d.alg_regio_key IN (" + regio_key_arr.join(",") + ") ";
        }
        else if (!afspr_key && dist_key_arr.length && !loc_key_arr.length)
        {
            sql += " AND d.alg_district_key IN (" + dist_key_arr.join(",") + ") ";
        }
        else
        {
          if (authparams.ALGreadlevel > -1 && loc_key_arr.length)
            sql += " AND EXISTS ("
                + " SELECT 'x'"
                + " FROM fac_v_my_districts  lr"
                + " WHERE lr.prs_perslid_key = " + user_key
                + " AND d.alg_district_key = lr.alg_district_key "
                + " AND lr.niveau = " + authparams.ALGreadlevel + ")";
        }

        if (!afspr_key && loc_key_arr.length)
           sql += " AND a.alg_locatie_key IN (" + loc_key_arr.join(",") + ")";
        else
        {
           if (authparams.ALGreadlevel > -1)
               sql += " AND EXISTS ("
                   + " SELECT 'x'"
                   + " FROM fac_v_my_locations lr "
                   + " WHERE lr.prs_perslid_key = " + user_key
                   + " AND a.alg_locatie_key = lr.alg_locatie_key"
                   + " AND lr.niveau = " + authparams.ALGreadlevel + ")";
        }

        if ((S("vis_afspraak_onrgoed_uses_keys") == 1) || (groupbez >= 1 && groupbez <= 6))
        {
          if (!afspr_key && bld_key_arr.length)
          {
            sql += " AND og.alg_gebouw_key IN (" + bld_key_arr.join(",") + ")";
            if (flr_key_arr.length)
                sql += " AND og.alg_verdieping_key IN (" + flr_key_arr.join(",") + ")";
          }
          else
           if (authparams.ALGreadlevel >= 3) // Anno feb-2016 blijkt geen enkele klant niveau 3 ingesteld te hebben
             sql += " AND EXISTS ("
                 + " SELECT 'x'"
                 + " FROM fac_v_my_buildings gr "
                 + " WHERE gr.prs_perslid_key = " + user_key
                 + " AND gr.alg_gebouw_key = COALESCE(og.alg_gebouw_key, gr.alg_gebouw_key)"
                 + " AND gr.niveau = " + authparams.ALGreadlevel + ")";
        }

      }
      else
      { // fe mode
        // String met collega keys is voor de tijd bepaald want in de sql duurde te lang.
        sql += " AND (a.bez_afspraak_contact_key IN (" + prsKeys + ")"
            + " OR a.bez_afspraak_host_key IN (" + prsKeys + ")"
            + ")";

        if (!afspr_key && sql_date)
          sql+= " AND a.bez_afspraak_datum " + sql_date;
        else
          sql+= " AND a.bez_afspraak_datum >= SYSDATE-" + S("vis_user_history");
      }

      if (!groupbez || groupbez == 7) {
        sql += " ORDER BY a.bez_afspraak_datum, " + (!groupbez && (!backo || S("bez_bo_orderby") == 0)? "bez_afspraak_naam" : "gastheer");
      }
      if (groupbez == 1)
      {
        sql += " GROUP BY d.alg_district_omschrijving"
             + ", alg_district_upper "
             + " ORDER BY alg_district_upper";
      }

      if (groupbez == 2)
      {
        sql += " GROUP BY l.alg_locatie_omschrijving"
             + ", l.alg_locatie_upper "
             + " ORDER BY alg_locatie_upper";
      }

      if (groupbez == 3)
      {
        sql += " GROUP BY g.alg_gebouw_key"
             + ", g.alg_gebouw_naam"
             + ", g.alg_gebouw_upper"
             + ", l.alg_locatie_plaats"
             + " ORDER BY g.alg_gebouw_upper";
      }

      if (groupbez == 4)
      {
        sql += " GROUP BY to_char(a.bez_afspraak_datum, 'YYYY-MM')  "
             + " ORDER BY 1";
      }
      if (groupbez == 5)
      {
        sql += " GROUP BY to_char(a.bez_afspraak_datum, 'IYYY-IW')  "
             + " ORDER BY 1";
      }
      if (groupbez == 6)
      {
        sql += " GROUP BY TRUNC(a.bez_afspraak_datum)  "
             + " ORDER BY 1";
      }

      /********************************************
       * General Callback functies ResultsetTable *
       ********************************************/

      var recent = new Date();
      recent.setMinutes(recent.getMinutes() - S("bez_bezoekers_recent"));
      function fnrowClass(oRs)
      {
        var class1 = "";

        if (backo)
        {
          if (oRs("authorized").value != 1)
            class1 = "unauthorized";
        }
        else // TODO PF: gaat helemaal mis voor mi 16-2-2009 18:46:24
        {
	        var tNow = new Date();
          // In het verleden zijn ze grijs voor de fe
          // if (tVan <= tNow && !fronto && !backo && (!(excel || print)))
          // if (group == -1) geldt ook nog => !minfo ofwel frontend
          // if (oRs("bez_afspraak_eind").Value <= tNow && !fronto && !minfo && !backo && (!(excel || print)))
          if (frontend && oRs("bez_afspraak_eind").Value <= tNow && (!(excel || print)))
            class1 = "unauthorized";
        }

        if (!groupbez && oRs("bez_bezoekers_aanmaak").Value > recent && !hideUpdated) // only updated class for lists, not for detail screens
        {
          class1 += " updated ";
        }
        return class1;
      }

      // Extra data voor de client om daar dynamisch buttons te kunnen activeren.
      function fnrowData(oRs)
      {
          var afspr_key = oRs("afspr_key").Value;
          var tVan = oRs("bez_afspraak_datum").Value;
          var bez_key;
          if (!groupbez)
            bez_key = oRs("bez_key").value;

          var authorized = 0; // nooit geautoriseerd tot afmelden
          if (backo) authorized = oRs("authorized").Value;

          var data = {afspr_key: afspr_key, bez_key: bez_key, tVan: tVan, authorized: authorized};
          return JSON.stringify(data);
      }

      function fnrowActionEnabler(oRs)
      {
        var tVan = 0;
        var tExpire = 0;
        var aantaldone = 0;
        var ruimte_extern = false;
        if (!minfo)
        {
          tVan = oRs("bez_afspraak_datum").Value;
          tExpire = oRs("tExpire").Value;
          aantaldone = oRs("aantaldone").Value;
          ruimte_extern = ((oRs("res_ruimte_extern_id").Value != null) || (oRs("res_rsv_ruimte_externnr").Value != null));
        }

        var eEdit = (fronto || backo || (tVan > tExpire));
        var eDelete = (canDelete || (tVan > tExpire)) && !ruimte_extern && aantaldone == 0;
        var eEditMulti = fronto || backo;
        var data = {eEdit: eEdit, eDelete: eDelete };

        return data;
      }

      function fncolContact(oRs)
      {
        var icon = "";
        // Alleen uitgeleende objecten opvragen indien personen ook daadwerkelijk objecten in zijn bezit heeft
        if ((backo || tiny) && oRs("nr_of_items_lend").value > 0)
        { // Er is een prs_perslid_key of prs_contactpersoon_key
          var icontxt = "";
          if (outputmode == 0)
          {
            if (oRs("prs_perslid_key").value)
            {
                var typ = 'P';
                var pc_key = oRs("prs_perslid_key").value
            }
            else
            {
                var typ = 'C';
                var pc_key = oRs("prs_contactpersoon_key").value
            }
            var sqlC = "SELECT i.ins_deel_omschrijving"
                     + "  FROM ins_deel i"
                     + "     , ins_srtdeel s"
                     + " WHERE s.ins_srtdeel_key = i.ins_srtdeel_key"
                     + "   AND i.ins_deel_verwijder IS NULL"
                     + "   AND i.ins_deel_module = 'INS'"
                     + "   AND i.ins_deel_parent_key IS NULL"
                     + "   AND s.ins_srtdeel_uitleenbaar = 1"
                     + "   AND i.ins_alg_ruimte_type = " + safe.quoted_sql(typ)
                     + "   AND i.ins_alg_ruimte_key = " + pc_key
                     + " ORDER BY ins_deel_omschrijving";
            var oRsC = Oracle.Execute(sqlC);
            while (!oRsC.eof)
            {
              icontxt += (icontxt != ""? "\n" : "") + safe.htmlattr(oRsC("ins_deel_omschrijving").value);
              oRsC.MoveNext();
            }
          }
          icon = "<span class='lendobj'" + (icontxt != ""? " title='" + icontxt : "") + ">" + I("fa-link") + "</span>";
        }

        if (outputmode != 0 || (oRs("prs_contactpersoon_key").value == null && oRs("prs_perslid_key").value == null))
            return safe.htmlattr(oRs("bez_afspraak_naam").Value) + icon;

        var action = "FcltMgr.openDetail('appl/" + (oRs("prs_contactpersoon_key").value? "prs/prs_contactpersoon.asp?key=" : "fac/fac_user_info.asp?prs_key=")
                   + (oRs("prs_contactpersoon_key").value? oRs("prs_contactpersoon_key").value : oRs("prs_perslid_key").value)
                   + "'); FcltMgr.stopPropagation(event);";
        return '<a href="#" title="' + (oRs("prs_contactpersoon_key").value? L("lcl_vis_contactperson") : L("lcl_intern_pers"))
             + '" onclick="' + action + ';return false;">' + safe.htmlattr(oRs("bez_afspraak_naam").Value) + "</a>" + icon;
      }

      function fncolDate(oRs)
      {
        return "<nobr>" + toDateString(oRs("bez_afspraak_datum").value) + "</nobr>"
             + ((toDateString(oRs("bez_afspraak_datum").value) != toDateString(oRs("bez_afspraak_eind").value))
                ? '<br /><nobr>:' + toDateString(oRs("bez_afspraak_eind").value) + '</nobr>'
                : "");
      }

      function fncolOmschrijving(oRs)
      {
        var txt;
        var rsv_ruimte_omschrijving = oRs("res_rsv_ruimte_omschrijving").Value;
        if (rsv_ruimte_omschrijving)
          txt = safe.html(rsv_ruimte_omschrijving);
        var mld_key = oRs("mld_melding_key").Value;
        if (mld_key)
          txt = safe.html(oRs("mld_typeopdr_omschrijving").Value) + " " + safe.html(oRs("ins_srtdiscipline_prefix").Value) + mld_key + "/" + safe.html(oRs("mld_opdr_bedrijfopdr_volgnr").Value)
      	return txt;
      }

      function fncolOpmerking(oRs)
      {
        var txt = oRs("bez_afspraak_opmerking").value||""; // Geen safe.html, dat doet ResultsetTable.formatValue wel
        if (!groupbez && oRs("bez_bezoekers_opmerking").value)
            txt += "\n"+ oRs("bez_bezoekers_opmerking").value;
      	return ResultsetTable.formatValue(txt, {});
      }

      function fncolBadgenr(oRs)
      {
        // Op scherm nog niet ingevulde nummers als input tonen
        if (oRs("badgenr").value == null)
            if (outputmode == 0)
               return '<input class="fldshort fldbadge" type=text size="10" maxlength="30"' + (reado || (oRs("authorized").value != 1)?' disabled':'')
                   + ' id="badgenr' + oRs("bez_key").value + '"'
                   + ' value="" OnClick="FcltMgr.stopPropagation(event)" onFocus="this.select()"'
                   + ' onchange="SaveBadge(' + oRs("bez_key").Value + ', this.value)">';
            else
               return "";
        else
          return safe.html(oRs("badgenr").value);
      }

      function fncolParkSort(oRs)
      {
        if (oRs("rsv_deel_key").value != 0)
            return 0; // Zodat met één keer klikken de P bovenaan
        else
            return 1;
      }

      function fncolPark(oRs)
      {
        if (oRs("rsv_deel_key").value != 0)
        {
          if (outputmode == 0)
          {
            if (!tiny)
              return "<span id='park' title='" + oRs("code").value + "'>" + I("fa-parking") + "</span>";
            else
              return safe.html(oRs("code").value);
          }
          else
          {
            // return 'P';
            return oRs("code").value;
          }
        }
        else
        {
          return '&nbsp;';
        }
      }

      function fncolRegVisit(oRs)
      {
        if (oRs("bez_bezoekers_done").value == null)
        { // date is empty, visitor is not yet in/badge not yet ready, show clickable action
          if (outputmode == 0)
          {
              content = '<span id="CHDin' + oRs("bez_key").value + '"'
                      + ' class="ilbutton"'
                      + (oRs("authorized").value == 1
                        ? ' OnClick="doCheckIn(event, ' + oRs("bez_key").value + ', 0);"'
                          + ' title="' + L("lcl_vis_register") + '"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '>' + I("fa-square") + '</span>';
          }
            else
                content = "&nbsp;";
        }
        else
        { // visitor is already inside
          if (outputmode == 0)
              content = '<span id="CHDin' + oRs("bez_key").value + '"'
                      + ' class="ilbutton"'
                      + ((oRs("authorized").value == 1 && S("vis_allow_uncheck"))
                        ? ' OnClick="doCheckIn(event, ' + oRs("bez_key").value + ', '
                          + ((oRs("bez_bezoekers_out").value == null) // bezoeker not out
                            ? '1' // Undo check in
                            : '0') // Check in
                          + ');"'
                          + ' title="' + L("lcl_vis_done") + ' (' + toDateTimeString(oRs("bez_bezoekers_done").Value) + ')"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '>' + I("fa-check-square") + '</span>';
           else
                content = toDateTimeString(oRs("bez_bezoekers_done").value);
        }
        return "<div id='checkin" + oRs("bez_key").value + "'>" + content + "</div>";
      }

      function fncolSignOutVisit(oRs)
      {
        if (oRs("bez_bezoekers_out").value == null) // bezoeker not out
        {
          if (outputmode == 0)
              content = '<span id="CHOut' + oRs("bez_key").value + '"'
                      + ' class="ilbutton"'
                      + (oRs("authorized").value == 1
                         ? ' OnClick="doCheckOut(event, ' + oRs("bez_key").value + ', 0);"'
                           + ' title="' + L("lcl_vis_todo") + '"'
                         : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '>' + I("fa-square") + '</span>';
            else
                content = "&nbsp;";
        }
        else
        {
          if (outputmode == 0)
              content = '<span id="CHOut' + oRs("bez_key").value + '"'
                      + ' class="ilbutton"'
                      + ((oRs("authorized").value == 1 && S("vis_allow_uncheck"))
                        ? ' OnClick="doCheckOut(event, ' + oRs("bez_key").value + ', 1);"'
                          + ' title="' + L("lcl_vis_checkout") + ' (' + toDateTimeString(oRs("bez_bezoekers_out").Value) + ')"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '>' + I("fa-check-square") + '</span>';
           else
                content = toDateTimeString(oRs("bez_bezoekers_out").value);
        }
        return "<div id='checkout" + oRs("bez_key").value + "'>" + content + "</div>";
      }

      function fncolPrintBadge(oRs)
      {
        if ((S("vis_badgeprint_enable") & 4) == 4 && (oRs("bez_actie_flags").Value &2) != 2)
            return; // Alleen voor autobadge

        return '<span id="CHPrt' + oRs("afspr_key").value + '"'
             + ' class="ilbutton"'
             + ((outputmode == 0) && (oRs("authorized").value == 1)
               ? ' OnClick="FcltMgr.stopPropagation(event);printBadge(' + oRs("bez_key").value + ');"'
                 + ' alt="' + L("lcl_vis_printbadge") + '"'
               : ' OnClick="FcltMgr.stopPropagation(event);"')
             + '>' + I("fa-id-badge") + '</span>';
      }

      function fncolRuimte(oRs)
      {
        return (S("bez_show_resname") && oRs("ruimte_nr").Value
               ? safe.html(oRs("ruimte_nr").Value)
               : safe.html(oRs("ruimte").Value)
               );
      }

      function fncolResRuimteOmschrijving(oRs)
      {
        return (S("bez_show_resname") && oRs("res_ruimte_omschrijving").Value
               ? safe.htmlattr(oRs("res_ruimte_omschrijving").Value)
               : safe.htmlattr(oRs("ruimte_nr").Value)
               );
      }

      function fncolFlags(oRs)
      {
        var bez_key   = oRs("bez_key").Value;
        var afspr_key = oRs("afspr_key").Value;
        var flagkey   = oRs("bez_bezoekers_flag").Value || 0;
        var ttl       = L("lcl_bez_flag" + flagkey);
        var displ     = "";

        if (print || excel)
        {
            if (flagkey != 0) displ = safe.html(ttl);  // else blijft-ie gewoon leeg
        }
        else  // maak er dan nog leuke plaatjes van
        {
            // Met hidden flagkey voor sortering. 999 zorgt dat bij 1 keer sorteren de gevlagde direct bovenaan staan
            displ = "<div class='clickParent' " + ((urole == "bo" || urole == "fo") ? "onclick='toggleBezFlag(event, "+ afspr_key +", "+ bez_key +");'":"")
                  + " title='"+safe.htmlattr(ttl)+"'>"
                  + "<span id='bezflagimg"+bez_key+"' flagkey='"+flagkey+"' class='bezflag"+flagkey+"'>" + I("fa-fclt-flag" + (flagkey == 0 ? "0" : "")) + "</span>"
                  + "<span style='display:none'>"+(flagkey||999)+"</span></div>";
        }
        return displ;
      }

      function fncolTeams(oRs)
      {
        var safe_content = "";
        var chatHostMail = oRs("gastheer_email").Value;
        var chatHostName = oRs("gastheer").Value || "";
        var bez_naam = oRs("bez_afspraak_naam").Value || "";
        var bez_bedrijf = oRs("bez_bedrijf").Value || "";
        var locatie = oRs("loc_omschr").Value || "";
        var defaultMessage = L("lcl_bezchat_message").format(bez_naam, bez_bedrijf, locatie).replace("()", "");
        if (outputmode == 0 && oRs("authorized").Value == 1 && chatHostMail && ((oRs("bez_actie_flags").Value & 4)==4))
        {
          var chatUrl = S("bez_chat_message").format(chatHostMail, Server.URLencode(defaultMessage));
          safe_content = '<span id="chatIN' + oRs("bez_key").Value + '"'
                       + ' class="ilbutton"'
                       + ' OnClick="doLaunchChat(event, \'' + safe.jsstring(chatUrl) + '\');"'
                       + ' title="' + safe.htmlattr(L("lcl_bezchat_launch").format(chatHostName)) + '"'
                       + '>' + I("fa-comment-exclamation") + '</span>';
          safe_content = "<div id='chatlink" + oRs("bez_key").Value + "'"
                       + (oRs("bez_bezoekers_done").value === null ? " class='hidden'" : "")
                       + ">" + safe_content + "</div>";
        }
        return safe_content;
      }

      /**********************************************
       * End general callback functies ResultsetTable
       *********************************************/

      var this_bez_afspraak = bez.func_enabled_afspraak(afspr_key);
      var xparams = "";
      if ((groupbez >= 1 && groupbez <= 6)) // minfo
      {
        xparams = {keyColumn: "alg_omschr", // Dummy
                  sql: sql,
                  ID: "beztable",
                  noPrint: noPrint,
                  filterParams: params,
                  outputmode: outputmode,
                  showAll: showall,
                  rowActionEnabler: fnrowActionEnabler,
                  nofloating: ("nofloating" in params ? params.nofloating : false)};
      }
      else
      {
        var buttons = [];
        if (!tiny)
        {
          if (authparams.ALGwritelevel < 9)
          {
              var addurl = "appl/bez/bez_afspraak.asp?urole=" + urole;
              if (params.contactonly)
                addurl += "&contactonly=1";
              var action = "FcltMgr.openDetail('" + addurl + "', '" + safe.jsstring(L("lcl_add")) + "')";

              if (urole == 'bo') // Krijgt de kans een pool-reservering te kiezen
              {
                  var sql2 = "SELECT *"
                           + "  FROM bez_actie"
                           + " WHERE bez_actie_verwijder IS NULL"
                           + "   AND BITAND(bez_actie_flags, 1) = 1"; // Bestaan er oproepers?
                  var oRs = Oracle.Execute(sql2);
                  if (!oRs.Eof)
                  {
                      var addurl = "bez_afspraak_bo_new.asp" + (loc_key_arr.length ? "?loc_key=" + loc_key_arr.join(",") : "");
                      if (params.contactonly)
                        addurl += "&contactonly=1";
                      var action = "FcltMgr.openModalDetail('" + addurl + "', '" + safe.jsstring(L("lcl_add")) + "', { callback: bezPoolCallback })";
                  }
                  oRs.Close()
              }

              buttons = [{ icon: "fa-plus", title: L("lcl_add"), action: action }];
          }
          buttons.push({ icon: "fa-columns",  title: L("lcl_scf_columns"), action: "openColumns()"});
        }
        xparams = { keyColumn: (!groupbez? "bez_key" : "afspr_key"),
                    rowClass: fnrowClass,
                    rowData: fnrowData,
                    sql: sql,
                    noPrint: noPrint,
                    summaryShow: (!groupbez && tiny ? function () {} : null),
                    ID: "beztable" + (tiny? "tiny" : ""),
                    flexModule: "BEZ",
                    flexId: (!groupbez? "bez_key" : null),
                    filterParams: params,
                    outputmode: outputmode,
                    showAll: showall,
                    showProperties: showProperties,
                    rowActionEnabler: fnrowActionEnabler,
                    buttons: buttons,
                    mobile: params.mobile,
                    nofloating: tiny || ("nofloating" in params ? params.nofloating : false)
                    };
      }

      if (!tiny)
      {
        xparams.title = L("lcl_vis_visitors");
        if (!groupbez || groupbez == 7)
          xparams.tabs_code = "bez_list-" + urole + (groupbez == 7? "-" + groupbez : "");
      }

      var rst = new ResultsetTable(xparams);

      // Kolommen
      if (!groupbez || groupbez == 7)
      {

        if (groupbez == 7)
        {
          rst.addColumn(new Column({caption: L("lcl_vis_appointment"), content: "afspr_key"}));
        }

        // Flags
        if (!groupbez && S("bez_bezoekers_flags") > 0 && !frontend)
        {
          rst.addColumn(new Column({caption: (outputmode == 0 ? I("fa-fclt-flag0") : L("lcl_bez_flags")), content: fncolFlags, colName: "fncolFlags", colText: L("lcl_bez_flags"), align: "center"}));
        }

        if (!groupbez && (backo || fronto)) {
          var captionResOk = I("fa-sign-in-alt fa-2x");
          rst.addColumn(new Column({caption: (outputmode == 0 ? captionResOk : L("lcl_vis_inside")), content: excel?"bez_bezoekers_done":fncolRegVisit, datatype: "datetime", colName: "fncolRegVisit", colText: L("lcl_bez_is_in_1"), align: "center"}));
          if (backo) {
            var actie_sql = "SELECT 1"
                          + "  FROM bez_actie"
                          + " WHERE bez_actie_verwijder IS NULL"
                          + "   AND BITAND(bez_actie_flags, 4) = 4"; // Bestaat er een onthaal-actie via teams?
            var actie_oRs = Oracle.Execute(actie_sql);
            if (!actie_oRs.eof) {
              rst.addColumn(new Column({caption: I("fa-comment-exclamation fa-lg"), content: fncolTeams, colName: "fncolTeams", align: "center"}));
            }
            actie_oRs.Close();
          }
        }
        if (!tiny)
        {

          // Als ik niet zeker weet dat het allemaal op dezelfde dag is, toon ik de datum
          // tevens bij printen en excel ook.
          if ( !datetimefrom ||
               !datetimeto ||
               outputmode != 0 ||
                (datetimefrom && datetimeto && datetimefrom.midnight().getTime() != datetimeto.midnight().getTime())
              )
          { // Compact als begin==eind
             rst.addColumn(new Column({caption: L("lcl_date"), content: excel?"bez_afspraak_datum":fncolDate, colName: "fncolDate" }));
          }
          rst.addColumn(new Column({caption: L("lcl_time"), content: "bez_afspraak_datum", datatype: "time"}));

          if (!groupbez && urole!="fe" && S("vis_checkout_enable") == 1)
          {
            var captionVisBad = I("fa-sign-out fa-2x");
            rst.addColumn(new Column({caption: (outputmode == 0 ? captionVisBad : L("lcl_vis_departed")), content: excel?"bez_bezoekers_out":fncolSignOutVisit, datatype: "datetime", colName: "fncolSignOutVisit", colText: L("lcl_bez_is_out_1"), align: "center"}));
          }
          if (excel)
          {
            rst.addColumn(new Column({caption: L("lcl_to"), content: "bez_afspraak_eind", datatype: "date"}));
          }
          rst.addColumn(new Column({caption: L("lcl_to"), content: "bez_afspraak_eind", datatype: "time"}));
        }

        if (groupbez == 7)
        {
          rst.addColumn(new Column({caption: L("lcl_vis_number_vis"), content: "bez_aant", datatype: "number"}));
          if (S("vis_parking_key") > 0  && this_bez.canWritePrk)
          {
            rst.addColumn(new Column({caption: L("lcl_vis_number_park"), content: "park_aant", datatype: "number"}));
          }
        }

        if (!groupbez)
        {
          if (!backo || S("bez_bo_orderby") == 0)
          {
            rst.addColumn(new Column({caption: L("lcl_vis_name"), nowrap: true, content: fncolContact, colName: "fncolContact"}));
            rst.addColumn(new Column({caption: L("lcl_vis_company"), content: "bez_bedrijf", combine: !tiny, hasActions: true}));
          }
          else
          {
            rst.addColumn(new Column({caption: L("lcl_vis_visit"), nowrap: true, content: "gastheer"}));
            if (S("bez_gastheer_telfnr") == 1)
              rst.addColumn(new Column({caption: L("lcl_phone"), content: "gastheer_telf_nr", combine: true}));
          }
          if (S("vis_parking_key") != -1 && this_bez.canWritePrk)
          {
            var parkcaption = (outputmode == 0 ? I("fa-parking fa-2x") : L("lcl_parking_caption"));
            rst.addColumn(new Column({caption: parkcaption, content: fncolPark, colName: "fncolPark", customSort: fncolParkSort, colText: L("lcl_vis_park"), align: "center" }));
          }
          // De kolommen telefoon, email of kenteken alleen in het overzicht tonen als er een gebouw is waarbij dit is aangegeven.
          var sql = "SELECT COUNT(g.alg_gebouw_key) aantal"
                  + "     , SUM(CASE WHEN alg_gebouw_toon_telefoon > 0 THEN 1 ELSE 0 END) toon_telefoon"
                  + "     , SUM(CASE WHEN alg_gebouw_toon_email > 0 THEN 1 ELSE 0 END) toon_email"
                  + "     , SUM(CASE WHEN alg_gebouw_toon_kenteken > 0 THEN 1 ELSE 0 END) toon_kenteken"
                  + "  FROM alg_v_aanweziggebouw g"
                  + "     , alg_locatie l"
                  + " WHERE l.alg_locatie_key = g.alg_locatie_key"
                  + "   AND (l.alg_locatie_vervaldatum IS NULL OR l.alg_locatie_vervaldatum > TRUNC(SYSDATE))"
                  + "   AND (g.alg_gebouw_vervaldatum IS NULL OR g.alg_gebouw_vervaldatum > TRUNC(SYSDATE))"
                  + "   AND g.alg_gebouw_bez = 1";
          var oRs = Oracle.Execute(sql);
          if (oRs("toon_telefoon").Value > 0)
            rst.addColumn(new Column({caption: L("lcl_bez_telefoon"), content: "bez_bezoekers_telefoon", thClass: "bezoekers_telefoon_th", tdClass: "bezoekers_telefoon"}));
          if (oRs("toon_email").Value > 0)
            rst.addColumn(new Column({caption: L("lcl_bez_email"), content: "bez_bezoekers_email", thClass: "bezoekers_email_th", tdClass: "bezoekers_email"}));
          if (oRs("toon_kenteken").Value > 0)
            rst.addColumn(new Column({caption: L("lcl_bez_kenteken"), content: "bez_bezoekers_kenteken", thClass: "bezoekers_kenteken_th", tdClass: "bezoekers_kenteken"}));
          oRs.close();
          if (tiny) {
              rst.addColumn(new Column({caption: L("lcl_remark"), content: "bez_bezoekers_opmerking"}));
              rst.addColumn(new Column({caption: L("lcl_bez_done_date"), content: "bez_bezoekers_done", datatype: "time"}));
              rst.addColumn(new Column({caption: L("lcl_bez_out_date"), content: "bez_bezoekers_out", datatype: "time"}));
          }
        }

        if (!frontend && !tiny)
        {
          rst.addColumn(new Column({caption: L("lcl_vis_contactperson"), content: "pers_naam"}));
          rst.addColumn(new Column({caption: L("lcl_phone"), content: "telf_nr", combine: true, xhasActions: true}));
        }

        if (!tiny)
        {
          if (!backo || S("bez_bo_orderby") == 0)
          {
            rst.addColumn(new Column({caption: L("lcl_vis_visit"), content: "gastheer"}));
            if (S("bez_gastheer_telfnr") == 1)
              rst.addColumn(new Column({caption: L("lcl_phone"), content: "gastheer_telf_nr", combine: true}));
          }
          else
          {
            rst.addColumn(new Column({caption: L("lcl_vis_name"), content: fncolContact, colName: "fncolContact"}));
            rst.addColumn(new Column({caption: L("lcl_vis_company"), content: "bez_bedrijf", nowrap: true, tooltip: "res_ruimte_omschrijving", combine: !tiny}));
          }
          rst.addColumn(new Column({caption: L("lcl_room"), content: fncolRuimte, colName: "fncolRuimte", nowrap: true, tooltip: fncolResRuimteOmschrijving}));
          if (more_actions_exist) {
              rst.addColumn(new Column({caption: L("lcl_action"), content: "actie", combine: true}));
          }

          rst.addColumn(new Column({caption: L("lcl_descr"), content: fncolOmschrijving, colName: "fncolOmschrijving"}));
          rst.addColumn(new Column({caption: L("lcl_vis_remark"), content: fncolOpmerking, colName: "fncolOpmerking", colText: L("lcl_remark"), combine: true}));
        }

        if (frontend && !tiny)
        {
          rst.addColumn(new Column({caption: L("lcl_contact"), content: "pers_naam"}));
        }

        function fnColRemote(oRs)
        {
          var bez_flags = oRs("bez_bezoekers_flags").Value;
          if ((bez_flags & S("bez_set_remote_flags")) == S("bez_set_remote_flags"))
              return L("lcl_bez_isremote");
          return L("lcl_bez_notremote");
        }

        if (!groupbez && S("bez_set_remote_flags") > 0 && afspr_key > 0)
            rst.addColumn(new Column({caption: L("lcl_bez_remote"), content: fnColRemote, colName: "fnColRemote", align: "center"}));

        if (!groupbez && anyflex)
          rst.addColumn(new Column({caption: flexlabel, content: "flex"}));

        if (!groupbez && backo) // Ook badgenr-edit en aanmeld/afmeld vinkjes
        {
          if (S("vis_bo_uses_badgenrs") == 1)
          {
            rst.addColumn(new Column({caption: L("lcl_vis_badgenr"), content: fncolBadgenr, colName: "fncolBadgenr"}));
          }

          if (outputmode == 0 && (S("vis_badgeprint_enable") & 2) == 2)
          {
            var captionVisBad = I("fa-id-card fa-2x");
            rst.addColumn(new Column({caption: captionVisBad, content: fncolPrintBadge, colName: "fncolPrintBadge", align: "center"}));
          }
        }
      }

      if (groupbez >= 1 && groupbez <= 6)  // groeperingen
      {
        var captionGroup = "";
        switch (groupbez)
        {
          case 1: captionGroup = L("lcl_district"); break;
          case 2: captionGroup = L("lcl_location"); break;
          case 3: captionGroup = L("lcl_building"); break;
          case 4: captionGroup = L("lcl_month"); break;
          case 5: captionGroup = L("lcl_week"); break;
          case 6: captionGroup = L("lcl_day"); break;

        }
        rst.addColumn(new Column({caption: captionGroup, content: "alg_omschr"}));
        rst.addColumn(new Column({caption: L("lcl_vis_number_vis"), content: "sum_visitors", datatype: "number", total: true}));
        rst.addColumn(new Column({caption: L("lcl_vis_number_checkin"), content: "sum_checkin", datatype: "number", total: true}));
        rst.addColumn(new Column({caption: L("lcl_vis_number_checkout"), content: "sum_checkout", datatype: "number", total: true}));
        rst.addColumn(new Column({caption: L("lcl_vis_number_park"), content: "sum_parking", datatype: "number", total: true}));
      }

      // add multibadge action only if appointment canBadge
      if (!groupbez && this_bez_afspraak.canBadge)
      {
            rst.addAction({ action: "resMultiPrint", caption: L("lcl_print"), single: false, multi: true, multiOnce: true});
      }

      // Acties, niet bij tiny (keuze) en minfo
      if (!minfo && !tiny)
      {
        if (!groupbez)
        {
          rst.addAction({ action: "bezEdit", caption: L("lcl_edit"), isDefault: true});
          rst.addAction({ action: "bezDelete", caption: L("lcl_delete"), enabler: "eDelete", single: true, multi: true, multiOnce: true});
          if ( S("puo_uid") && S("puo_pwd") && S("bez_can_send_sms") && backo )
              rst.addAction({ action: "bezSendSms", caption: L("lcl_bez_send_sms"), single: true, multi: false });
          var canWriteProp = authparams && authparams.ALGwritelevel < 9 && authparams.PRSwritelevel < 9;
          if (((S("bez_show_progress_prop") & 2) == 2) && canWriteProp)
            rst.addAction({ action: "bezProgressProp", caption: L("lcl_bez_reg_progress_prop"), single: true, multi: false });
          if (!frontend && S("vis_allow_check_all") == 1)
          {   // Door enablee: NotExist effectied alleen multi
              rst.addAction({ action: "bezCheckIn", caption: L("lcl_bez_sign_in"), enabler: "NotExist", multi: true, onlyMulti: true, multiOnce: true });
              rst.addAction({ action: "bezCheckOut", caption: L("lcl_bez_sign_out"), enabler: "NotExist", multi: true, onlyMulti: true, multiOnce: true });
          }
        }
        else
        {
          rst.addAction({ action: "afsprEdit", caption: L("lcl_edit"), isDefault: true});
          rst.addAction({ action: "afsprEditMulti", caption: L("lcl_bez_multi_edit"), enabler: "eEditMulti", single:false, multi: true, multiOnce: true});
        }
      }

      if (!groupbez && gebouw_toon_email)
        rst.addAction({ action: "bezSendMail", caption: L("lcl_bez_mail_send"), multi: true, multiOnce: true });

      var count = rst.processResultset();
%>
      <iframe src="../Shared/empty.asp" id=hiddenFrame name=hiddenFrame style="display:none"></iframe>
    </body>
  </html>
<%
}
%>