<% /*
     $Revision$
     $Id$

    File:               res_list_ppi.inc
    Description:        Geef een overzicht van de performance prestatie indicator van reserveringen,
                        die voldoen aan de gegeven 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 orders which meets with the given requirements
        datefrom        search for reservations at the selected date-month-year
        dateto          search for reservations at the selected date-month-year
        dist_key        search for reservations for the selected district
        loc_key         search for reservations for the selected location
        bld_key         search for reservations for the selected building
        flr_key         search for reservations for the selected floor
        room_key        search for reservations for the selected room
        room_key_arr    search for reservations with the selected room categories/types
        dayschedule     give an overview at day schedule level
        groupres        groupres the reservations by
    Context:            Search action from res_search_ppi.asp form
    Note:
    TODO:

*/
%>

<!-- #include file="../Shared/discxalg3d.inc" -->
<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="./res.inc" -->
<!-- #include file="../Shared/getkenmerksql.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: ["../res/res_list.js"]
                    });

function res_list_ppi(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.datefrom      : date
  // params.dateto        : date
  // params.dist_key      : key
  // params.loc_key       : key
  // params.bld_key       : key
  // params.flr_key       : key
  // params.room_key      : key
  // params.room_key_arr  : array met keys
  // params.dayschedule   : boolean (true | false)
  // params.groupres      : key

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

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

  settings.overrule_setting("res_t1", Math.floor(S("res_t1")));
  settings.overrule_setting("res_t2", Math.floor(S("res_t2") + 0.6));

  // Voor resulttable de globalen zetten; zou nog 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 formString = params.formString;
  var showall = params.showall;

  var datefrom = params.datefrom; // Periode van
  var dateto = params.dateto; // Periode tot
  var dist_key = params.dist_key; // District
  var loc_key = params.loc_key; // Locatie
  var bld_key = params.bld_key; // Gebouw
  var flr_key = params.flr_key; // Verdieping
  var room_key = params.room_key; // Ruimte
  var room_key_arr = params.room_key_arr; // Ruimte categorie array
  var dayschedule = params.dayschedule; // Dagverdeling
  var groupres = params.groupres; // Groepering

%>

  <html>
    <head>
<%
      FCLTHeader.Generate({ outputmode: outputmode });
%>
      <script type="text/javascript">
        var urole = "<%=urole%>";
        var print = (<%=print? 1 : 0%> == 1);
        var excel = (<%=excel? 1 : 0%> == 1);
      </script>

    </head>
    <body id="listbody">

<%
      /***** Build sql *****/
      //var date_sql = "";
      var sql_dis = "";
      var sql_loc = "";
      var sql_bld = "";
      var sql_floor = "";
      var sql_rooms = "";
      var sql_dept = "";
      var sql_account = "";
      var sql_room_key = "";

      // If from and to are given both are used
      // If only one of from and to are give, this is used as a (1) day, not an half open interval
      // 20-10-2009 9:46:28/PF
      datefrom = datefrom || dateto;
      dateto = dateto || datefrom;

      // if both are not given take last month als period
      if (!(datefrom && dateto))
      {
        datefrom = new Date();
        dateto = new Date();
      }
      var ora_date1 = datefrom.beginToSQL();
      var ora_date2 = dateto.beginToSQL();
      var ora_date3 = datefrom.beginToSQL();
      var ora_date4 = dateto.endToSQL();
      //date_sql = " AND beschik.res_reservering_van BETWEEN " + ora_date1 + " AND " + ora_date2;

      if (room_key)
        sql_rooms = " AND ruimte_geg.alg_ruimte_key = " + room_key;
      else if (flr_key)
        sql_floor = " AND ruimte_geg.alg_verdieping_key = " + flr_key;
      else if (bld_key)
        sql_bld = " AND ruimte_geg.alg_gebouw_key = " + bld_key;
      else if (loc_key)
        sql_loc = " AND ruimte_geg.alg_locatie_key = " + loc_key;
      else if (dist_key)
        sql_dis = " AND ruimte_geg.alg_district_key = " + dist_key;

      if (room_key_arr)
        sql_room_key = " AND beschik.res_discipline_key IN (" + room_key_arr.join(",") + ")";

// Leuke functie om voor alle uren een resultaat op te leveren.
// Zie res_list_ppi.inc;7 voor wat er gegenereerd wordt.
var rap_t1_overruled = S("res_rap_t1") < 0;
var rap_t2_overruled = S("res_rap_t2") < 0;
settings.overrule_setting("res_rap_t1", rap_t1_overruled? S("res_t1") : S("res_rap_t1"));
settings.overrule_setting("res_rap_t2", rap_t2_overruled? S("res_t2") : S("res_rap_t2"));

function forhours(fn)
{
    var i;
    var res = []
    // Wel met hele uren rekenen, anders geeft dat hier problemen.
    for (i = Math.floor(S("res_rap_t1")); i < Math.floor(S("res_rap_t2") + 0.6); i++)
        res.push(fn.call(null, i));
    return res;
}
//__Log(forhours(function (h) { return String(h); }));

      var sql = " SELECT beschik.alg_ruimte_key"
              + "      , beschik.res_discipline_key"
              + (dayschedule
                ? "    ," + forhours(function (h) { return "b" + String(h); })
                : "    , ROUND(bezetting,2) bezetting")
              + "      , ROUND(beschikbaar,2) beschikbaar"
              + "      , di.alg_regio_key"
              + "      , l.alg_district_key"
              + "      , l.alg_locatie_key"
              + "      , alg_gebouw_key"
              + "      , alg_verdieping_key"
              + " FROM (SELECT alg_ruimte_key"
              + "            , rarg.res_discipline_key"
              + (dayschedule
                ? ("         ," + forhours(function (h) { return " SUM(n" + String(h) + ") b" + String(h); }))
                : "          , SUM(GREATEST(LEAST(to_number(TO_CHAR(res_rsv_ruimte_tot, 'SSSSS')) / 3600"
                  + "                           , COALESCE(res_ruimte_eindtijd, " + S("res_t2") + ")"
                  + "                           ," + S("res_rap_t2")
                  + "                            )"
                  + "                     ," + (rap_t1_overruled? 0 : S("res_rap_t1")) // Als res_rap_t1 overruled is (geen waarde had) dan GREATEST automatisch 1-ste waarde te laten kiezen.
                  + "                      )"
                  + "           -  LEAST(GREATEST(to_number(TO_CHAR(res_rsv_ruimte_van, 'SSSSS')) / 3600"
                  + "                           , COALESCE(res_ruimte_begintijd, " + S("res_t1") + ")"
                  + "                           ," + S("res_rap_t1")
                  + "                            )"
                  + "                  ," + (rap_t2_overruled? 24 : S("res_rap_t2")) // Als res_rap_t2 overruled is (geen waarde had) dan LEAST automatisch 1-ste waarde te laten kiezen.
                  + "                   )"
                  + "             ) bezetting")
              + "         FROM (SELECT r.res_rsv_ruimte_key"
              + "                    , ra.alg_ruimte_key"
              + "                    , ra.res_alg_ruimte_key"
              + "                    , rr.res_discipline_key"
              + (dayschedule
                ? "                  ," + forhours(function (h) { return "r.n" + String(h); })
                : "")
              + "                    , r.res_rsv_ruimte_van"
              + "                    , r.res_rsv_ruimte_tot"
              + "                    , ra.res_alg_ruimte_aanmaak"
              + "                    , ra.res_alg_ruimte_verwijder"
              + "                    , rr.res_ruimte_begintijd"
              + "                    , rr.res_ruimte_eindtijd"
              + "                 FROM "
              + (dayschedule
                ? "                    res_v_res_dag_bezetting r"
                : "                    res_rsv_ruimte r")
              + "                    , res_ruimte_opstelling ro"
              + "                    , res_ruimte rr"
              + "                    , res_alg_ruimte ra"
              + "                WHERE r.res_rsv_ruimte_verwijder IS NULL"
              + "                  AND r.res_status_fo_key IN (1, 2)"
              + "                  AND r.res_ruimte_opstel_key = ro.res_ruimte_opstel_key"
              + "                  AND ro.res_ruimte_key = rr.res_ruimte_key"
              + "                  AND rr.res_ruimte_key = ra.res_ruimte_key) rarg"
              + "        WHERE res_rsv_ruimte_van BETWEEN " + ora_date3 + " AND " + ora_date4
              + "          AND TO_CHAR(res_rsv_ruimte_van, 'd') >= 2" // --veronderstelt NLS_TERRITORY='AMERICA', 2 is maandag
              + "          AND TO_CHAR(res_rsv_ruimte_van, 'd') <= 6"
              + "          AND TRUNC(res_rsv_ruimte_van) NOT IN (SELECT mld_vrije_dagen_datum FROM mld_vrije_dagen)"
              + "          AND rarg.res_alg_ruimte_aanmaak <= " + ora_date2
              + "          AND (rarg.res_alg_ruimte_verwijder IS NULL"
              + "               OR rarg.res_alg_ruimte_verwijder >= " + ora_date1 + ")"
              + "       GROUP BY alg_ruimte_key"
              + "               , rarg.res_discipline_key) bez"
              + "  ,    (SELECT DISTINCT rr1.res_discipline_key"
                + "                    , ra.alg_ruimte_key"
                + "                    , ((fac.Count_Work_Days(" + ora_date1 + "-1 , " + ora_date2 + "))"
                  + (dayschedule
                    ? ""
                    : "                  * (LEAST(COALESCE(rr1.res_ruimte_eindtijd, " + S("res_t2") + ")"
                      + "                      ," + (rap_t2_overruled? 24 : S("res_rap_t2")) // Als res_rap_t2 overruled is (geen waarde had) dan LEAST automatisch 1-ste waarde te laten kiezen.
                      + "                        )"
                      + "                   - GREATEST(COALESCE(rr1.res_ruimte_begintijd, " + S("res_t1") + ")"
                      + "                            ," + (rap_t1_overruled? 0 : S("res_rap_t1")) // Als res_rap_t1 overruled is (geen waarde had) dan GREATEST automatisch 1-ste waarde te laten kiezen.
                      + "                             )"
                      + "                   - (COALESCE( rr1.res_ruimte_eindtijdblok, 12) - COALESCE( rr1.res_ruimte_begintijdblok,12) )"
                      + "                  )"
                    )
                  + "                    ) beschikbaar"
              + "          FROM res_ruimte rr1"
              + "             , res_alg_ruimte ra"
              + "         WHERE rr1.res_ruimte_key = ra.res_ruimte_key"
              + "           AND ra.res_alg_ruimte_aanmaak <= " + ora_date2
              + "           AND (ra.res_alg_ruimte_verwijder IS NULL"
              + "                OR ra.res_alg_ruimte_verwijder >= " + ora_date1 + ")) beschik"
              + "     , alg_v_ruimte_gegevens_all ruimte_geg"
              + "     , alg_locatie l"
              + "     , alg_district di"
              + " WHERE beschik.alg_ruimte_key = bez.alg_ruimte_key(+)"
              + "   AND beschik.res_discipline_key = bez.res_discipline_key(+)"
              + "   AND beschik.alg_ruimte_key = ruimte_geg.alg_ruimte_key"
              + "   AND ruimte_geg.alg_locatie_key = l.alg_locatie_key"
              + "   AND l.alg_district_key = di.alg_district_key"
              + sql_room_key
              + sql_dis
              + sql_loc
              + sql_bld
              + sql_floor
              + sql_rooms;

      //
      // Alleen gebruikt voor groepering maand of datum of weekdag
      if (groupres >=16)
      {
        var sql_reservering = "SELECT r.res_rsv_ruimte_key"
                            + "     , ra.alg_ruimte_key"
                            + "     , ra.res_alg_ruimte_key"
                            + "     , rr.res_discipline_key"
                            + "     , r.res_rsv_ruimte_van"
                            + "     , r.res_rsv_ruimte_tot"
                            + "     , ra.res_alg_ruimte_aanmaak"
                            + "     , ra.res_alg_ruimte_verwijder"
                            + "     , rr.res_ruimte_begintijd"
                            + "     , rr.res_ruimte_eindtijd"
                            + "  FROM res_rsv_ruimte r"
                            + "     , res_ruimte_opstelling ro"
                            + "     , res_ruimte rr"
                            + "     , res_alg_ruimte ra"
                            + " WHERE r.res_rsv_ruimte_verwijder IS NULL"
                            + "   AND r.res_status_fo_key IN (1, 2)"
                            + "   AND r.res_ruimte_opstel_key = ro.res_ruimte_opstel_key"
                            + "   AND ro.res_ruimte_key = rr.res_ruimte_key"
                            + "   AND rr.res_ruimte_key = ra.res_ruimte_key";

        var sql_sel_periode = "";
        var sql_grp_periode = "";
        if (groupres == 16)
        { // Gebruik hele maanden in het berekenen van het aantal werkdagen.
          sql_sel_periode = "fac.count_Work_Days"
                          + "( DECODE(periode, TO_CHAR(" + ora_date1 + ",'yyyymm'), " + ora_date1 + ",          fac.safe_to_date(periode || '01','yymmdd')) - 1"
                          + ", DECODE(periode, TO_CHAR(" + ora_date2 + ",'yyyymm'), " + ora_date2 + ", last_day(fac.safe_to_date(periode || '01','yymmdd')))"
                          + ")"
          sql_grp_periode = "TO_CHAR(res_rsv_ruimte_van, 'yyyymm')";
        }
        if (groupres == 18 || groupres == 19)
        { // Alle dagen zijn goed. //Is de huidig geselecteerde dag een werkdag.
          sql_sel_periode = "1";   //"fac.count_Work_Days(to_date(werkbaredagen.periode,'yyyymmdd')-1, to_date(werkbaredagen.periode,'yyyymmdd'))";
          sql_grp_periode = "TO_CHAR(res_rsv_ruimte_van, 'yyyymmdd')";
        }

        var sql_bezetting   = "SELECT rarg.alg_ruimte_key"
                            + "     , rarg.res_discipline_key"
                            + "     , " + sql_grp_periode + " periode"
                            + "     , SUM(    LEAST(to_number(TO_CHAR(rarg.res_rsv_ruimte_tot, 'SSSSS')) / 3600, COALESCE(rarg.res_ruimte_eindtijd, " + S("res_t2") +"))"
                            + "          - GREATEST(to_number(TO_CHAR(rarg.res_rsv_ruimte_van, 'SSSSS')) / 3600, COALESCE(rarg.res_ruimte_begintijd," + S("res_t1") +"))"
                            + "          ) bezetting"
                            + "  FROM ("+ sql_reservering + ") rarg"
                            + " WHERE rarg.res_rsv_ruimte_van BETWEEN " + ora_date3 + " AND " + ora_date4;
        // Alleen werkdagen meetellen voor 16:Maand.
        // Ook zaterdag en zondag meetellen voor 18:Weekdag, 19:Datum.
        if (groupres == 16)
        {
          sql_bezetting    += "   AND TO_CHAR(rarg.res_rsv_ruimte_van, 'd') >= 2" // --veronderstelt NLS_TERRITORY='AMERICA', 2 is maandag
                            + "   AND TO_CHAR(rarg.res_rsv_ruimte_van, 'd') <= 6";
        }
        sql_bezetting      += "   AND TO_CHAR(rarg.res_rsv_ruimte_van, 'yyyymmdd') NOT IN"
                                  + "(SELECT to_char(mld_vrije_dagen_datum, 'yyyymmdd')"
                                  + "   FROM mld_vrije_dagen"
                                  + ")"
                            + "   AND rarg.res_alg_ruimte_aanmaak <= " + ora_date2
                            + "   AND (  rarg.res_alg_ruimte_verwijder IS NULL "
                            + "       OR rarg.res_alg_ruimte_verwijder >= " + ora_date1
                            + "       )"
                            + " GROUP BY alg_ruimte_key"
                            + "        , rarg.res_discipline_key"
                            + "        , " + sql_grp_periode;

        var sql_werkperiode = "SELECT werkbaredagen.periode"
                            + "     , " + sql_sel_periode + " werkdagen"
                            + "  FROM (SELECT " + sql_grp_periode + " periode"
                                    + "  FROM res_rsv_ruimte"
                                    + " WHERE res_rsv_ruimte_van BETWEEN " + ora_date3 + " AND " + ora_date4
                                    + " GROUP BY " + sql_grp_periode
                                    + ") werkbaredagen";

        var sql_beschikbaar = "SELECT DISTINCT"
                            + "       rr1.res_discipline_key"
                            + "     , ra.alg_ruimte_key"
                            + "     , sw.periode"
                            + "     , sw.werkdagen * (COALESCE(rr1.res_ruimte_eindtijd, " + S("res_t2") + ") - COALESCE(rr1.res_ruimte_begintijd, " + S("res_t1") + ")) beschikbaar"
                            + "  FROM res_ruimte rr1"
                            + "     , res_alg_ruimte ra"
                            + "     , ("+ sql_werkperiode +") sw"
                            + " WHERE rr1.res_ruimte_key = ra.res_ruimte_key"
                            + "   AND ra.res_alg_ruimte_aanmaak <= " + ora_date2
                            + "   AND (  ra.res_alg_ruimte_verwijder IS NULL"
                            + "       OR ra.res_alg_ruimte_verwijder >= " + ora_date1
                            + "       )";

        var sqlM = "SELECT beschik.alg_ruimte_key"
                 + "     , beschik.res_discipline_key"
                 + "     , ROUND(bez.bezetting,2) bezetting"
                 + "     , ROUND(beschik.beschikbaar,2) beschikbaar"
                 + "     , di.alg_regio_key"
                 + "     , l.alg_district_key"
                 + "     , l.alg_locatie_key"
                 + "     , ruimte_geg.alg_gebouw_key"
                 + "     , ruimte_geg.alg_verdieping_key"
                 + "     , beschik.periode"
                 + "  FROM ("+ sql_bezetting   + ") bez"             // calculate the occupation of the reservable rooms
                 + "     , ("+ sql_beschikbaar + ") beschik"         // calculate the availability of the reservable rooms
                 + "     , alg_v_ruimte_gegevens_all ruimte_geg"
                 + "     , alg_locatie l"
                 + "     , alg_district di"
                 + " WHERE beschik.alg_ruimte_key = bez.alg_ruimte_key(+) "
                 + "   AND beschik.res_discipline_key = bez.res_discipline_key(+)"
                 + "   AND beschik.periode = bez.periode(+)"
                 + "   AND beschik.alg_ruimte_key = ruimte_geg.alg_ruimte_key"
                 + "   AND ruimte_geg.alg_locatie_key = l.alg_locatie_key"
                 + "   AND l.alg_district_key = di.alg_district_key"
                 + sql_room_key
                 + sql_dis
                 + sql_loc
                 + sql_bld
                 + sql_floor
                 + sql_rooms;
      }

      sql = discxalg3d(sql,
                       "beschik.res_discipline_key",
                       "di.alg_regio_key",
                       "l.alg_district_key",
                       "ruimte_geg.alg_locatie_key",
                       "ruimte_geg.alg_gebouw_key",
                       "ruimte_geg.alg_verdieping_key",
                       "ruimte_geg.alg_ruimte_key",
                       autfunction,
                       "");

      sqlM = discxalg3d(sqlM,
                        "beschik.res_discipline_key",
                        "di.alg_regio_key",
                        "l.alg_district_key",
                        "ruimte_geg.alg_locatie_key",
                        "ruimte_geg.alg_gebouw_key",
                        "ruimte_geg.alg_verdieping_key",
                        "ruimte_geg.alg_ruimte_key",
                        autfunction,
                        "");

      if (dayschedule)
      {
        res_colums =  [ [L("lcl_location"), "locatie", "string", false],
                        [L("lcl_res_nr_of_rooms"), "aantal_ruimten", "number", true]];

        res_colums = res_colums.concat(forhours(function (h) { return [String(h) + ":00", "t" + String(h), "float", true]; }));

        select_sql =  ", " + forhours(function (h) { return "ROUND((SUM(b"+String(h)+") / SUM(beschikbaar)) * 100, 2) t"+String(h)+""; })
        //order_by = "13";
      }
      else
      {
        res_colums = [ [L("lcl_location"), "locatie", "string", false],
                       [L("lcl_res_nr_of_rooms"), "aantal_ruimten", "number", true],
                       [L("lcl_res_load_in_hours"), "gebruik_uren", "float", true],
                       [L("lcl_res_available_in_hours"), "beschikbaar_uren", "float", true],
                       [L("lcl_occupation_perc"), "bezetting", "float", true] ];
        select_sql = ", SUM(bezetting) gebruik_uren, SUM(beschikbaar) beschikbaar_uren, ROUND((SUM(bezetting) / SUM(beschikbaar)) * 100, 2) bezetting";
        //order_by = "6";
      }

      if (groupres == 6)
      { // locatie
        res_colums[0][0] = L("lcl_location");
        sql = " SELECT l.alg_locatie_key res_keycolumn"
            + ", l.alg_locatie_omschrijving locatie"
            + ", COUNT(DISTINCT alg_ruimte_key) aantal_ruimten"
            + select_sql
            + " FROM (" + sql + ") data"
            + ", alg_locatie l"
            + " WHERE data.alg_locatie_key = l.alg_locatie_key"
            + " GROUP BY l.alg_locatie_key"
            + ", l.alg_locatie_omschrijving"
            + " ORDER BY l.alg_locatie_omschrijving";
      }
      else if (groupres == 15)
      { // room_cat
        res_colums[0][0] = L("lcl_res_roomcat");
        res_colums[0][1] = "ruimte_categorie";
        sql = " SELECT d.ins_discipline_key res_keycolumn"
            + ", ins_discipline_volgnr"
            + ", "+ lcl.xsql('d.ins_discipline_omschrijving','d.ins_discipline_key') +" ruimte_categorie"
            + ", COUNT(DISTINCT alg_ruimte_key) aantal_ruimten"
            + select_sql
            + " FROM (" + sql + ") data"
            + ", ins_tab_discipline d"
            + " WHERE data.res_discipline_key = d.ins_discipline_key"
            + " GROUP BY d.ins_discipline_key"
            + ", ins_discipline_volgnr"
            + ", "+ lcl.xsql('d.ins_discipline_omschrijving','d.ins_discipline_key')
            + " ORDER BY ins_discipline_volgnr, "+ lcl.xsql('d.ins_discipline_omschrijving','d.ins_discipline_key');
      }
      else if (groupres == 16)
      { // maand
        res_colums =  [ [L("lcl_month"), fnrowMaand, "string", false],
                        [L("lcl_res_load_in_hours"), "gebruik_uren", "float", false],
                        [L("lcl_res_available_in_hours"), "beschikbaar_uren", "float", false],
                        [L("lcl_occupation_perc"), "bezetting", "float", false] ];
        sql = " SELECT periode res_keycolumn"
            + ", SUM(bezetting) gebruik_uren"
            + ", SUM(beschikbaar) beschikbaar_uren"
            + ", ROUND((SUM(bezetting) / SUM(beschikbaar)) * 100, 2) bezetting"
            + " FROM (" + sqlM + ") data"
            + " GROUP BY periode"
            + " ORDER BY periode";
      }
      else if (groupres == 18)
      { // datum
        res_colums =  [ [L("lcl_weekday"), fnrowMaand, "string", false],
                        [L("lcl_res_load_in_hours"), "gebruik_uren", "float", false],
                        [L("lcl_res_available_in_hours"), "beschikbaar_uren", "float", false],
                        [L("lcl_occupation_perc"), "bezetting", "float", false] ];
        sql = " SELECT TO_CHAR(TO_DATE(periode,'yyyymmdd'),'d') res_keycolumn"
            + ", SUM(bezetting) gebruik_uren"
            + ", SUM(beschikbaar) beschikbaar_uren"
            + ", ROUND((SUM(bezetting) / SUM(beschikbaar)) * 100, 2) bezetting"
            + " FROM (" + sqlM + ") data"
            + " GROUP BY TO_CHAR(TO_DATE(periode,'yyyymmdd'),'d')"
            + " ORDER BY TO_CHAR(TO_DATE(periode,'yyyymmdd'),'d')";
      }
      else if (groupres == 19)
      { // datum
        res_colums =  [ [L("lcl_date"), fnrowMaand, "string", false],
                        [L("lcl_res_load_in_hours"), "gebruik_uren", "float", false],
                        [L("lcl_res_available_in_hours"), "beschikbaar_uren", "float", false],
                        [L("lcl_occupation_perc"), "bezetting", "float", false] ];
        sql = " SELECT periode res_keycolumn"
            + ", SUM(bezetting) gebruik_uren"
            + ", SUM(beschikbaar) beschikbaar_uren"
            + ", ROUND((SUM(bezetting) / SUM(beschikbaar)) * 100, 2) bezetting"
            + " FROM (" + sqlM + ") data"
            + " GROUP BY periode"
            + " ORDER BY periode";
      }
      else if (groupres == 10)
      { // gebouw
        res_colums[0][0] = L("lcl_building");
        res_colums[0][1] = "gebouw";
        sql = " SELECT g.alg_gebouw_key res_keycolumn"
            + ", g.alg_gebouw_omschrijving gebouw"
            + ", COUNT(DISTINCT alg_ruimte_key) aantal_ruimten"
            + select_sql
            + " FROM (" + sql + ") data"
            + ", alg_gebouw g"
            + " WHERE data.alg_gebouw_key = g.alg_gebouw_key"
            + " GROUP BY g.alg_gebouw_key"
            + ", g.alg_gebouw_omschrijving"
            + " ORDER BY g.alg_gebouw_omschrijving";
      }
      else if (groupres == 5)
      { // district
        res_colums[0][0] = L("lcl_district");
        res_colums[0][1] = "district";
        sql = " SELECT d.alg_district_key res_keycolumn"
            + ", d.alg_district_omschrijving district"
            + ", COUNT(DISTINCT alg_ruimte_key) aantal_ruimten"
            + select_sql
            + " FROM (" + sql + ") data"
            + ", alg_district d"
            + " WHERE data.alg_district_key = d.alg_district_key"
            + " GROUP BY d.alg_district_key"
            + ", d.alg_district_omschrijving"
            + " ORDER BY d.alg_district_omschrijving";

      }
      else if (groupres == 14)
      { // ruimte
        if (dayschedule)
        {
          res_colums =  [ [L("lcl_room"), "ruimte", "string", false] ];

          res_colums = res_colums.concat(forhours(function (h) { return [String(h) + ":00", "t" + String(h), "float", true]; }));
        //select_sql =  ", " + forhours(function (h) { return "ROUND((SUM(b"+String(h)+") / SUM(beschikbaar)) * 100, 2) t"+String(h)+""; })

          sql = " SELECT rg.alg_ruimte_key res_keycolumn"
              + ", rg.alg_ruimte_aanduiding || ' - (' || ("
                + " SELECT MAX("+lcl.xsql('rr.res_ruimte_nr', 'rr.res_ruimte_key')+")"
                + " FROM res_v_aanwezigalg_ruimte rar"
                + ", res_v_aanwezigruimte rr"
                + " WHERE rar.res_ruimte_key = rr.res_ruimte_key"
                + " AND rar.alg_ruimte_key = data.alg_ruimte_key) ||"
                + " (SELECT CASE COUNT(rar.res_ruimte_key)"
                  + " WHEN 1"
                  + " THEN ')'"
                  + " ELSE '...)'"
                  + " END"
                  + " FROM res_v_aanwezigalg_ruimte rar "
                  + " WHERE rar.alg_ruimte_key = data.alg_ruimte_key) ruimte"
              + ", " + forhours(function (h) { return "ROUND((b"+String(h)+" / beschikbaar) * 100, 2) t"+String(h); })
              + " FROM (" + sql + ") data"
              + ", alg_v_ruimte_gegevens_all rg"
              + " WHERE data.alg_ruimte_key = rg.alg_ruimte_key"
              + " ORDER BY 2";
        }
        else
        {
          res_colums =  [ [L("lcl_room"), "ruimte", "string", false],
                          [L("lcl_res_load_in_hours"), "gebruik_uren", "float", true],
                          [L("lcl_res_available_in_hours"), "beschikbaar_uren", "float", true],
                          [L("lcl_occupation_perc"), "bezetting", "float", true]];

          sql = " SELECT rg.alg_ruimte_key res_keycolumn"
              + ", rg.alg_ruimte_aanduiding || ' - (' || ("
                + " SELECT MAX("+lcl.xsql('rr.res_ruimte_nr', 'rr.res_ruimte_key')+") "
                + " FROM res_v_aanwezigalg_ruimte rar"
                + ", res_v_aanwezigruimte rr "
                + " WHERE rar.res_ruimte_key = rr.res_ruimte_key "
                + " AND rar.alg_ruimte_key = data.alg_ruimte_key ) ||"
                + " (SELECT CASE COUNT(rar.res_ruimte_key)"
                  + " WHEN 1 "
                  + " THEN ')'"
                  + " ELSE '...)'"
                  + " END"
                  + " FROM res_v_aanwezigalg_ruimte rar"
                  + " WHERE rar.alg_ruimte_key = data.alg_ruimte_key) ruimte"
              + ", bezetting gebruik_uren"
              + ", beschikbaar beschikbaar_uren"
              + ", ROUND((bezetting / beschikbaar) * 100, 2) bezetting"
              + " FROM (" + sql + ") data"
              + ", alg_v_ruimte_gegevens_all rg"
              + " WHERE data.alg_ruimte_key = rg.alg_ruimte_key"
              + " ORDER BY 2";
        }
      }
      else
      {
        sql = sql;
      }

      /***** End build sql *****/

        /*****************************************************
         * Callback functies ResultsetTable for FE and FO only
         ****************************************************/

        function fnrowMaand(oRs)
        {
          var content = oRs("res_keycolumn").value;
          if (groupres == 16 || groupres == 19)
          {
            var jaar_int  = parseInt(content.substr(0,4), 10);
            var maand_int = parseInt(content.substr(4,2), 10);
            var dag_int   = parseInt(content.substr(6,2), 10);

            var maand_str = calendar_names.months[maand_int - 1];
            var dag_str   = "";
            if (groupres == 19)
            {
              dag_str = dag_int + " ";
            }
            return dag_str + maand_str + " " + jaar_int;
          }
          else if (groupres == 18)
          {
            var dagnaam = calendar_names.days[content-1];
            return dagnaam;
          }
        }

        var tot_aantal_ruimten = 0;
        var tot_gebruik_uren = 0;
        var tot_beschikbaar_uren =0;
        var totaal = [];
        forhours(function (h) { totaal[h] = 0; })

        function fntotalCalc(oRs)
        {
          if (dayschedule)
          {
            if (groupres == 14)
            {
              tot_aantal_ruimten++;
              forhours(function (h) { totaal[h] = totaal[h] + oRs("t" + String(h)).value });
            }
            else
            {
              var aantal_ruimten = oRs("aantal_ruimten").value;
              tot_aantal_ruimten += oRs("aantal_ruimten").value;
              forhours(function (h) { totaal[h] = totaal[h] + aantal_ruimten * oRs("t" + String(h)).value });
            }
          }
          else
          {
            if (groupres == 14)
              tot_aantal_ruimten++;
            else
              tot_aantal_ruimten += oRs("aantal_ruimten").value;
            tot_gebruik_uren += (oRs("gebruik_uren").value? oRs("gebruik_uren").value : 0);
            tot_beschikbaar_uren += (oRs("beschikbaar_uren").value? oRs("beschikbaar_uren").value : 0);
          }
        }

        function fntotalShow(column, nrlines)
        {
          var result = "";
          switch (column.caption)
          {
              case L("lcl_res_nr_of_rooms"): result = tot_aantal_ruimten; break;
              case L("lcl_res_load_in_hours"): result = safe.displayfloat(tot_gebruik_uren, 2); break;
              case L("lcl_res_available_in_hours"): result = safe.displayfloat(tot_beschikbaar_uren, 2); break;
              case L("lcl_occupation_perc"): result = safe.displayfloat((tot_gebruik_uren / tot_beschikbaar_uren) * 100, 2); break;
              default: result = safe.curr(totaal[parseInt(column.caption, 10)]/tot_aantal_ruimten); break;
          }

          return result;
        }

        /**************************************
         * End callback functies ResultsetTable
         **************************************/
         // Transform decimal limit to friendly times (i18n?)
         var res_rap_t1h = Math.floor(S("res_rap_t1"));
         if (res_rap_t1h < 10) res_rap_t1h = "0" + res_rap_t1h;
         var res_rap_t1m = Math.floor((S("res_rap_t1") - res_rap_t1h)*60);
         if (res_rap_t1m < 10) res_rap_t1m = "0" + res_rap_t1m;
         var res_rap_t1s = res_rap_t1h + ":" + res_rap_t1m

         var res_rap_t2h = Math.floor(S("res_rap_t2"));
         if (res_rap_t2h < 10) res_rap_t2h = "0" + res_rap_t2h;
         var res_rap_t2m = Math.floor((S("res_rap_t2") - res_rap_t2h)*60);
         if (res_rap_t2m < 10) res_rap_t2m = "0" + res_rap_t2m;
         var res_rap_t2s = res_rap_t2h + ":" + res_rap_t2m


         var doTotals = (groupres != 16 && groupres != 18 && groupres != 19)
         var rst = new ResultsetTable({ keyColumn: "res_keycolumn",
                                        ID: "restable",
                                        sql: sql,
                                        totalCalc: (doTotals ? fntotalCalc : null),
                                        totalShow: (doTotals ? fntotalShow : null),
                                        filterParams: params,
                                        outputmode: outputmode,
                                        title: L("lcl_res_PPI_title") + " " + L("lcl_res_PPI_fromto").format(res_rap_t1s, res_rap_t2s),
                                        showAll: showall
                                      });

        // Kolommen [L("lcl_location"), "locatie", "Text"]
        res_colums.length
        for (var i = 0; i < res_colums.length; i++)
        {
          rst.addColumn(new Column({ caption: res_colums[i][0], content: res_colums[i][1], datatype: res_colums[i][2], total: res_colums[i][3] }));
        }

        var count = rst.processResultset();
%>
    </body>
  </html>
<%
}
%>
