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

    Description: Toont verplichtingen (lopende zaken) etc van de jezelf of user prs_key
    Parameters:  prs_key optioneel (anders user_key)
                 melding, reservering, bestelling, afspraak, deel om ongewenste zaken uit te sluiten, default is alles aan
                 vb. deel=0 om geen objecten op te nemen
                 dates, zie onder
                 columns, zie onder

    Note:        De urole (voor vervolgacties) wordt impliciet bepaald door
                 de prs_key: is het de lijst van mezelf, dan ga ik met fe verder,
                 is het de lijst van een ander, dan ga ik met fo verder.

    Note:        bes.inc, mld.inc en res.inc wordt geinclude tbv single source om de statuscode naar statustekst om te zetten.
                 Dat zijn best behoorlijke includes. Die 3 functies zouden naar shared.inc mogen?

    Note:        Naar wens kan met de dates parameter de zichtbaarheid van datumkolommen worden beinvloed (voor widgetportal)
                 Zaken waar je alleen contactpersoon van bent tonen we niet meer (alleen in je lijst met eigen zaken)


*/ %>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../shared/data_recordset.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../shared/rater.inc" -->
<!-- #include file="../bes/bes.inc" -->
<!-- #include file="../mld/mld.inc" -->
<!-- #include file="../res/res.inc" -->
<!-- #include file="fac.inc" -->
<!-- #include file="fac_list.inc" -->
<%
FCLTHeader.Requires( {js: ["jquery-ui.js"]} )

var pkey = getQParamInt("prs_key", user_key);
var outputmode = getQParamInt("outputmode", 0); //  0 = screen, 1 = print, 2 = excel etc
var showall = getQParamInt("showall", 0) == 1;
var embedded = getQParamInt("embedded", 0) == 1;
var asWidget = getQParamInt("asWidget", 0) == 1;

// Wat extra opties om datum kolommen weg te laten als je dat echt zou willen
var faclist_mode = getQParamInt("dates", 1);
// 0  = show expected end date (always)
// &1 = show start date too
// &2 = show last modification date too
// &128 = descending, most recent on top

// En nog wat voor de overige kolommen
var faclist_columns = getQParamInt("columns", 63);
// see use below for mapping on columns

var urole = "?";
if (pkey == user_key)
  urole = "fe";
else
  urole = "fo";

var showmelding     = getQParamInt("melding", 1) == 1;
var showreservering = getQParamInt("reservering", 1) == 1;
var showbestelling  = getQParamInt("bestelling", 1) == 1;
var showafspraak    = getQParamInt("afspraak", 1) == 1;
var showdeel        = getQParamInt("deel", 1) == 1;

function fnstatus(oRs)
{ // Soms is deze statustekst een lcl, soms moet je de status_key gebruiken voor vertaling
  switch (oRs.Fields("xmlnode").Value)
  {
    case "melding":       statusstr = (oRs.Fields("status").Value && (oRs.Fields("status_key").Value == 4 || oRs.Fields("status_key").Value == 7)) ? L("lcl_at_team").format(oRs.Fields("status").Value) : mld.getmldstatustext(oRs.Fields("status_key").Value,oRs.Fields("conceptstatus").Value); break
    case "reservering":   statusstr = (oRs.Fields("bo_status_key").Value == 5 || oRs.Fields("bo_status_key").Value == 6)? res.getbostatustext(oRs.Fields("bo_status_key").Value) : res.getfostatustext(oRs.Fields("status_key").Value); break;
    case "afspraak":      statusstr = fac.localstring("" + oRs.Fields("status").Value); break;  // als lcl beschikbaar
    case "bestelling":    statusstr = bes.getbesbestellingstatustext(oRs.Fields("status_key").Value); break;
    case "deel":          statusstr = L("lcl_geleend_object"); break; // nvt
  }
   return safe.html(statusstr);
}

function fncolType(oRs)
{
  var txt= "??";
  switch (oRs.Fields("xmlnode").Value) {
     case "melding":     txt = L("lcl_complain"); break;
     case "reservering": txt = L("lcl_reservation"); break;
     case "bestelling":  txt = L("lcl_bes_bestelling");  break;
     case "afspraak":    txt = L("lcl_vis_appointment");  break;
     case "deel":        txt = "";  break;  // status vertelt L("lcl_geleend_object")
  }
  return txt + " " + oRs.Fields("item").Value;
}
function fnIcon(oRs)
{
    var icon = "fa-circle"; // default
    if (oRs.Fields("image").Value && !(oRs.Fields("image").Value).match(/fa-/))
       icon = "";  // fotos worden leeg
    else
    {
      if (oRs.Fields("image").Value == null && oRs.Fields("xmlnode").Value == 'reservering')
        icon = "fa-users";  // de systeemdefault voor reserveringen
      else if (oRs.Fields("image").Value == null && oRs.Fields("xmlnode").Value == 'melding')
        icon = "fa-chevron-circle-right";  // de systeemdefault voor meldingen
      else
        icon = oRs.Fields("image").Value;
    }
    return (icon != "" ? I(icon + " fa-lg") : "");
}

// om te bepalen of er al beoordeeld mag worden
function isGereed(pxmlnode, pstatuskey)
{
  var isgereed = false;
  switch (pxmlnode)
  {
    case "bestelling" : var isgereed = (pstatuskey == 1 || pstatuskey == 6 || pstatuskey == 7 || pstatuskey == 8)
                        break;
    case "melding"    : var isgereed = (pstatuskey == 1 || pstatuskey == 5 || pstatuskey == 6)
                        break;
    case "reservering": var isgereed = (pstatuskey == 5 || pstatuskey == 6)
                        break;
  }
  return isgereed;
}

function fnLike(oRs, processParams)
{
  var isRemote = (processParams && processParams.disc_key);

  var likesymbol = "";
  var xmlnode = oRs.Fields("xmlnode").Value;
  var statuskey = oRs.Fields("status_key").Value;
  var bostatuskey = oRs.Fields("bo_status_key").Value;
  // Als xmlmode niet "reservering" is, dan is het zetten van het likesybol alleen afhankelijk van isGereed().
  // Voor xmlmode "reservering" moet het likesymbol worden gezet als (isGereed || v_like).
  var v_like = false;

  if (xmlnode == "reservering")
  {
    // Alleen voor reserveringen extra controle.
    var vandaag = new Date();
    var dteinde = new Date(oRs.Fields("datum_eind").value);
    var flike_days = vandaag.getTime() - dteinde.getTime();
    var flike_past = S("facilities_flike_past") * 1000 * 60 * 60 * 24;
    flike_days = (flike_days < 0 ? flike_past+1 : flike_days); // Als flike_days < 0 dan is de reservering nog niet afgelopen, dus mag nog niet worden beoordeeld
    v_like = (flike_days < flike_past);
  }

  // Wat al beoordeeld is in ieder geval tonen.
  if (oRs.Fields("satisfaction").Value)
    likesymbol = rating.stars(oRs.Fields("satisfaction").Value, {shownone: true, rating: {note: oRs.Fields("satisfaction_op").Value}});
  if ((isGereed(xmlnode, (xmlnode == "reservering"? bostatuskey : statuskey)) || v_like) && oRs.Fields("soort").Value != "2")
  {
    if (pkey == user_key)
    {
      likesymbol = rating.stars(oRs.Fields("satisfaction").Value, {shownone: true, rating: {note: oRs.Fields("satisfaction_op").Value}});
      likesymbol = "<div class='flikelist' onclick='fLike(event, \"" + oRs.Fields("item_key").Value + "\", \"" + oRs.Fields("xmlnode").Value +"\", "+(isRemote?1:0)+")'>" + likesymbol + "</div>";
    }
  }
  return likesymbol;
}

function fnMark(oRs)
{ // aanduiding of de bal bij jou ligt
  var actiecode = oRs.Fields("mark").Value;
  var txt= "";
  switch (oRs.Fields("xmlnode").Value) {
    case "melding":
      if (actiecode & 256) {
        if (outputmode == 0) {
          txt = "<span class='ac256' title='"+L("lcl_mld_actiecodeATT")+"'>" + I("fa-bell", { fastyle: "fas" }) + "</span>";
        } else {
          txt = L("lcl_mld_actiecodeATT");
        }
      } else if (actiecode & 2) {
        if (outputmode == 0) {
          txt = "<span class='ac2' title='"+L("lcl_mld_actiecodeYou")+"'>" + I("fa-bell", { fastyle: "far" }) + "</span>";
        } else {
          txt = L("lcl_mld_actiecodeFE");
        }
      }
      break;
    case "reservering" :
      var icon;
      var cls;
      switch (oRs.Fields("mark").Value) {
        case 0: txt = L("lcl_res_ter_fiat");
                icon = "fa-exclamation-circle";
                cls= "resfiat0";
                break;
        // case 1: alles akkoord: geen aanduiding
        case 2: txt = L("lcl_res_afgewezen");
                icon = "fa-times-circle";
                cls= "resfiat2";
                break;
      }
      if (icon) {
        txt = "<span class='"+cls+"' title='" + safe.htmlattr(txt) + "'>"
            + I(icon+" fa-lg", {"fastyle" : "fas"})
            + "</span>";
      }
      break;
  }
  return txt;
}

function fnExtra1(oRs)
{
  var txt= "";
  switch (oRs.Fields("xmlnode").Value) {
     case "melding":     txt = (oRs.Fields("extra1").Value ? "<span class='mldflag" +  oRs.Fields("extra1").Value + "'>" + I("fa-fclt-flag") + "</span> "+L("lcl_mld_flag"+oRs.Fields("extra1").Value) : "");  break;
     case "reservering": txt = (oRs.Fields("extra1").Value ? "<span class='resflag" +  oRs.Fields("extra1").Value + "'>" + I("fa-fclt-flag") + "</span> "+L("lcl_res_flag"+oRs.Fields("extra1").Value) : "");  break;
     case "afspraak":    txt = (oRs.Fields("extra1").Value ? "<span class='bezflag" +  oRs.Fields("extra1").Value + "'>" + I("fa-fclt-flag") + "</span> "+L("lcl_bez_flag"+oRs.Fields("extra1").Value) : "");  break;
     case "bestelling":
     case "deel":        txt = "";  break;
  }
  return txt;
}
function fnrowData(oRs, processParams)
{
  var data = {module:oRs.Fields("xmlnode").Value, item: oRs.Fields("item").Value};
  if (processParams && processParams.disc_key)
  {
    data.disc_key = processParams.disc_key;
    data.deepurl = oRs.Fields("deepurl").Value;
  }

  return JSON.stringify(data);
}

var recent = new Date();
function fnrowClass(oRs)
{
  var lclass = "";
  var lnow = new Date();
  var lthisdate = new Date(oRs.Fields("datum").Value);
  var xmlnode = oRs.Fields("xmlnode").Value;
  var statuskey = oRs.Fields("status_key").Value;
  var bostatuskey = oRs.Fields("bo_status_key").Value;

  // visuele hint voor de actualiteit
  if (lthisdate.toDateString() == lnow.toDateString()) // Dit is een rare, voor reserveringen is dit een datum in de TZ van de locatie, voor de rest de TZ van de user ..
    lclass += " today";
  else if (xmlnode != "melding" && xmlnode != "bestelling")  // die lopen gewoon, reserveringen en afspraken zijn voorbij of toekomstig, en delen, ach.
  {
    if (lthisdate < lnow)
      lclass += " past";
    else
      lclass += " future";
  }

  if (isGereed(xmlnode, (xmlnode == "reservering"? bostatuskey : statuskey)))
    lclass += " isready";

  if (oRs.Fields("status_key").Value == -1)
     lclass = " listfatal";  // ja, deze overruled de vorige classes

  // Tracking: hoe lang geleden voor het laatst gewijzigd?
  if (oRs.Fields("recentdatum").Value != null)
  {
    var ltrackdate1 = new Date();
    var ltrackdate10 = new Date();
    var ltrackdate100 = new Date();
    var module = oRs.Fields("xmlnode").Value;
    var soort = oRs.Fields("soort").Value;
    var recentlimit = 0;
    if (soort)  lclass += " lzsoort"+soort;  // je weet nooit waar het goed voor is
    switch (module)
    {
      case "bestelling":
      case "deel":
      case "melding":     recentlimit = S("mld_melding_recent");
                          break;
      case "reservering": recentlimit = S("res_reservering_recent");
                          break;
      case "afspraak":    recentlimit = S("bez_bezoekers_recent")
                          break;
    }
    ltrackdate1.setMinutes(recent.getMinutes() - recentlimit);
    ltrackdate10.setMinutes(recent.getMinutes() - recentlimit*12);
    ltrackdate100.setMinutes(recent.getMinutes() - recentlimit*12*2);

    var fac_recent = new Date(oRs.Fields("recentdatum").Value);
    if (fac_recent > ltrackdate1)
    {
      lclass += " updated";
    }
    else if (fac_recent > ltrackdate10)
    {
      lclass += " updated10";
    }
    else if (fac_recent > ltrackdate100)
    {
      lclass += " updated100";
    }
  }
  return lclass;
}

function fnDatum (oRs) {
  var val = oRs("datum").Value;
  if (oRs("xmlnode").Value == "reservering") { // Deze zijn al in de lokale tijdszone
    return toDateTimeString(val, { isLocal: true });
  } else {
    return toDateTimeString(val, { pretty: true });
  }
}

function fnDatumEind(oRs) {
  var val = oRs("datum_eind").Value;
  if (oRs("xmlnode").Value == "reservering") { // Deze zijn al in de lokale tijdszone
    return toDateTimeString(val, { isLocal: true });
  } else {
    return toDateTimeString(val, { pretty: true, noMidnight: true });
  }
}

%>
<html>
  <head>
<%  FCLTHeader.Generate({outputmode: outputmode}) %>
    <script type='text/javascript'>
      function facDetail(row, autolike)
      {
        var facData = JSON.parse(row.getAttribute("ROWDATA"));
        var item_key = row.getAttribute("ROWKEY");
        var module = facData.module;
        switch (module)
        {
          case "melding":
              FcltMgr.openDetail("appl/mld/mld_melding.asp?urole=xx&mld_key=" + item_key, { reuse: true });
              break;
          case "reservering":
              FcltMgr.openDetail("appl/res/res_reservering.asp?urole=<%=urole%>&rsv_ruimte_key=" + item_key, { reuse: true });
              break;
          case "bestelling":
              FcltMgr.openDetail("appl/bes/bes_bestelling.asp?urole=<%=urole%>&bes_key=" + item_key, { reuse: true });
              break;
          case "afspraak":
              FcltMgr.openDetail("appl/bez/bez_afspraak.asp?urole=<%=urole%>&afspr_key=" + item_key, { reuse: true });
              break;
          case "deel":
              FcltMgr.openDetail("appl/ins/ins_deel.asp?urole=<%=urole%>&ins_key=" + item_key, { reuse: true });
              break;
        }
      }

      function fLike (event, itemkey, node, isRemote)
      {
        FcltMgr.stopPropagation(event);
        if (!isRemote)
        {
          FcltMgr.openModalDetail("fac_like.asp?key=" + itemkey + "&node=" + node, L("lcl_fac_like"), {callback: FcltCallbackRefresh});
        }
        else
        {
          var deze = event.srcElement || event.target;
          facDetail($(deze).closest("tr")[0], true);
        }
      }
    </script>
  </head>

  <body id="listbody" class="fac-list-body<%=asWidget ? ' widgetbody' : ''%>">
<%

    if (pkey != user_key)
    {
        // Autorisatiechecks voor als je voor iemand anders kijkt
        var xfunc = user.func_enabled("*", null, null, pkey);
        showmelding = (xfunc.canRead("WEB_MLDFOF") || xfunc.canRead("WEB_MLDBOF"));
        showreservering = (xfunc.canRead("WEB_RESFOF") || xfunc.canRead("WEB_RESBOF"));
        showbestelling = (xfunc.canRead("WEB_BESFOF") || xfunc.canRead("WEB_BESBOF"));
        showafspraak = (xfunc.canRead("WEB_BEZFOF") || xfunc.canRead("WEB_BEZBOF"));
        showdeel = (xfunc.canRead("WEB_INSMAN"));
    }

    var sqln = fac_list_query({
                    showafspraak: showafspraak,
                    showbestelling: showbestelling,
                    showdeel: showdeel,
                    showmelding: showmelding,
                    showreservering: showreservering,
                    pkey: pkey
                  });

    user.auth_required_or_abort(sqln);

    sqln = "SELECT prs_perslid_key"
         + "     , item"
         + "     , item_key"
         + "     , plaats"
         + "     , xmlnode"
         + "     , subtype"
         + "     , soort"
         + "     , datum"
         + "     , datum_eind"
         + "     , detail"
         + "     , status"
         + "     , conceptstatus"
         + "     , satisfaction"
         + "     , satisfaction_op"
         + "     , status_key"
         + "     , recentdatum"
         + "     , bo_status_key"
         + "     , extra1"
         + "     , mark"
         + "     , image"
         + "  FROM (" + sqln + ")";

    if ((faclist_mode & 1) == 1)      // Kolom "Verwacht/gereed".
      sqln += " ORDER by datum"+((faclist_mode & 128) == 128 ? " DESC" : "") + ", xmlnode";
    else if ((faclist_mode & 2) == 2) // Kolom "Recentste actie".
      sqln += " ORDER by recentdatum"+((faclist_mode & 128) == 128 ? " DESC" : "") +", xmlnode";
    else                              // Kolom "Faciliteit".
      sqln += " ORDER by xmlnode, item_key"+((faclist_mode & 128) == 128 ? " DESC" : "") +"";

    var buttons = [];
    if (!embedded)
    {
        var transitParams = buildTransitParam(["melding", "bestelling", "reservering", "afspraak", "deel"]);
        // deze worker negeert de prs_key een laat je eigen stuff zien. Dat is embedded bij iemand anders niet nuttig.
        var calendarurl = "appl/shared/fullcalendar.asp?worker=faclist&prs_key="+pkey+transitParams;
        buttons = [{ icon: "fa-calendar-alt", title: L("lcl_calendar"), action: "FcltMgr.openDetail('" + calendarurl + "', '" + safe.jsstring(L("lcl_prs_frame_facilities")) + "')" }];
    }
    buttons.push({ icon: "fa-columns",  title: L("lcl_scf_columns"), action: "openColumns()"});

    var rst = new ResultsetTable({ sql: sqln,
                                   keyColumn: "item_key",
                                   ID: "fac_list",
                                   tabs_code: "fac_list-" + urole,
                                   rowData: fnrowData,
                                   rowClass: fnrowClass,
                                   title: L("lcl_prs_frame_facilities").format(S("facilitiesfuture")),
                                   showAll: showall,
                                   outputmode: outputmode,
                                   buttons: buttons,
                                   emptySetString: L("lcl_geenfaciliteiten"),
                                   collapsible: true
                                  });

    if ((faclist_columns & 1) == 1)
      rst.addColumn(new Column({caption: "", content: fnIcon, align: "center", colName: "fnIcon"}));
    if ((faclist_columns & 2) == 2)
      rst.addColumn(new Column({caption: (outputmode == 0 ? I("fa-bell", { fastyle: "far" }) : L("lcl_mld_actiecode")), content: fnMark, align: "center", colName: "fnMark"}));
    if ((faclist_mode & 1) == 1)
        rst.addColumn(new Column({caption: L("lcl_myfacilities_date"), content: fnDatum, datatype: "datetime" }));
    rst.addColumn(new Column({caption: L("lcl_faciliteit"), content: fncolType, colName: "fncolType"}));
    rst.addColumn(new Column({caption: L("lcl_descr"), content: "detail"}));
    if ((faclist_columns & 4) == 4)
      rst.addColumn(new Column({caption: L("lcl_vakgroup"), content: "subtype"}));
    if ((faclist_columns & 8) == 8)
      rst.addColumn(new Column({caption: L("lcl_status_at"), content: fnstatus, colName: "fnstatus"}));
    if ((faclist_mode & 2) == 2)
        rst.addColumn(new Column({caption: L("lcl_fac_laatste_actie"), content: "recentdatum", datatype: "datetime", prettydate: true})); // experiment
    var flagpresent = false;
    if (urole == "fo"  || (urole == "fe" && S("fac_flags_visible_for_fe") == 1))
        rst.addColumn(new Column({caption: L("lcl_fac_extra1"), content: fnExtra1, colName: "fnExtra1"}));
    if ((faclist_columns & 16) == 16)
      rst.addColumn(new Column({caption: L("lcl_myfacilities_enddate"), content: fnDatumEind, datatype: "datetime" }));
    if ((faclist_columns & 32) == 32)
      rst.addColumn(new Column({caption: L("lcl_place"), content: "plaats"}));
    if (S("facilities_flike_past") >= 0)
        rst.addColumn(new Column({caption: L("lcl_fac_oordeel"), content: fnLike, align: "center", colName: "fnLike"}));

    rst.addAction({ action: "facDetail", caption:L("lcl_edit"), isDefault: true });

    var cnt = rst.processResultset();

%>
  </body>
</html>
<% ASPPAGE_END(); %>
