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

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

var urole = getQParamSafe("urole");
var afspr_key = getQParamInt("afspr_key");

var this_bez = bez.func_enabled_afspraak(afspr_key);
user.auth_required_or_abort(this_bez.canRead);
%>
<html>
    <head>
<%
FCLTHeader.Generate();

// =========================================
// Eerst wat info ophalen
var sql = "SELECT ba.bez_afspraak_datum"
        + ",      ba.bez_afspraak_eind"
        + "  FROM bez_afspraak ba"
        + " WHERE ba.bez_afspraak_key = "+afspr_key;

oRs = Oracle.Execute(sql);
var bez = { afspraak_datum : new Date(oRs("bez_afspraak_datum").value),
            afspraak_eind  : new Date(oRs("bez_afspraak_eind").value)
          }
oRs.Close();

var limiet = (urole == "fe" && S("vis_fe_afspraak_limiet") > 0) ? S("vis_fe_afspraak_limiet") : S("vis_afspraak_limiet");
if (limiet < 0)
    limiet = 9999; // 30 jaar, rekent gemakkelijker.

var maxday = new Date()
maxday.setDate(maxday.getDate() + limiet);

%>
    <script>

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

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

        function selecteerbareDagen(p_date)
        { // Selecteerbare dagen zijn alleen werkdagen als dat is aangevinkt.
          // Is "Alleen werkdagen" niet aangevinkt dan gelden regels volgens de setting "bez_use_buildinghours".
          // : 0=Alle dagen te selecteren, 1=vrije dagen niet te selecteren, 2=weekends niet te selecteren, 3=vrijedagen en weekends niet  te selecteren.
          var selectMode = <%=S("bez_use_buildinghours")%>;
          var weekend = (!$.datepicker.noWeekends(p_date)[0]);
          var day_off = ($.inArray(p_date.getTime(), mld_vrije_dagen) > -1);
          var disableDay = false;
          if ($("#withWeekends:checked").val() == "on")
            disableDay = (day_off || weekend);
          else
            disableDay = ((day_off && ((selectMode & 1) == 1)) || (weekend && ((selectMode & 2) == 2)));

          return disableDay;
        }

        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 bez_new_dates = [];
          var limitDate = null;
<%        if (limiet > 0)
          { %>
            limitDate = new Date();
            limitDate.setDate(limitDate.getDate() + <%=limiet%>);
<%        } %>
          var overflow = false;
          var message = "";
          for (i = 0; i < np; i++)
          {
            nextDate.setDate(nextDate.getDate() + interval);
            if (limitDate && nextDate > limitDate)
            {
              overflow = true;
              break;
            }
            if (selecteerbareDagen(nextDate))
            {
              np++;
              continue;
            }
            bez_new_dates.push(nextDate.getTime());
          }

          var result = { bez_new_dates: bez_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_bez_date_limit_reached") + toDateString(limitDate);
          return result;
        }

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

          var bez_new_dates = json.bez_new_dates;
          if (bez_new_dates)
          {
            for (var j = 0; j < bez_new_dates.length; j++)
            {
              // window.dates = bez_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(bez_new_dates[j], 10))
                {
                  exists = true;
                  continue;
                }
              }
              if (!exists)
                window.dates.push(bez_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)
        {
            // $("#newDates").empty();
            var np = $("#n_periods").val();
            if (isNaN(np) || np < 1)
            {
                FcltMgr.alert(L("lcl_bez_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%>",
                           np: np,
                           nextDate: nextDate.getTime(),
                           bits: bits
                         };
              $.getJSON("get_bez_info_ajax.asp?req_info=bez_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 bez_new_dates = json.bez_new_dates;
          if (bez_new_dates)
          {
            var nextDate = new Date();
            nextDate.setTime(bez_new_dates[bez_new_dates.length - 1]);
            $("#show_date_to0").datepicker("setDate", nextDate);
          }
        }

        function calcEinddatum()
        {
          fillDates(false);
        }

        function finishCalcPerioden(json, textStatus)
        {
          var bez_steps = json.bez_steps;
          if (bez_steps >= 0)
          {
            $("#n_periods").val(bez_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_bez_info_ajax.asp?req_info=bez_nr_periods",
                        data,
                        finishCalcPerioden
                       );
            }
          }
          else
          {
            if ($.inArray(nextDate.getTime(), mld_vrije_dagen) > -1
                || nextDate.getDay() == 0
                || nextDate.getDay() == 6)
            { // een vrije/weekend dag geselecteerd als startdatum, dus niet alleen werkdagen.
              $("#withWeekends").prop("checked", false);
            }
            var selectMode = <%=S("bez_use_buildinghours")%>;
            nextDate.setDate(nextDate.getDate() + interval);
            while (nextDate <= lastDate)
            {
              if (!selecteerbareDagen(nextDate))
                periodedagen.push(new Date(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 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()
        {
            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;
            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(), FcltCallbackClose, "json");
            return true; // disable button
        }

        // Maintain array of dates
        // Vrij naar http://stackoverflow.com/questions/1452066
        var dates = new Array();
        function addDate(date) {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);
        }

        $(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 (selecteerbareDagen(date))
                                            return [true, "ui-state-disabled"];
                                          // Dates not in the array are left enabled, but with no extra style
                                          return [true, ""];
                                        }
                       };
<%        if (limiet > 0)
          { %>
          params.maxDate = "+<%=limiet%>";
<%        } %>
          $("#show_date_from").datepicker(params);
          onChangePeriod($("#sel_cycle"));
          FcltMgr.resized();
        });

    </script>
</head>
<body class="fclt-modal" id="mod_resmulti">
<% MODAL_START(); %>
<form name="u2" action="bez_multi_save.asp?urole=<%=urole%>&afspr_key=<%=afspr_key%>" method="post">
<% MODAL_BLOCK_START("", L("lcl_bez_repeat1") + afspr_key + " ("+toDateTimeString(bez.afspraak_datum)+")" + L("lcl_bez_repeat3"), { icon: "fa-copy" });
%>
    <tr><td colspan="2"><div id="bezmakedates"><%=L("lcl_bez_makedates")%></div></td></tr>
<%
      // ======= 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_bez_repeat2"),
                                   datum: bez.afspraak_datum.getTime() > today.getTime() ? bez.afspraak_datum : today, // of today als de afspraak ouder is
                                   maxPast: 0,
                                   maxFuture: limiet,
                                   timeField: false,
                                   volgnr: 1,
                                   selectableDays: (S("bez_use_buildinghours") > 1 ? 3 : 0),
                                   onChange: "calcPerioden()"
                                 });

      FCLTcalendar("date_to0", { label : L("lcl_end_date"),
                                 datum: today,
                                 initEmpty: true,
                                 maxPast : 0,
                                 maxFuture: limiet,
                                 timeField: false,
                                 volgnr: 2,
                                 selectableDays: (S("bez_use_buildinghours") > 1 ? 3 : 0),
                                 onChange: "calcPerioden()"
                               });

      RWFIELDTR("n_periods", "fld", L("lcl_n_of_periods"), "", { html: "onChange='calcEinddatum();'" });
      RWCHECKBOXTR("withWeekends", "", L("lcl_res_skipnonworkdays"), 1
                                 , { trclass: "trweekends", html: "onClick='calcPerioden();'", readonly: S("bez_use_buildinghours")==3 });
%>
    <tr class="trdays">
      <td class="label"><label for="dayofmonth"><%=L("lcl_day")%></label></td>
      <td>
<%
      sql = "       SELECT 256, " + safe.qL("lcl_bez_eerste") + ", 1 FROM DUAL"
          + " UNION SELECT 512, " + safe.qL("lcl_bez_tweede") + ", 2 FROM DUAL"
          + " UNION SELECT 768, " + safe.qL("lcl_bez_derde") + ", 3 FROM DUAL"
          + " UNION SELECT 1024, " + safe.qL("lcl_bez_vierde") + ", 4 FROM DUAL"
          + " UNION SELECT 1280, " + safe.qL("lcl_bez_vijfde") + ", 5 FROM DUAL"
          + " UNION SELECT 1536, " + safe.qL("lcl_bez_eennalaatste") + ", 6 FROM DUAL"
          + " UNION SELECT 1792, " + safe.qL("lcl_bez_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_bez_period_ofthemonth")%></td>
    </tr>
    <% MODAL_BLOCK_END(); %>
<%    SIMPLE_BLOCK_START();
      var buttons =  [{title: L("lcl_bez_showdates"), action: "fillDates(true)", icon: "fa-calendar-day", importance: 2},
                      {title: L("lcl_bez_erasedates"), action: "eraseDates()", icon: "fa-calendar-times", importance: 3}];
      CreateButtons(buttons);
      SIMPLE_BLOCK_END();
      SIMPLE_BLOCK_START();%>
          <div class="simple-content-wrapper">
              <input type="hidden" id="date_from">
              <div id="show_date_from"></div>
          </div>
          <select style="display:none" id="newDates" name="newDates" multiple size="10"></select>
<%    SIMPLE_BLOCK_END();
    IFACE.FORM_END(); %>
<%
    SIMPLE_BLOCK_START();
        CreateButtons([ { title: L("lcl_bez_duplicate"), action: "multi_submit()", icon: "fa-fclt-save", singlepress: true, id: "btn_multi_submit", importance: 1 },
                        { title: L("lcl_cancel"), action: "FcltMgr.closeDetail(window, { cancel: true } )", icon: "fa-fclt-cancel", importance: 3} ]);
    SIMPLE_BLOCK_END();
%>
</form>
<% MODAL_END(); %>
</body>
<% ASPPAGE_END(); %>
