<% /*
     $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       search for visitors with the given regio key
        dist_key        search for visitors with the given district key
        loc_key         search for visitors with the given location key
        bld_key         search for visitors with the given building key
        flr_key         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)
                                         99) // (afspraak) (frontoffice) Lijkt me vervallen (= !groupbez)
        bezPark         search 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

    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/json2.js" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      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.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 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 = params.regio_key;
  var dist_key = params.dist_key;
  var loc_key = params.loc_key;
  var bld_key = params.bld_key;
  var flr_key = params.flr_key;
  var requestor_key = params.requestor_key;
  var host_key = params.host_key;
  var dep_key = params.dep_key;
  var groupbez = params.groupbez;
  var bezPark  = params.bezPark;
  var bezExpect = params.bezExpect;
  var bezInside = params.bezInside;
  var bezDepart = params.bezDepart;
  var bezClosed = params.bezClosed;

  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 bez_kenmerk_volgnr > 900"
          //+ "   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();

%>

<html>
 <head>
<%
    if (!params.noHeader)
        FCLTHeader.Generate({ outputmode: outputmode });
%>
  <script type="text/javascript">
    urole = "<%=urole%>";
    contactonly = <%=params.contactonly?1:0%>;
    var todayString = "<%=toDateString(new Date())%>";
    var hasKenmerk = (<%=hasKenmerk%> != 0);
    var s_vis_remark = <%=S("vis_remark")%>;

  </script>
 </head>
 <body id="listbody">
<%
      if (!afspr_key && bezPark)
      {
        var sql_having = " having (COUNT (rd.res_rsv_deel_key) > 0)";
      } else {
        var sql_having = "";
      }

      if (!groupbez) // elke individuele bezoeker
      { // geen management info => fe, fo en bo
        sql = "SELECT a.bez_afspraak_key afspr_key"
            + ", " + "a.bez_afspraak_datum"
            + ", b.bez_afspraak_naam"
            + ", b.bez_afspraak_bedrijf bez_bedrijf"
            + ", b.prs_contactpersoon_key"
            + ", b.prs_perslid_key"
            + ", " + S("prs_pers_string") + " pers_naam"
            + ", a.bez_afspraak_gastheer gastheer"
            + ", " + (S("vis_afspraak_host_uses_keys") & 1 == 1
                     ? "COALESCE (p2.prs_perslid_telefoonnr, p2.prs_perslid_mobiel)"
                     : "a.bez_afspraak_telefoonnr"
                     ) + " gastheer_telf_nr"
            + ", COALESCE(p.prs_perslid_telefoonnr, p.prs_perslid_mobiel) telf_nr"
            + ", COALESCE(res_ruimte_groep, a.bez_afspraak_ruimte) ruimte"
            + ", a.bez_afspraak_opmerking"
            + ", b.bez_bezoekers_opmerking"
            + ", a.bez_afspraak_eind"
            + ", "+lcl.xsql('t.bez_actie_omschrijving', 't.bez_actie_key')+ " actie"
            + ", t.bez_actie_flags"
            + ", b.bez_bezoekers_flags"
            + ", b.bez_bezoekers_done"
            + ", b.bez_bezoekers_out "
            + ", l.alg_locatie_omschrijving loc_omschr"
            + ", b.bez_bezoekers_key bez_key"
            + ", COALESCE(rd.res_rsv_deel_key, 0) rsv_deel_key"
            + ", b.bez_bezoekers_pasnr badgenr"
            + ", a.bez_afspraak_datum" // just for sorting
            + ", " + lcl.xsqla('rr.res_ruimte_omschrijving', 'rr.res_ruimte_key')
            + ", fac.DatumTijdPlusUitvoerTijd(SYSDATE, " + S("vis_expire") + ", 'DAGEN') tExpire"
            + ", res_rsv_ruimte_omschrijving"
            + ", COALESCE(org.alg_gebouw_code, org.alg_terreinsector_code) || ' ' || COALESCE(org.alg_gebouw_naam, org.alg_terreinsector_naam) code";

        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
        }

        sql += ", (SELECT COUNT (ins_deel_key)"
             + "     FROM (SELECT i.ins_deel_key"
             + "                , i.ins_alg_ruimte_key"
             + "             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"
             + "             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"
             + "       OR x.ins_alg_ruimte_key = b.prs_contactpersoon_key) 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 (groupbez == 1) // district (management info)
      {
        sql = "SELECT d.alg_district_omschrijving alg_omschr"
            + ", COUNT(*) sum_visitors"
            + ", 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(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 3) // gebouw (management info)
      {
        sql = "SELECT g.alg_gebouw_omschrijving alg_omschr"
            + ", COUNT(*) sum_visitors"
            + ", 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(rd.res_rsv_deel_key) sum_parking";
      }

      if (groupbez == 5) // Week (management info)
      {
        sql = "SELECT TO_CHAR(a.bez_afspraak_datum, 'YYYY-IW') alg_omschr"
            + ", COUNT(*) sum_visitors"
            + ", 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(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)
                 ? ", " + l_alg_v_onroerendgoed_gegevens + " og"
                 : "");
      }

      sql += ", res_rsv_deel rd"
           + ", res_deel d"
           + ", ins_deel id"
           + ", alg_v_allonrgoed_gegevens org"
           + " 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)
             ? " 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(+)";
      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;

      // 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") > 1;

      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 && 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)
        {
          if (backo)
          {
            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 && !dist_key)
        {
            sql += " AND d.alg_regio_key = " + regio_key + " ";
        }
        else if (!afspr_key && dist_key && !loc_key)
        {
            sql += " AND d.alg_district_key = " + dist_key + " ";
        }
        else
        {
          if (authparams.ALGreadlevel > -1 && loc_key)
            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)
           sql += " AND a.alg_locatie_key = " + loc_key;
        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)
        {
          if (!afspr_key && bld_key)
          {
            sql += " AND og.alg_gebouw_key = " + bld_key;
            if (flr_key)
                sql += " AND og.alg_verdieping_key = " + flr_key;
          }
          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 + ")"
            + ")";
        sql+= " AND a.bez_afspraak_datum >= SYSDATE-" + S("vis_user_history");
      }

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

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

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

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

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

      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") <= tNow && !fronto && !minfo && !backo && (!(excel || print)))
          if (frontend && oRs("bez_afspraak_eind") <= tNow && (!(excel || print)))
            class1 = "unauthorized";
        }
        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 authorized = 0; // nooit geautoriseerd tot afmelden
          if (backo) authorized = oRs("authorized").Value;

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

      function fnrowActionEnabler(oRs)
      {
        var tVan = 0;
        var tExpire = 0;
        if (!minfo)
        {
          tVan = oRs("bez_afspraak_datum").Value;
          tExpire = oRs("tExpire").Value;
        }

        var aantaldone = oRs("aantaldone").Value;
        var eEdit = (fronto || backo || (tVan > tExpire));
        var eDelete = (fronto || (tVan > tExpire)) && aantaldone == 0;  // backo in elk geval niet
        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)
          {
            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 IN ('A', 'P', 'C')"
                 + " AND i.ins_alg_ruimte_key = " + (oRs("prs_perslid_key").value? oRs("prs_perslid_key").value : oRs("prs_contactpersoon_key").value)
                 + " ORDER BY ins_deel_omschrijving";
            oRsC = Oracle.Execute(sqlC);
            while (!oRsC.eof)
            {
              icontxt += (icontxt != ""? "\n" : "") + safe.htmlattr(oRsC("ins_deel_omschrijving").value);
              oRsC.MoveNext();
            }
          }
          icon = "<img class='lendobj' src='../Pictures/uitlenen.png'" + (icontxt != ""? " alt='" + icontxt : "") + "'>";
        }

        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/prs/" + (oRs("prs_contactpersoon_key").value? "prs_contactpersoon.asp" : "prs_perslid.asp")
                   + "?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 fncolOpmerking(oRs)
      {
        var txt = oRs("bez_afspraak_opmerking").value||"";
        if (oRs("bez_bezoekers_opmerking").value)
            txt += "\n"+safe.html(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="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 '<i class="fa fa-car fa-lg" id="park" title="' + oRs("code").value + '"></i>';
            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="fa fa-square-o fa-lg ilbutton"'
                      + (oRs("authorized").value == 1
                        ? ' OnClick="doCheckIn(event, ' + oRs("bez_key").value + ', 0);"'
                          + ' title="' + L("lcl_vis_register") + '"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '></span>';
          }
            else
                content = "&nbsp;";
        }
        else
        { // visitor is already inside
          if (outputmode == 0)
              content = '<span id="CHDin' + oRs("bez_key").value + '"'
                      + ' class="fa fa-check-square-o fa-lg 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")) + ')"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '></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="fa fa-square-o fa-lg ilbutton"'
                      + (oRs("authorized").value == 1
                         ? ' OnClick="doCheckOut(event, ' + oRs("bez_key").value + ', 0);"'
                           + ' title="' + L("lcl_vis_todo") + '"'
                         : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '></span>';
            else
                content = "&nbsp;";
        }
        else
        {
          if (outputmode == 0)
              content = '<span id="CHOut' + oRs("bez_key").value + '"'
                      + ' class="fa fa-check-square-o fa-lg 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")) + ')"'
                        : ' OnClick="FcltMgr.stopPropagation(event);"')
                      + '></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="fa fa-id-badge fa-lg 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);"')
             + '></span>';
      }

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

      var xparams = "";
      if (groupbez && groupbez != 99) // minfo
      {
        xparams = {keyColumn: "alg_omschr", // Dummy
                  sql: sql,
                  ID: "beztable",
                  noPrint: noPrint,
                  filterParams: params,
                  outputmode: outputmode,
                  showAll: showall,
                  rowActionEnabler: fnrowActionEnabler};
      }
      else
      {
        var buttons = [];
        if (!tiny)
        {
          if (authparams.ALGwritelevel < 9)
          {
              if (urole == 'bo') // Krijgt de kans een pool-reservering te kiezen
              {
                  var addurl = "bez_afspraak_bo_new.asp?loc_key=" + (loc_key||-1);
                  if (params.contactonly)
                    addurl += "&contactonly=1";
                  var action = "FcltMgr.openModalDetail('" + addurl + "', '" + L("lcl_add") + "', {callback: bezPoolCallback} )"
              }
              else
              {
                  var addurl = "appl/bez/bez_afspraak.asp?urole=" + urole;
                  if (params.contactonly)
                    addurl += "&contactonly=1";
                  var action = "FcltMgr.openDetail('" + addurl + "', '" + L("lcl_add") + "')";
              }
              var buttons = [{ icon: "plus.png", title: L("lcl_add"), action: action }];
          }
        }

        xparams = {keyColumn: "bez_key",
                    rowClass: fnrowClass,
                    rowData: fnrowData,
                    sql: sql,
                    noPrint: noPrint,
                    summaryShow: (tiny ? function () {} : null),
                    ID: "beztable"+(tiny?"tiny":""),
                    flexModule: "BEZ",
                    flexId: "bez_key",
                    filterParams: params,
                    outputmode: outputmode,
                    showAll: showall,
                    showProperties: showProperties,
                    rowActionEnabler: fnrowActionEnabler,
                    buttons: buttons,
                    mobile: params.mobile
                    };
      }

      if (!tiny)
        xparams.title = L("lcl_vis_visitors");

      var rst = new ResultsetTable(xparams);

      // Kolommen
      if (!groupbez || groupbez == 99)
      {
        if (backo) {
          var captionResOk = "<i class='fa fa-sign-in fa-lg'></i>";
          rst.addColumn(new Column({caption: (outputmode == 0 ? captionResOk : L("lcl_vis_inside")), content: fncolRegVisit, align: "center"}));

        }
        if (!tiny && !groupbez)
        {
          // 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: fncolDate}));
          }
          rst.addColumn(new Column({caption: L("lcl_time"), content: "bez_afspraak_datum", datatype: "time"}));

          if (urole!="fe" && S("vis_checkout_enable") == 1)
          {
            var captionVisBad = "<i class='fa fa-sign-out fa-lg'></i>";
            rst.addColumn(new Column({caption: (outputmode == 0 ? captionVisBad : L("lcl_vis_departed")), content: fncolSignOutVisit, align: "center"}));
          }
          rst.addColumn(new Column({caption: L("lcl_to"), content: "bez_afspraak_eind", datatype: "time"}));
        }
        if (!groupbez)
        {
          if (!backo || S("bez_bo_orderby") == 0)
          {
            rst.addColumn(new Column({caption: L("lcl_vis_name"), nowrap: true, content: 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_host"), 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 class="fa fa-car fa-lg"></i>' : L("lcl_parking_caption"));
            rst.addColumn(new Column({caption: parkcaption, content: fncolPark, customSort: fncolParkSort, align: "center" }));
          }
          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_host"), 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}));
            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: "ruimte", nowrap: true, tooltip: "res_ruimte_omschrijving"}));
          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: "res_rsv_ruimte_omschrijving" }));
          rst.addColumn(new Column({caption: L("lcl_vis_remark"), content: fncolOpmerking, combine: true}));
        }

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

        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 (S("bez_set_remote_flags") > 0 && afspr_key > 0)
            rst.addColumn(new Column({caption: L("lcl_bez_remote"), content: fnColRemote, align: "center"}));

        if (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}));
          }

          if (outputmode == 0 && (S("vis_badgeprint_enable") & 2) == 2)
          {
            var captionVisBad = "<i class='fa fa-id-card fa-lg'></i>";;
            rst.addColumn(new Column({caption: captionVisBad, content: fncolPrintBadge, align: "center"}));
          }
        }
      }

      if (groupbez && groupbez != 99)  // 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"}));
        rst.addColumn(new Column({caption: L("lcl_vis_number_park"), content: "sum_parking", datatype: "number"}));
      }

      // Acties, niet bij tiny (keuze) en minfo
      if (!minfo && !tiny)
      {
        rst.addAction({ action: "bezEdit", caption: L("lcl_edit"), isDefault: true});
        rst.addAction({ action: "bezDelete", caption: L("lcl_delete"), enabler: "eDelete"});
        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, multiOnce: true });
            rst.addAction({ action: "bezCheckOut", caption: L("lcl_bez_sign_out"), enabler: "NotExist", multi: true, multiOnce: true });
        }
      }

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