/*
     $Revision$
     $Id$

    File:               res_plan.js
    Remark:             Functies voor res planborden
    Parameters:
    Context:
*/
function showLoader() {
    $("div.busyloading").show();
}
function hideLoader() {
    $("div.busyloading").hide();
}
//
function set_borders_margins(tb, printfactor)
{
    function calc_margin(len)
    {
        var rest = unit_length;
        if (len > unit_length)
        {
            rest = unit_length - (len % unit_length);
        }
        else if (len < unit_length)
        {
            rest = unit_length - len;
        }
        return (rest * hour_px) % unit_px;
    }
    var _factor = printfactor || 1;
    var hour_px = tb._hour_px() * _factor;
    var unit_length = tb._unit_length;
    var unit_px = unit_length * hour_px;
    var root = document.documentElement;
    root.style.setProperty('--hourpx', hour_px + "px");
    root.style.setProperty('--unit0125', (calc_margin(.125)) + "px");
    if (unit_length > 0.25)
    {
        root.style.setProperty('--unit025', (calc_margin(.25)) + "px");
        root.style.setProperty('--unit050', (calc_margin(.5)) + "px");
        root.style.setProperty('--unit075', (calc_margin(.75)) + "px");
        root.style.setProperty('--unit100', (calc_margin(1)) + "px");
        root.style.setProperty('--unit125', (calc_margin(1.25)) + "px");
        root.style.setProperty('--unit150', (calc_margin(1.5)) + "px");
        root.style.setProperty('--unit175', (calc_margin(1.75)) + "px");
        root.style.setProperty('--unit200', (calc_margin(2)) + "px");
    }
    root.style.setProperty('--displayhour1', (hour_px < 15 ? "none" : "initial"));
    root.style.setProperty('--displayhour2', (hour_px < 48 ? "none" : "initial"));
    root.style.setProperty('--displayhour3', (hour_px < 24 ? "none" : "initial"));
}
// show/hide location-rooms in css grid
function toggleLoc()
{
    var $this = $(this);
    var $grid = $this.closest("div.grid");
    $this.toggleClass("collapsed");
    $("div[data-row]", $grid).not(".locatiegrid, .grid").toggleClass("hidden");
    FcltMgr.resized();
}
// show/hide ins_disc-objects in css grid
function toggleDisc()
{
    var $this = $(this);
    var $grid = $this.closest("div.grid");
    $this.toggleClass("collapsed")
    $("div[data-row]", $grid).not(".insdiscgrid, .grid").toggleClass("hidden");
    FcltMgr.resized();
}
function loadtitle(target,dest)
{
    target.title = "..."; // Voorkom te snelle recall's
    $.get(dest, function (data) { target.title = data });
}
function showtitle(target,dest)
{
    target.title = "..."; // Voorkom te snelle recall's
    $.get(dest, function (data) { $("p", target).first().html(data); });
}

var timerID=null;
function delayed(delay, fn)
{
    if (timerID) clearTimeout(timerID);
    timerID = setTimeout(fn, delay);
}

function setResRsvDeelTitle(elm, rsv_deel_key)
{
    if (!elm.title)
        delayed(200, function () {
            loadtitle(elm, "../res/res_load_title_obj.asp?rsv_deel_key="+rsv_deel_key);
        });
}

function rsv_title(elm)
{
    if (!elm.title && elm.getAttribute("rsv_key") > 0)
    {
        delayed(200, function () {
            loadtitle(elm, "../res/res_load_title_rsv.asp?rsv_ruimte_key="+elm.getAttribute("rsv_key"));
        });
    }
}

function setBezBezoekersTitle(elm, bez_bezoekers_key)
{
    if (!elm.title)
        delayed(200, function () {
            loadtitle(elm, "../res/res_load_title_bez.asp?bez_bezoekers_key="+bez_bezoekers_key);
        });
}

function rsv_click(elm,urole)
{
    if (window.beingdragged)
    {
        window.beingdragged = false;
        return;
    }
    if (elm.getAttribute("rsv_key") > 0)
    {
        var cmd = "appl/res/res_reservering.asp?rsv_ruimte_key=" + elm.getAttribute("rsv_key") + "&urole="+urole;
        FcltMgr.openDetail(cmd, { reuse: true });
    }
}

function room_table_click(evt, res_van, hour_px, res_t1, urole, act_key_arr)
{
    var hours = parseInt('offsetX' in evt?evt.offsetX:evt.layerX, 10)/ hour_px + res_t1;
    if (window.beingdragged)
    {
        window.beingdragged = false;
        return;
    }
    var ob = (window.event ? window.event.srcElement : evt.target);
    if ($(ob).hasClass("tddiv"))
        ob = ob.parentElement || ob.parentNode;
    if ($(ob).hasClass("plantd") && $(ob).hasClass("reserv"))
    {
        var theTR = $(ob).parent("TR");
        // Externe ruimten mogen niet gewijzigd worden.
        if (theTR.hasClass("extern"))
          return;
        var dagnr = $('td.plantd.reserv', theTR).index(ob); // Hoeveelste TD?
        var res_ruimte_key = theTR[0].id;
        res_van.setHours(Math.floor(hours), Math.floor(60*(hours-Math.floor(hours))), 0, 0);
        res_van.setDate(res_van.getDate()+dagnr);
        // Gewoon intern
        var cmd = "appl/res/res_reservering.asp"
                + "?res_ruimte_key=" + res_ruimte_key
                + "&res_van=" + res_van.getTime()
                + (act_key_arr.length == 1 ? "&activiteit_key=" + act_key_arr : "")
                + "&urole=" + urole;
        FcltMgr.openDetail(cmd);
    }
}

function room_table_mouse(evt, res_van, hour_px, res_t1)
{
    var hours = parseInt('offsetX' in evt?evt.offsetX:evt.layerX, 10)/ hour_px + res_t1;
    var ob = (window.event ? window.event.srcElement : evt.target);
    if ($(ob).hasClass("tddiv"))
        ob = ob.parentElement || ob.parentNode;
    if ($(ob).hasClass("plantd") && $(ob).hasClass("reserv"))
    {
        var theTR = $(ob).parent("TR");
        var dagnr = $('td.plantd.reserv', theTR).index(ob); // Hoeveelste TD?
        res_van.setDate(res_van.getDate()+dagnr);
        res_van = res_van.setFloatHours(hours, 0.25);

        $("#timetip").html(toDateTimeString(res_van))
                     .css({ left: parseInt(evt.pageX, 10) + 10 + "px",
                            top: parseInt(evt.pageY, 10) - 25 + "px"
                          })
                     .show();
    }
}

function obj_table_click(evt, res_van, hour_px, res_t1, urole)
{
    var hours = parseInt('offsetX' in evt?evt.offsetX:evt.layerX, 10)/ hour_px + res_t1;
    if (window.beingdragged)
    {
        window.beingdragged = false;
        return;
    }
    var ob = (window.event ? window.event.srcElement : evt.target);
    if ($(ob).hasClass("tddiv"))
        ob = ob.parentElement || ob.parentNode;
    if ($(ob).hasClass("plantd") && $(ob).hasClass("reserv"))
    {
        var theTR = $(ob).parent("TR");
        var dagnr = $('td.plantd.reserv', theTR).index(ob); // Hoeveelste TD?
        var res_deel_key = theTR[0].id;
        res_van.setHours(Math.floor(hours), Math.floor(60*(hours-Math.floor(hours))), 0, 0);
        res_van.setDate(res_van.getDate()+dagnr);
        var cmd = "appl/res/res_reservering.asp?restype=CV"
                + "&res_deel_key=" + res_deel_key
                + "&res_van=" + res_van.getTime()
                + "&urole="+urole;
        FcltMgr.openDetail(cmd);
    }
}

// Gebruiker heeft een ruimte geselecteerd in een css grid.
function selectRoomGrid(roomDiv)
{
    var res_ruimte_key = $(roomDiv).attr("id");
    var res_ruimte_extern = $(roomDiv).data("extern");
    var res_ruimte_extern_meeting = $(roomDiv).data("room-extern-meeting");

    FcltMgr.closeDetail(window, {
        res_ruimte_key:     res_ruimte_key,
        res_ruimte_extern:  res_ruimte_extern,
        res_ruimte_extern_meeting: res_ruimte_extern_meeting
    });
}

// Gebruiker heeft een ruimte geselecteerd.
function selectRoom(radio)
{
    var this_row = $(radio).closest('tr')[0];
    var res_ruimte_key = this_row.id;

    FcltMgr.closeDetail(window, { res_ruimte_key: res_ruimte_key });
}

// Controleer of alle catering tijden wel binnen res_cat_t1 en res_cat_t2 vallen
// Als dat niet zo is geef dan een melding en return false
function checkArtikelen(starttime_room, endtime_room)
{
    var show_bound = true;
    var allGood = true;
    $(".tab_cat_sched").each(function() // doorloop alle catering disciplines
    {
        var tbl=this;
        var thisCatExpire = new Date(parseInt(tbl.getAttribute("catExpire"), 10));
        if (allGood)
        $(".catline", tbl).each(function ()
        {
            var objCnt = $("[id^='inpb_c_']",this)[0];
            var Cnt = parseInt(objCnt.value,10);
            var hh = parseInt($("[id^='inpbh1_c_']",this).val(),10);
            var mm = parseInt($("[id^='inpbm1_c_']",this).val(),10);
            var minimum = parseInt($("[id^='inpb_c_']",this)[0].getAttribute("minimum"),10);
            if (!isNaN(Cnt) && Cnt == 0)
                return; // Niet over zeuren als het 0 is

            if ($("[id^='inpb_c_']",this).val() > 0 && $("[id^='inpb_c_']",this).val() < minimum)
            {
              $("[id^='inpb_c_']",this).select().focus();
              FcltMgr.alert(L("lcl_res_bestel_minimum").format(minimum));
              allGood = false;
              return;
            }

            if (isNaN(Cnt) || isNaN(hh) || isNaN(mm) ||
                (hh+(mm/60) < (res_cat_t1>=0?res_cat_t1:starttime_room)) ||
                (hh+(mm/60) > (res_cat_t2>=0?res_cat_t2:endtime_room ))
               )
            {
                var starttime_art = parseInt($("[id^='inpbb1_c_']",this).val(),10);
                var endtime_art   = parseInt($("[id^='inpbe1_c_']",this).val(),10);
                if (hh+(mm/60) < starttime_art || hh+(mm/60) > endtime_art) // HSLE#38449
                {
                    objCnt.focus();
                    FcltMgr.alert(L("lcl_res_cons_time")); // Niet beschikbaar op dit tijdstip
                    allGood = false;
                    return;
                }
            }

            var jsDate = res_van.midnight();
            jsDate.setHours(hh);
            jsDate.setMinutes(mm);

            if (show_bound && (jsDate < res_van || jsDate > res_tot))
            {
                FcltMgr.alert(L("lcl_res_facility_bound"));
                show_bound = false;
            }

            if (jsDate < thisCatExpire && !backo && !fronto)
            {
              FcltMgr.alert(L("lcl_res_lastmin"));
              allGood = false;
            }
        });
    });
  return allGood;
}

function ItemChoosed_obj(elm, fromID, disc_key, hour_px, extraparams)
{
    var isMore = ((extraparams || "").indexOf("&more=1") >= 0); // extraparams="&more=1" wordt in res_plan_obj_v2.inc gezet
    $(elm).toggleClass("closed")
          .find("i.fa-plus-square, i.fa-minus-square").toggleClass("fa-minus-square fa-plus-square");
    var tabel = $("#table_dis" + disc_key);
    if (tabel.length && !isMore)
    {
        FcltMgr.resized(window);
        return;
    }

    params  = "?urole="+urole
            + "&rsv_ruimte_key="+rsv_ruimte_key
            + "&mld_opdr_key="+mld_opdr_key
            + "&disc_key="+disc_key
            + "&hour_px=" + hour_px

    $("#"+fromID).load("./res_load_plan_obj.asp" + params + (extraparams||""),
                        function(txt) {
                          if (window.checkForChange) { checkForChange(); }
                          FcltMgr.resized(window);
                        });
}

function ItemChoosed_cat(elm, fromID, disc_key, extraparams, callback)
{
    $(elm).toggleClass("closed")
          .find("i.fa-plus-square, i.fa-minus-square").toggleClass("fa-minus-square fa-plus-square");

    var tabel = $("#table_dis" + disc_key);
    if (tabel.length)
    {
        FcltMgr.resized(window);
        return;
    }

    var params  = "?discipline_key=" + disc_key
                + "&rsv_ruimte_key="+rsv_ruimte_key;

    var s = "./res_load_cat.asp" + params + (extraparams||"");
    $.get(s, data => {
        flexReloaded(data, undefined, "#div_dis" + disc_key);
        callback?.();
    });
}

// onclick van een reserveerbaar deel regel (dan is de categorie al opengeklapt)
//
function res_deel_click(rdeel)
{
    $("#" + rdeel).toggleClass("selected").toggleClass("unselected");
}
function res_deel_grid_click(rdeel)
{
    var $this = $("input#chk_" + rdeel);
    var $bulk = $("input[name=amt_" + rdeel).removeClass("missing").toggleClass("required", $this.is(":checked"));
    if ($bulk.length > 0 && !$this.is(":checked"))
    {
        $("div.bad", $bulk.parent()).remove();
    }
    var disc = $this.parent().attr("data-disc");
    var row = $this.parent().attr("data-row");
    $("div.gepland.res_nieuw[data-disc=" + disc + "][data-row=" + row + "]").toggleClass("selected", $this.prop("checked")).toggleClass("unselected", !$this.prop("checked"));
}
function res_deel_grid_change(rdeel)
{
    var $chk = $("input#chk_" + rdeel);
    var bulk = $("input[name=amt_" + rdeel).val();
    if (bulk > 0 && !$chk.is(":checked"))
    {
        $chk.click();
    }
}

function showTotPriceArt(number)
{
    // show the total price of the selected artikel
    var aant = parseInt($("#inpb_c_"+number).val(), 10)||0;
    if (urole=='fe' && aant < 0)
        aant = 0
    var pric = parseFloat($("#inpbp_c_"+number).val().replace(',','.')||0);
    $("#inpb_c_"+number).val(aant);
    if (!$("#inpbp_c_"+number).attr("readonly"))
        $("#inpbp_c_"+number).val(num2currEditable(pric));
    $("#inpbtp_c_"+number).val(num2curr(aant*pric));
}

function showOpmerking(remark_selector, evt, v2)
{
  var evt = evt || event;

  // Onderkant popup ongeveer gelijk met onderderkant aangeklikte omschrijving.
  // Mocht bovenkant uit zicht verdwijnen dan bovenkant omschrijving gelijk aan bovenkant iframe.
  var $rem = $(remark_selector);
  if (!$rem.length) // Geen omschrijving tooltip
    return;
  $rem.find('img').attr('src',$rem.find('img').attr('theSrc'))
  if (!String($rem.html()).replace(/[ \t\n\r]/g,""))
  {
    $rem.hide(); // want leeg
    return;
  }
  if (evt && "clientX" in evt)
      $rem.css("left", evt.clientX+15);

  var Positions = function(element)
  {
    this.boxShadow =          12;
    this.dropDownHeight =     element.outerHeight() + this.boxShadow;
    this.base =               element.closest(v2?"div.labelgrid":"td");
    this.tdBottom =           this.base.offset().top + this.base.outerHeight();
    this.pageBottom =         $("iframe.fcltmodal", window.parent.document).length ? $("iframe.fcltmodal", window.parent.document).contents().height()
                                                                                   : $("div.divrstable").height() || ($(window.frameElement).height() + $(window).scrollTop());
    this.dropDownBottom =     this.tdBottom + this.dropDownHeight;
    this.dissappearingBottom = this.dropDownBottom > (this.pageBottom || 0);
    this.positionFromBottom = (this.pageBottom - this.dropDownHeight - (element.closest(".block-wrapper").length ? element.closest(".block-wrapper").offset().top : 0)) + "px";
  };
  var p = new Positions($rem);

  if (p.dissappearingBottom)  // Een negatieve waarde mag er niet uitkomen, anders verdwijnt het onderste gedeelte uit zicht.
    $rem.css("top", p.positionFromBottom);
  else
    $rem.css("top", "");
  $rem.show();
  if ($("iframe.fcltmodal", window.parent.document).length)
    FcltMgr.resized();
  return;
}
