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

    File:               res_multi.asp
    Description:        Maak een dialoog om gegevens van een deelreservering
                        repeterend te maken
    Parameters:
        rsv_ruimte_key  bron-deelreservering
    Context:
    Note:
*/
%>
<!--#include file="../Shared/common.inc"-->
<!--#include file="../Shared/iface.inc"-->
<!--#include file="../Shared/selector.inc"-->
<!--#include file="../Shared/calendar.inc"-->
<!--#include file="./res.inc"-->
<%
FCLTHeader.Requires({plugins: ["jQuery"],
                          js: ["date.js"]})


var urole = getQParamSafe("urole");
var frontend = urole == "fe";
var rsv_ruimte_key = getQParamInt("rsv_ruimte_key");
res.res_set_dialect(rsv_ruimte_key);

var this_res = res.func_enabled(rsv_ruimte_key); // wat mocht ik zoal op deze reservering
user.auth_required_or_abort(this_res.couldCreate);
//
%>
<html>
  <head>
<%  FCLTHeader.Generate() %>
<%
    // =========================================
    // Eerst wat info ophalen
    sql = "SELECT rr.res_reservering_key"
        + "     , rr.res_reservering_ispool"
        + "     , rrr.res_rsv_ruimte_van"
        + "     , res_rsv_ruimte_volgnr "
        + "     , r.res_ruimte_vervaldatum"
        + "  FROM res_reservering rr"
        + "     , res_rsv_ruimte rrr"
        + "     , res_ruimte_opstelling ro"
        + "     , res_ruimte r"
        + " WHERE rr.res_reservering_key = rrr.res_reservering_key"
        + "   AND rrr.res_ruimte_opstel_key = ro.res_ruimte_opstel_key(+)"
        + "   AND ro.res_ruimte_key = r.res_ruimte_key(+)"
        + "   AND res_rsv_ruimte_key = " + rsv_ruimte_key;
    oRs = Oracle.Execute(sql);
    // Als de ruimte al vervallen is kun je direct wel stoppen.
    var ruimte_vervaldatum = oRs("res_ruimte_vervaldatum").Value;
    var daysToExpire = null;
    if (ruimte_vervaldatum != null)
    {
      ruimte_vervaldatum = new Date(ruimte_vervaldatum);
      daysToExpire = (ruimte_vervaldatum.midnight().getTime() - new Date().midnight().getTime())/(24*3600*1000);
      if (daysToExpire <= 0)
        abort_with_warning(L("lcl_res_room_expired").format(toDateString(ruimte_vervaldatum)));
    }

    var rrr = { rsv_ruimte_key    : rsv_ruimte_key,
                reservering_key   : oRs("res_reservering_key").Value,
                reservering_ispool: oRs("res_reservering_ispool").Value == 1,
                rsv_ruimte_van    : new Date(oRs("res_rsv_ruimte_van").Value),
                rsv_ruimte_volgnr : oRs("res_rsv_ruimte_volgnr").Value,
                ruimte_vervaldatum: ruimte_vervaldatum
              }
    oRs.Close();
%>
    <script type="text/javascript">
      var earliest_expire_change = new Date(<%=this_res.earliest_expire_change.getTime()%>);
      var frontend = <%=frontend? 1 : 0%> == 1;
<%
      // ============================================
      // maak lijst met bestaande reserveringen
      // ============================================
      var sql = "SELECT res_rsv_ruimte_key"
              + "     , res_rsv_ruimte_van"
              + "     , res_rsv_ruimte_tot"
              + "     , rm.res_rsv_ruimte_volgnr"
              + "     , rm.res_rsv_ruimte_dirtlevel"
              + "  FROM res_rsv_ruimte rm"
              + " WHERE res_reservering_key = " + rrr.reservering_key
              + "   AND res_rsv_ruimte_verwijder IS NULL"
              + " ORDER BY res_rsv_ruimte_van, res_rsv_ruimte_key"

%>
      var res_existing_dates = [0
<%
      var oRs = Oracle.Execute(sql);
      var multidate = false;
      while (!oRs.Eof)
      {
          var vandate = new Date(oRs("res_rsv_ruimte_van")).midnight();
          var totdate = new Date(oRs("res_rsv_ruimte_tot")).midnight();
          if (vandate.getTime() != totdate.getTime())
          {
              multidate = true;
          }
          Response.Write(", " + vandate.getTime());
          oRs.MoveNext;
      }
      oRs.Close();
%>
         ];
<%    if (multidate)
      { %>
        $(document).ready(function () { FcltMgr.closeDetail(window, { cancel: true, warning: L("lcl_res_no_multi_multi") } ) });
        </script>
<%      Response.End;
      } %>

      function EraseDates()
      {
        window.dates = [];
        $("#show_date_from").datepicker('refresh'); // undocumented maar werkt bij 1.7.3
        $("#show_date_to0").html("");

        $("#newDates").empty();
      }

      function fillDateArray(chk_lastmin)
      {
        var np = $("#n_periods").val();
        var nextDate = new Date(parseInt($('#date_from0').val()));
        nextDate.setHours(0, 0, 0, 0);
        var interval = parseInt($("#sel_cycle").val());
        var i;
        var res_new_dates = [];
        var limitDate = null;
<%
        var limit = ((urole == "fe" && S("res_fe_reservering_limiet") > 0)? S("res_fe_reservering_limiet") : S("res_reservering_limiet"))

        // MGE: Als de ruimte vervallen is (daysToExpire <= 0) dan is er hierboven al een abort_with_warning geweest en kom je hier nooit.

        if (daysToExpire != null && daysToExpire >= 0 && daysToExpire < limit)
          limit = daysToExpire - 1; // De vervaldatum niet meerekenen.

        if (limit > 0)
        {
%>
          limitDate = new Date();
          limitDate.setDate(limitDate.getDate() + <%=limit%>);
<%      } %>
        var overflow = false;
        var message = "";
        for (i = 0; i < np; i++)
        {
          nextDate.setDate(nextDate.getDate() + interval);
          var date2 = new Date(nextDate); // zelfde tijdstip gebruiken als rrr.rsv_ruimte_van
          date2 = date2.setFloatHours(new Date(<%=rrr.rsv_ruimte_van.getTime()%>).getFloatHours(), <%=safe.jsfloat(S("res_h"))%>);

          if (chk_lastmin && frontend && earliest_expire_change && date2 < earliest_expire_change)
          {
            message = L("lcl_res_repeat_lastmin_n");
            continue;
          }
          if (limitDate && nextDate > limitDate)
          {
            overflow = true;
            break;
          }
          if ($("#withWeekends:checked").val() == "on" &&
              ($.inArray(nextDate.getTime(), mld_vrije_dagen) > -1 ||
               nextDate.getDay() == 0 ||
               nextDate.getDay() == 6)
             )
          {
            np++;
            continue;
          }
          res_new_dates.push(nextDate.getTime());
        }

        var result = {res_new_dates: res_new_dates, message: message};
        // Alleen als op de "Tonen datums" button (chk_lastmin is true) is geklikt, de melding geven en niet meer bij invoer.
        // Anders moet je minstens twee keer klikken op de button om de datums te tonen.
        if (chk_lastmin && overflow)
          result.message += (message != ""? "<br>" : "") + L("lcl_res_date_limit_reached") + toDateString(limitDate);
        return result;
      }

      function finishFillDates(json, textStatus)
      {
        if (json.message)
          FcltCallback(json, textStatus); // Geef message weer

        var res_new_dates = json.res_new_dates;
        if (res_new_dates)
        {
          for (var j = 0; j < res_new_dates.length; j++)
          {
            //window.dates = res_new_dates; // of merge?
            var exists = false;
            // Dezelfde datums niet opnieuw toevoegen.
            for (var k = 0; k < window.dates.length; k++)
            {
              if (parseInt(window.dates[k], 10) == parseInt(res_new_dates[j], 10))
              {
                exists = true;
                continue;
              }
            }
            if (!exists)
              window.dates.push(res_new_dates[j]); // Merge
          }
          var nextDate = new Date();
          $("#newDates").empty();
          for (var i = 0; i < window.dates.length; i++)
          {
            nextDate.setTime(window.dates[i]);
            $("#newDates").append("<option value=" + nextDate.getTime() + ">" + toDateString(nextDate) + "</option>");
          }

          $("#show_date_from").datepicker('refresh'); // undocumented maar werkt bij 1.7.3
        }
      }

      function fillDates(chk_lastmin, dosubmit)
      {
        var np = $("#n_periods").val();
        if (isNaN(np) || np < 1)
        {
          alert(L("lcl_res_period_error"))
          return;
        }

        var interval = parseInt($("#sel_cycle").val());
        if (interval == 31)
        {
          var nextDate = new Date(parseInt($('#date_from0').val()));
          nextDate.setHours(0, 0, 0, 0);
          var bits = parseInt($("#dayofmonth").val(), 10) + parseInt($("#dayofweek").val(), 10);
          var data = { urole: "<%=urole%>",
                       chk_lastmin: chk_lastmin? 1 : 0,
                       np: np,
                       nextDate: nextDate.getTime(),
                       bits: bits,
                       rsv_ruimte_van: <%=rrr.rsv_ruimte_van.getTime()%>,
                       ruimte_vervaldatum: <%=rrr.ruimte_vervaldatum != null? rrr.ruimte_vervaldatum.getTime() : -1%>,
                       earliest_expire_change: earliest_expire_change.getTime()
                     };
          $.getJSON("get_res_info_ajax.asp?req_info=res_new_dates",
                    data,
                    function(data)
                    {
                      if (chk_lastmin)
                      {
                        finishFillDates(data);
                        if (dosubmit) multi_submit();
                      }
                      else
                        finishCalcEinddatum(data);
                    }
                   );
        }
        else
        {
          var data = fillDateArray(chk_lastmin);
          if (chk_lastmin)
          {
            finishFillDates(data);
            if (dosubmit) multi_submit();
          }
          else
            finishCalcEinddatum(data);
        }
      }

      function finishCalcEinddatum(json, textStatus)
      {
        if (json.message)
          FcltCallback(json, textStatus); // Geef message weer

        var res_new_dates = json.res_new_dates;
        if (res_new_dates)
        {
          var nextDate = new Date();
          nextDate.setTime(res_new_dates[res_new_dates.length - 1]);
          $("#show_date_to0").datepicker("setDate", nextDate);
        }
      }

      function calcEinddatum()
      {
        fillDates(false);
      }

      function finishCalcPerioden(json, textStatus)
      {
        var res_steps = json.res_steps;
        if (res_steps >= 0)
        {
          $("#n_periods").val(res_steps);
        }
      }

      function calcPerioden()
      {
        var periodedagen = new Array();
        var interval = parseInt($("#sel_cycle").val());
        var nextDate = new Date(parseInt($('#date_from0').val()));
        var lastDate = new Date(parseInt($('#date_to0').val()));
        nextDate.setHours(0, 0, 0, 0);
        lastDate.setHours(0, 0, 0, 0);

        if (interval == 31)
        {
          if (nextDate <= lastDate)
          {
            var np = $("#n_periods").val();
            var bits = parseInt($("#dayofmonth").val(), 10) + parseInt($("#dayofweek").val(), 10);
            var data = { urole: "<%=urole%>",
                         np: np != ""? np : 0,
                         nextDate: nextDate.getTime(),
                         lastDate: lastDate.getTime(),
                         bits: bits
                       };
            $.getJSON("get_res_info_ajax.asp?req_info=res_nr_periods",
                      data,
                      finishCalcPerioden
                     );
          }
        }
        else
        {
          nextDate.setDate(nextDate.getDate() + interval);
          while (nextDate <= lastDate)
          {
            if (!($("#withWeekends:checked").val() == "on" &&
                  ($.inArray(nextDate.getTime(), mld_vrije_dagen) > -1 ||
                   nextDate.getDay() == 0 ||
                   nextDate.getDay() == 6)
                 )
               )
            {
              periodedagen.push(nextDate);
            }
            nextDate.setDate(nextDate.getDate() + interval);
          }
          var aantaldagen = periodedagen.length;
          $("#n_periods").val(aantaldagen);
        }
      }

      function onChangePeriod(el)
      {
        if (el.value == 0) // niet periodiek
        {
          $("#n_periods").attr('disabled', true).val(1);
        }
        else
          $("#n_periods").attr('disabled', false);

        if (el.value == 31) // Maandelijks
        {
          $(".trweekends").hide();
          $(".trdays").show();
        }
        else
        {
          $(".trweekends").show();
          $(".trdays").hide();
        }
        calcPerioden();
      }

      function multi_submit_callback (json, textStatus)
      {
        iface.button.enable("btn_res_submit");
        if (json.success)
          FcltMgr.closeDetail(window, json);
      }

      function multi_submit ()
      {
        if (!dates.length)
        {
          fillDates(true, true); // Na het vullen van de datums wordt er opnieuw een submit gedaan. Daardoor is een alert melding niet meer nodig.
          return false;
        }

        $("#newDates").empty();
        var i;
        dates.sort();
        for (i = 0; i < dates.length; i++)
        {
          var nextDate = dates[i];
          $("#newDates").append("<option value=" + nextDate + ">" + toDateString(new Date(nextDate)) + "</option>")
        }
        $('#newDates>option').prop('selected', 'true');
        $.post($("form[name=u2]")[0].action, $("[name=u2]").serialize(), FcltCallbackAndThenAlways(multi_submit_callback), "json");
        return true; // disable submit
      }

      // Maintain array of dates
      // Vrij naar http://stackoverflow.com/questions/1452066
      var dates = new Array();
      function addDate(date)
      {
        var date2 = new Date(date); // zelfde tijdstip gebruiken als rrr.rsv_ruimte_van
        date2 = date2.setFloatHours(new Date(<%=rrr.rsv_ruimte_van.getTime()%>).getFloatHours(), <%=safe.jsfloat(S("res_h"))%>);

        if (frontend && earliest_expire_change && date2 < earliest_expire_change)
        {
          alert(L("lcl_res_repeat_lastmin"));
          return;
        }
        if ($.inArray(date, dates) < 0) dates.push(date);
      }
      function removeDate(index) {dates.splice(index, 1);}
      // Adds a date if we don't have it yet, else remove it
      function addOrRemoveDate(date)
      {
        var index = $.inArray(date, dates);
        if (index >= 0)
          removeDate(index);
        else
          addDate(date);
      }

      jQuery(document).ready(function()
                             {
                               var params = {altField: "#date_from",
                                             minDate: '0d',
                                             numberOfMonths: 3,
                                             onSelect: function(dateText, inst) // noot: het alt-veld is al bijgewerkt
                                                       {
                                                         var dt = parseInt($("#date_from").val());
                                                         addOrRemoveDate(dt);
                                                       },
                                             beforeShowDay: function (date)
                                                            {
                                                              var dt = date.getTime();
                                                              var gotDate = $.inArray(dt, dates);
                                                              if (gotDate >= 0)
                                                              {
                                                                // Enable date so it can be deselected. Set style to be highlighted
                                                                return [true,"calselected"];
                                                              }
                                                              if ($.inArray(dt, mld_vrije_dagen) > -1)
                                                                return [ true, 'ui-state-disabled' ];
                                                              // Dates not in the array are left enabled, but with no extra style
                                                              return [true, ""];
                                                            }
                                            };
<%                             var limit = ((urole == "fe" && S("res_fe_reservering_limiet") > 0)? S("res_fe_reservering_limiet") : S("res_reservering_limiet"))
                               if (daysToExpire != null && daysToExpire >= 0 && daysToExpire < limit)
                                 var limit = daysToExpire - 1; // De vervaldatum niet meerekenen.
                               if (limit > 0)
                               { %>
                                 params.maxDate = '+<%=limit%>'
<%                             } %>
                               $("#show_date_from").datepicker(params);
                               onChangePeriod($("#sel_cycle"));
                             });

    </script>
  </head>
  <body class="modal" id="mod_resmulti">
  <form name="u2"
        action="res_multi_create_save.asp?urole=<%=urole%>&rsv_ruimte_key=<%=rsv_ruimte_key%>"
        method="post">
<%
    if (rrr.reservering_ispool)
        BLOCK_START("", L("lcl_res_repeat_pool").format(rrr.reservering_key));
    else
        BLOCK_START("", L("lcl_res_repeat1") + rrr.reservering_key + "/" + rrr.rsv_ruimte_volgnr + L("lcl_res_repeat3"));
%>
    <div id="resmakedates"><%=L("lcl_res_makedates")%></div><br>

<%  //======= FIELD 'Periode' =======
    sql = "SELECT c.res_cyclus_periode"
        + "     , " + lcl.xsqla('c.res_cyclus_naam', 'res_cyclus_key')
        + "  FROM res_cyclus c"
        + " WHERE res_cyclus_periode > 0"
        + " ORDER BY res_cyclus_periode";
    FCLTselector("sel_cycle",
                 sql,
                 { label: L("lcl_period"),
                   onChange: "onChangePeriod(this)"
                 }
                );
    var today = new Date();
    FCLTcalendar("date_from0",
                 { label : L("lcl_res_repeat2"),
                   datum: rrr.rsv_ruimte_van.getTime() > today.getTime()? rrr.rsv_ruimte_van : today, // of today als de ruimte ouder is
                   maxPast : 0,
                   maxFuture: (urole == "fe" && S("res_fe_reservering_limiet") > 0)? S("res_fe_reservering_limiet") : S("res_reservering_limiet"),
                   timeField: false,
                   volgnr: 1,
                   onChange: "calcPerioden()"
                 });

    var lastday = new Date();
    FCLTcalendar("date_to0",
                 { label : L("lcl_end_date"),
                   datum : lastday,
                   initEmpty: true,
                   maxPast : 0,
                   maxFuture: (urole == "fe" && S("res_fe_reservering_limiet") > 0)? S("res_fe_reservering_limiet") : S("res_reservering_limiet"),
                   timeField: false,
                   volgnr: 2,
                   onChange: "calcPerioden()"
                 });

%>
    <tr>
      <td class="label"><label for="n_periods"><%=L("lcl_n_of_periods")%>:</label></td>
      <td><input name="n_periods" id="n_periods" value="" onChange="calcEinddatum();"></td>
    </tr>
    <tr class="trweekends">
      <td class="label"><label for="withWeekends"><%=L("lcl_res_skipnonworkdays")%>:</label></td>
      <td><input id='withWeekends' type='checkbox' checked onclick='calcPerioden();'></td>
    </tr>
    <tr class="trdays">
      <td class="label"><label for="dayofmonth"><%=L("lcl_res_day")%>:</label></td>
      </td>
      <td>
<%
      sql = "SELECT 256, " + safe.quoted_sql(L("lcl_ins_controle_eerste")) + ", 1 FROM DUAL"
          + " UNION SELECT 512, " + safe.quoted_sql(L("lcl_ins_controle_tweede")) + ", 2 FROM DUAL"
          + " UNION SELECT 768, " + safe.quoted_sql(L("lcl_ins_controle_derde")) + ", 3 FROM DUAL"
          + " UNION SELECT 1024, " + safe.quoted_sql(L("lcl_ins_controle_vierde")) + ", 4 FROM DUAL"
          + " UNION SELECT 1280, " + safe.quoted_sql(L("lcl_ins_controle_vijfde")) + ", 5 FROM DUAL"
          + " UNION SELECT 1536, " + safe.quoted_sql(L("lcl_ins_controle_eennalaatste")) + ", 6 FROM DUAL"
          + " UNION SELECT 1792, " + safe.quoted_sql(L("lcl_ins_controle_laatste")) + ", 7 FROM DUAL"
          + " ORDER BY 1";
      FCLTselector("dayofmonth",
                   sql,
                   { initKey: 1,
                     required: false,
                     html: " width='100px'",
                     onChange: "calcPerioden()"
                   });
      sql = "";
      for (var i = 0; i <= 6; i++)
      {
        sql += (i > 0? " UNION " : "") + "SELECT " + Math.pow(2, (i )) + ", " + safe.quoted_sql(calendar_names.days[i]) + " FROM DUAL"
      }
      sql += " ORDER BY 1";
      FCLTselector("dayofweek",
                   sql,
                   { initKey: 1,
                     required: false,
                     onChange: "calcPerioden()"
                   });
%>
      <%=L("lcl_ins_controle_period_ofthemonth")%></td>
    </tr>
    <tr>
      <td colspan="2">
<%    var buttons =  [{title: L("lcl_res_showdates"), action:"fillDates(true)"},
                      {title: L("lcl_res_erasedates"), action:"EraseDates()"}];
      CreateButtons(buttons);
%>    </td>
    </tr>
    <tr>
      <td colspan=2>
        <input type="hidden" id="date_from"/>
        <% /* #show_date_from heeft harde hoogte in de css voor als je naar een maand bladert met een week meer dan de meeste maanden */ %>
        <div id="show_date_from"></div>
      </td>
    </tr>
    <% BLOCK_END(); %>

    <select style="display:none" id="newDates" name="newDates" multiple size="10"></select>
<%
  CreateButtons([ { title: L("lcl_res_duplicate"), action: "multi_submit()", singlepress: true, id:"btn_res_submit" },
                  { title: L("lcl_cancel"), action: "FcltMgr.closeDetail(window, { cancel: true } )"} ]);

  IFACE.FORM_END(); %>
  </form>
</body>
