<%@ 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.canChange);
%>
<html>
    <head>
<%  FCLTHeader.Generate()
    var submitting = getQParamInt("submit",0)==1;
    if (submitting)
    {
        var form_dates = Request.Form("newDates");
        for (var i=1; i<= form_dates.Count; i++)
        {
            var datum = new Date(parseInt(form_dates(i),10));
            var sql = "BEGIN bez.copy_afspraak("+afspr_key+","+datum.toSQL()+", "+user_key+", NULL); END;";
            Oracle.Execute(sql);
        }
        var msg = L("lcl_bez_multi_created").format(form_dates.Count);
        if (this_bez.nrPAF > 0)
            msg += "\n" + L("lcl_bez_paf_not_copied").format(this_bez.nrPAF);
        %><script>$(document).ready(function () {
                FcltMgr.closeDetail(window, { refresh: true, warning:
                                             "<%=safe.jsstring(msg)%>" } );
               });
          </script><%
        Response.End;
    }

    // =========================================
    // 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 type="text/javascript">
            function fillDates()
            {
                $("#newDates").empty();
                var np = $("#n_periods").val();
                if (isNaN(np) || np < 1)
                {
                    alert(L("lcl_bez_period_error"))
                    return;
                }
                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=[];
                for (i=0; i< np; i++)
                {
                    nextDate.setDate(nextDate.getDate() + interval);
                    if (nextDate.getTime() > <%=maxday.getTime()%>)
                    {
                        alert(L("lcl_bez_multi_limit_reached") + toDateString(nextDate));
                        break;
                    }
                    if($("#withWeekends:checked").val()=="on" &&
                            ($.inArray(nextDate.getTime(), mld_vrije_dagen) > -1
                             ||nextDate.getDay()==0
                            ||nextDate.getDay()==6)
                        )
                    {
                        np++;
                        continue;
                    }
                    bez_new_dates.push(nextDate.getTime());
                    $("#newDates").append("<option value="+nextDate.getTime()+">"+toDateString(nextDate)+"</option>")
                };
                window.dates = bez_new_dates; // of merge?
                $("#show_date_from").datepicker('refresh'); // undocumented maar werkt bij 1.7.3
            }
            function onChangePeriod(el)
            {
                if (el.value==0) // niet periodiek
                {
                    $("#n_periods").attr('disabled',true).val(1);
                }
                else
                    $("#n_periods").attr('disabled',false);
            }


function multi_submit ()
{
    if (!dates.length)
    {
        alert(L("lcl_bez_multi_none"));
        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');
    document.forms.u2.submit();
    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);
}

        jQuery(document).ready(
          function(){

        $("#show_date_from").datepicker(
                    {   altField: "#date_from",
                        minDate : '0d',
                        maxDate : '+<%=limiet%>d',
                        numberOfMonths: 2,
                        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"];
                                }
                                // Dates not in the array are left enabled, but with no extra style
                                 return [true, ""];
                            }
                   });
            });
        </script>
</head>
<body class="modal" id="mod_resmulti">
<form name=u2 action=bez_multi.asp?submit=1&urole=<%=urole%>&afspr_key=<%=afspr_key%> method="post">
<% BLOCK_START("", L("lcl_bez_repeat1") + afspr_key + " ("+toDateTimeString(bez.afspraak_datum)+")" + L("lcl_bez_repeat3"));
         //======= 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"
          + "   AND res_cyclus_periode <> 31" // Maandelijks kunnen we bij BEZ nog niet aan
          + " 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 ruimte ouder is
            maxPast : 0,
            maxFuture: limiet,
            timeField: false
          });

       RWFIELDTR("n_periods", "fldshort", L("lcl_n_of_periods"), "");

%>
    <tr>
        <td class="label"><label for="withWeekends"><%=L("lcl_res_skipnonworkdays")%>:</label></td>
        <td><input id='withWeekends' type='checkbox' checked></td>
    </tr>
    <tr><td colspan="2">
    <%
        var buttons =  [ {title: L("lcl_bez_makedates"), action:"fillDates()" }];
        CreateButtons(buttons);
    %>
    </td></tr>
    <tr><td colspan=2>
            <input type="hidden" id="date_from" />
            <div id="show_date_from"></div>
        </td>
    </tr>
<% BLOCK_END(); %>
<select style="display:none" id="newDates" name="newDates" multiple size="10"></select>
<% IFACE.FORM_END(); %>
<%
    CreateButtons([ { title: L("lcl_res_duplicate"), action: "multi_submit()", singlepress: true, id: "btn_multi_submit" },
                    { title: L("lcl_cancel"), action: "FcltMgr.closeDetail(window, { cancel: true } )"} ]);
%>
</form>
</body>
