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

    File:               res_search_plan_room_v2.asp
    Remark:             Toon ruimte planbord
    Parameters:
    Context:            vanuit res_search.asp
*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../shared/iface.inc" -->
<!-- #include file="../Shared/discxalg3d.inc"-->
<!-- #include file="res_plan_room_v2.inc" -->
<!-- #include file="res.inc" -->
<%
FCLTHeader.Requires({plugins: ["jQuery"],
                        js  : ["jquery-ui.js"],  // Voor slepen
                        css : ["../res/res.css"]});

var initcollapsed = getQParamInt("initcollapsed", 0) == 1;
var collapseThreshold = getQParamInt("collapsethreshold", 0); // klap automatisch open als er maximaal zoveel regels zijn.

var res_ruimte_key = getQParamInt("res_ruimte_key", -1); // Filter specifieke vergaderzaal
var vis = getQParamInt("vis", 0);
var srtact = getFParamInt("srtact", -1);
var autosearch = getFParamInt("autosearch", 0) == 1;

var urole = getQParamSafe("urole");
var autfunction = "";
switch(urole)
{
  case "fe": autfunction = "WEB_RESUSE";
             break;
  case "fo": autfunction = "WEB_RESFOF";
             break;
  case "bo": autfunction = "WEB_RESBOF";
             break;
  case "mi": autfunction = "WEB_RESBAC";
             break;
}
var authparams = user.checkAutorisation(autfunction);

//dateoffset wordt voor deeplinking gebruikt!(?)
dateoffset = getQParamInt("dateoffset",0)*24*60*60*1000;
var defDate = new Date();
defDate.setDate(defDate.getDate() + dateoffset);

// Bij wijze van uitzondering mogen date_from en date_to ook uit de QueryString komen voor deeplinking
var date_from = getQParamDate("date_from", getFParamDate("date_from", defDate));
var date_to = getQParamDate("date_to", getFParamDate("date_to", date_from));

var samedate = (date_from.midnight().getTime() == date_to.midnight().getTime());
var ruimtecat = getFParamIntArray("roomcatmulti", []); // Ruimte soort catalogus
var act_key_arr = getFParamKeyArray("act", []);
if (act_key_arr.length > 0)
{ // Voeg de disciplines van de activiteit aan de ruimtecatalogus toe.
  var sql = "SELECT res_discipline_key"
          + "  FROM res_activiteitdiscipline"
          + " WHERE res_activiteit_key IN (" + act_key_arr.join(", ") + ")";
  var oRs = Oracle.Execute(sql);
  while (!oRs.eof)
  {
    ruimtecat.push(oRs("res_discipline_key").value);
    oRs.MoveNext();
  }
  oRs.Close();
}

var fnStep;
if (getFParam("fnStep", ""))
{
    fnStep = "parent.fnStepPlanbord";
}

// Bereken dynamisch breedte blokjes
// PAS OP: identiek houden aan res_plan_room_v2.inc!
var width_px = getQParamInt("width_px", 1024);
var nr_days = Math.round(1+(date_to.midnight() - date_from.midnight())/24/60/60/1000);
hour_px = res.hour_px(width_px - 400, nr_days);
%>

<html style="overflow: scroll">
  <head>
<%  FCLTHeader.Generate(); %>
<%  // Ruimtes mogen alleen horizontaal gewijzigd worden, je mag geen andere ruimte kiezen in het planbord
    // Dat heeft mogelijk veel te veel consequenties
%>
    <script type="text/javascript">
      <% // TODO: Wel erg hardcoded
        var extern_flex = customerId + " gebruiker: " + user.naam()
                         + "\nE-mail:" + user.prs_perslid_email()
                         + "\n" + customerId + " kostenplaats: " + user.kpn_string();
      %>
      var extern_flex = "Flex voor externen=<%=safe.jsstring(extern_flex)%>";

$(function() {});

      function res_print()
      {
         FcltMgr.setHeaderExtraTitle("<%=toDateString(date_from)%>");
         window.print();
      }

      function res_change()
      {
          if (typeof tijdbalken === "undefined") { // Geen tijdbalken, geen change mogelijk; disable knop
            return true;
          }
          var tb = tijdbalken[0];
          var hour_px = tb._unit_px() * tb._units_hour;
          var blokje = (hour_px * <%=safe.jsfloat(S("res_h"))%>);
          var startx; // start positie van het slepen (left);
          var starty; // start positie van het slepen (top);
          var x, y;
          var element = $('div.gepland').not('.overflowleft,.overflowright,.extern_readonly,.res_blok');
          element.draggable({
              cursor: 'crosshair',
              containment: false,
              addClasses: false,
              opacity: 0.75,
              revert: true,
              start: function (event, ui) {
                  window.beingdragged = true; /* to prevent onclick */
                  $(ui.helper).css({
                      width: $(this).css("width"),
                      height: $(this).css("height")
                  });
                  x = event.originalEvent.pageX;
                  y = event.originalEvent.pageY;
                  startx = ui.offset.left; // start positie van het slepen (left);
                  starty = ui.offset.top; // start positie van het slepen (top);
              },
              drag: function (event, ui) {
                  if (x && y && (Math.abs(event.originalEvent.pageX - x) > 5 || Math.abs(event.originalEvent.pageY - y) > 5))
                  {
                      axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
                      element.draggable('option', {
                          'axis': axis
                      });
                      x = y = null;
                  }
              },
              stop: function ()
              {
                  x = y = null;
                  element.draggable('option',
                  {
                      'axis': false
                  });
              },
              helper: 'clone',
              iframeFix: true,
              scroll: true
          });
          $('div.gepland:not(.res_nietvrij,.res_lunchblok,.overflowright,.overflowleft.continueright,.continueleft,.extern,.extern_readonly)').resizable(
                 {
                   handles: 'e, w',
                   ghost: true,
                   start: function (event, ui)
                          {
                            window.beingdragged = true; /* to prevent onclick */
                          },
                   stop: function (event, ui)
                         {
                           var callback = function (tb) {
                             return  function (json)
                                     {
                                       function timestring(timenumber)
                                       {
                                         var hours = parseInt(timenumber, 10);
                                         var minutes = (timenumber - hours) * 60;
                                         return hours + ":" + (minutes < 10 ? "0" : "") + minutes;
                                       }
                                       if (json.message) FcltMgr.alert(json.message);
                                       if (json.info)
                                         FcltMgr.setHeaderExtraTitle(json.info);
                                       else
                                         FcltMgr.setHeaderExtraTitle("");
                                       if (json.success)
                                       {
                                         // widen start and endtime with pre and postcleaning
                                         var $this = $(event.target);
                                         var preclean = Number($this.attr("prc") || 0);
                                         var postclean = Number($this.attr("poc") || 0);
                                         var new_van = Number(json.new_van);
                                         var new_tot = Number(json.new_tot);
                                         $("span.time-from-to", $this).text(timestring(new_van) + "-" + timestring(new_tot));
                                         // count preclean cells + rest cell
                                         new_van -= (preclean + (preclean % tb._unit_length) ? (tb._unit_length - (preclean % tb._unit_length)) : 0);
                                         new_tot += (postclean + (postclean % tb._unit_length) ? (tb._unit_length - (postclean % tb._unit_length)) : 0);

                                         var row = $this.css("grid-area").split("/")[0].trim();
                                         $this.css("grid-area", tb._gridareaposition(row, new_van, new_tot)).css({"left": "", "width": "", "height": ""});
                                         ui.originalElement[0].title="";
                                         ui.originalElement.removeClass(json.removeClass).addClass(json.addClass)
                                       }
                                       else
                                       {
                                         ui.originalElement.css({"left": "", "width": "", "height": ""});
                                       }
                                     }
                           }
                           var dvan = Math.floor((ui.position.left - ui.originalPosition.left) / blokje + 0.5);
                           var dwidth = Math.floor((ui.size.width - ui.originalSize.width) / blokje + 0.5);
                           var elm = ui.originalElement;
                           FcltMgr.stopPropagation(event);
                           //window.beingdragged = false;  doet rsv_click wel
                           var data = { rsv_ruimte_key: elm[0].getAttribute("rsv_key"),
                                          dvan: dvan,
                                          dwidth: dwidth
                                        };
                           <% protectRequest.dataToken("data"); %>
                           $.post("res_update_room.asp",
                                  data,
                                  callback(tb),
                                  "json");
                         }
                 });
          $('div.rc').droppable(
                       { addClasses: false,
                         tolerance: 'pointer',
                         containment: false,
                         drop: function(event, ui)
                               {
                                 // First column of the dropped on row
                                 var jtr = $(this).prevAll("div.labelgrid").first();
                                 // First column of the dragged from row
                                 var dragfrom = $(ui.draggable);
                                 var dragfromrow = dragfrom.prevAll("div.labelgrid").first();
                                 // Externe ruimten mogen niet versleept worden en ruimten mogen niet naar een externe ruimte versleept worden.
                                 if (dragfromrow.hasClass("extern") || jtr.hasClass("extern"))
                                   return;
                                 // Langs welke as wordt er nu verschoven?
                                 // X-as: ruimte blijft hetzelfde (res_ruimte_key blijft hetzelfde)
                                 // Y-as: Tijd blijft hetzelfde (fres_van blijft hetzelfde)
                                 var axis = ui.draggable.draggable("option", "axis");

                                 // LET OP: Het verschoven blok is met of zonder schoonmaaktijd. En schoonmaaktijd wordt in het planbord niet goed bepaald en is altijd 1 blokje
                                 var old_dx = startx - jtr.offset().left;
                                 var new_dx = ui.offset.left - $("div.plantimegrid.first").first().offset().left;
                                 old_dx = old_dx / hour_px + <%=safe.jsfloat(S("res_t1"))%>;
                                 new_dx = new_dx / hour_px + <%=safe.jsfloat(S("res_t1"))%>;
                                 var rsv_ruimte_key = dragfrom.attr("rsv_key"); // nieuwe rsv_ruimte_key
                                 var new_res_ruimte_key = jtr.attr("id"); // nieuwe res_ruimte_key
                                 var old_res_ruimte_key = dragfromrow.attr("id"); // oorspronkelijke res_ruimte_key

                                 // Als er niets gewijzigd is dan modal popup scherm niet tonen
                                 var noChange = (axis == "x" && old_dx == new_dx) || (axis == "y" && new_res_ruimte_key == old_res_ruimte_key)
                                 if (new_res_ruimte_key &&
                                     !noChange)
                                 {
                                   var url = "./res_update_room_drag.asp?rsv_ruimte_key=" + rsv_ruimte_key
                                           + "&res_ruimte_key=" + (axis == "x"? old_res_ruimte_key : new_res_ruimte_key)
                                           + "&preclean=" + ($(ui.draggable).attr("prc") || 0)
                                           + "&fres_van=" + (axis == "y"? old_dx : new_dx); // LET OP: dx is met of zonder schoonmaaktijd. En schoonmaaktijd wordt in het planbord niet goed bepaald en is altijd 1 blokje
                                   FcltMgr.openModalDetail(url,
                                                           "",
                                                           { callback: function (data)
                                                                       {
                                                                         if (data.refresh)
                                                                         {
                                                                           <% if (fnStep)
                                                                                Response.Write(fnStep + "(0, 0, 1)"); // hersubmit vanuit parent
                                                                           %>
                                                                         }
                                                                       }
                                                           }
                                                          );
                                   dragfrom.css({"left": "", "width": "", "height": "", "top": ""});
                                 }
                               }
                       });


          // adjust height en top of resize handles
          $("div.ui-resizable-handle").each(function()
          {
              var $this = $(this);
              $this.css({ top: Math.max((parseInt($this.parent().css("height"), 10) / 2) - 7, 0), height: "15px"})
          });
          $("#btnchange").html(L("lcl_res_edit_inplanbord"))
                         .addClass("noHover")
                         .removeClass("btn_disabled"); // Remove disabled CSS
          return true;                                 // But keep button onClick disabled
      }
<%    if (autosearch && samedate)
      { %>
        $(function()
        {
          res_change();
        });
<%    } %>
    </script>
  </head>

  <body id="planbody">
<%
    var buttons = [];
    if (authparams.PRSwritelevel < 9 && authparams.ALGwritelevel < 9 && samedate)
        buttons.push({ icon: "fa-fclt-edit", title: L("lcl_change"), action: 'res_change()', singlepress: true, id: "btnchange" });
    buttons.push({ icon: "fa-list-ul",  title: L("lcl_res_legenda"), action: 'openLegenda()' });
    buttons.push({ icon: "fa-print",  title: L("lcl_print_table"), action: 'res_print()' });
    if (fnStep)
        buttons.push({ icon: "fa-fclt-refresh", title: L("lcl_refresh"), action: fnStep + "(0, 0)" });

    IFRAMER_HEADER(L("lcl_planboard"), buttons);
%>
    <div id="list">
<%
      var params = { id: "tab_room_sched",
                     res_van: date_from,
                     res_tot: date_to,
                     reg: getFParamInt("regiokey", -1),
                     dist: getFParamInt("districtkey", -1),
                     loc_key_arr: getFParamIntArray("locatiekey", []),
                     bld_key_arr: getFParamIntArray("gebouwkey", []),
                     ver_key_arr: getFParamIntArray("verdiepingkey", []),
                     rui_key_arr: getFParamIntArray("ruimtekey", []),
                     ruimtecat: ruimtecat,
                     srtact: (srtact != -1? srtact : null),
                     act_key_arr: act_key_arr,
                     res_ruimte_key: (res_ruimte_key != -1? res_ruimte_key : null),
                     authparams: authparams,
                     host_key: getFParamInt("sHost_key",-1),
                     contact_key: getFParamInt("sName_key",-1),
                     urole: urole,
                     fnStep: fnStep,
                     width_px: width_px,
                     sort: getFParamSafe("sort", "")
                    };
      var plan_rooms_info = res.plan_rooms_info(params);
      var plan_bezet_info = res.plan_bezet_info(params);
      var nnregels = make_plan_room(plan_rooms_info, plan_bezet_info, params);
%>
    </div>
<%
// Genereer ruimte voor popupje bij kleine planborden
while (nnregels < 8)
{
    Response.Write("<p>&nbsp;</p>");
    nnregels ++;
}
%>
<!-- LEGENDA  -->
<script type="text/javascript">
    function openLegenda()
    {
        var myPosition = "right top+30";
        if (elems.$originalHeaderRow && elems.$originalHeaderRow.length)
            myPosition = "right-15 top+"+(parseInt(elems.$fcltFrameHeader.css("top"))+30);
        params = { width: "auto",
                   resizable: false,
                   position: { my: "right top", at: myPosition },
                   title: L("lcl_res_legenda"),
                   create: FcltMgr.fnCreateCloseButton("div#legenda")
                 }
        $('div#legenda').dialog(params).dialog('open');
        FcltMgr.resized();
    }
</script>
    <div id="legenda" class="legenda" style="display:none">
      <table id="planbordlegenda">
       <tr><td class="res_definitief"><%= L("lcl_def") %></td></tr>
       <tr><td class="res_optie"><%= L("lcl_optie") %></td></tr>
       <tr><td class="res_vervallen"><%= L("lcl_vervallen") %></td></tr>
       <tr><td class="res_afgemeld"><%= L("lcl_afgemeld") %></td></tr>
       <tr><td class="res_blok"><%= L("lcl_blokkade") %></td></tr>
       <tr><td class="res_nietvrij"><%= L("lcl_niet_beschikbaar") %></td></tr>
       <tr><td class="res_definitief_eigen"><%= L("lcl_def_own") %></td></tr>
       <tr><td class="res_optie_eigen"><%= L("lcl_optie_own") %></td></tr>
       <tr><td class="res_extern"><%= L("lcl_reservation_extern") %></td></tr>
       <tr><td class="res_fatalicon res_fatal"><%=I("fa-exclamation-triangle", {fastyle: "fal"})%>&nbsp;<% = L("lcl_dirty") %></td></tr>
<%  if (urole != 'fe') { %>
       <tr><td><%=I("fa-digging", {fastyle: "fal"})%>&nbsp;<% = L("lcl_complains") %></td></tr>
       <tr><td><%=I("fa-projector", {fastyle: "fal"})%>&nbsp;<% = L("lcl_reserved_object") %></td></tr>
       <tr><td><%=I("fa-utensils-alt", {fastyle: "fal"}) + "&nbsp;" + L("lcl_reserved_cons") %></td></tr>
<%  }
    var sql = "SELECT res_activiteit_key"
            + "     , res_activiteit_omschrijving"
            + "     , res_activiteit_color"
            + "  FROM res_activiteit"
            + " WHERE (   res_activiteit_verwijder IS NULL"
            + "        OR res_activiteit_verwijder > SYSDATE)"
            + "   AND res_activiteit_color IS NOT NULL";
    var oRs = Oracle.Execute(sql);
    var css = "";
    var html = "";
    while (!oRs.EoF) {
      css += "[data-custom-color][data-act-key='" + safe.htmlattr(oRs("res_activiteit_key").Value) + "']::before {\n"
           + "  background-color: " + safe.html(oRs("res_activiteit_color").Value) + ";\n"
           + "}\n";
      html += "<tr>"
            + "  <td>"
            + "    <div data-custom-color='true' data-act-key='" + safe.htmlattr(oRs("res_activiteit_key").Value) + "'>"
            + "      <div>" + safe.html(oRs("res_activiteit_omschrijving").Value) + "</div>"
            + "    </div>"
            + "  </td>"
            + "</tr>";
      oRs.MoveNext();
    }
    oRs.Close();
    if (css) {
      Response.Write("<style>\n" + css + "</style>");
      Response.Write(html);
    }
    if (S("res_reservering_flags") > 1)
    {
        for (var flagkey=1; flagkey < S('res_reservering_flags'); flagkey++)
        {
            %><tr class="flg"><td><span class='resflag<%=flagkey%>'><%=(flagkey == 0 ? I("fa-fclt-flag0", {fastyle: "far"}) : I("fa-fclt-flag", {fastyle: "fas"}))%></span>&nbsp;<%=L("lcl_res_flag"+flagkey)%></td></tr><%
        }
    }
%>
 </table>
    </div>
  </body>
</html>
<% ASPPAGE_END(); %>
