/*
     $Revision$
     $Id$

     File:               resultset_table_v2.js
     Description:        Javascript code voor de resultsettable. Voegt post formulier aan body toe.
     Parameters:
     Globals:
     Context:            Wordt gebruikt door de resultset_table_v2.inc
     Note:
*/

// post formulier voor printen aan de body toevoegen
// <form> printform is nodig bij printen reserveringen i.v.m. POST formulier
// maar <form> mag niet binnen een ander <form> voorkomen en moet eigenlijk wel binnen body staan
// Formulier als tekststring samenstellen en m.b.v. $(document).ready(function(){}) binnen de body zetten
var timerID=null;
var useHamb = null;
var currentRowKey = null;
window.activerow = null;

function delayed(delay, fn)
{
    if (window.timerID)
        clearTimeout(window.timerID);
    window.timerID = setTimeout(fn, delay);
}
function doFilter(deze)
{
    var deze = $("#autofilter");
    var valThis = deze.val().toLowerCase();
    $('table.rstable>tbody>tr').each(function(){
        var text = $(this).text().toLowerCase();
        var moretext = ($(this).find("span.rsTruncmore").attr('resttxt')||"").toLowerCase();
        $(this).toggle(text.indexOf(valThis) > -1 || moretext.indexOf(valThis) > -1);
    });
    if (typeof updateTableHeaders == 'function')
        updateTableHeaders();
}

if (window.$)
$(document).ready(function() {
    if (typeof(postformHTML)!="undefined") $("body").append(postformHTML);

    if ($('table.rstable>tbody>tr').length > 4)
    {   // Uitsluitend als de frameheader direct voor de omsluitende collapseblock komt
        // Voorkomt dat het bij factuurregels of veel bezoekers bovenin het scherm komt
        // Die schermen hebben voor de details namelijk geen IFRAMER_HEADER
        var collapse = $('table.rstable').closest("#collapseblock");
        var collapsePrev;

        // Als de hambdropdown div tussendoor komt, 1 opschuiven
        if (collapse.prev().prop("className") == "hambdropdown")
            var collapsePrev = collapse.prev().prev(".fcltframeheader");
        else
            var collapsePrev = collapse.prev(".fcltframeheader");

        collapsePrev.find("#iframerextratitle").after("<input id='autofilter' type='text' placeholder='"+L("lcl_autofilter")+"'>");
        $("#autofilter")
            .click(function (e) {e.stopPropagation()})
            .keyup(function(e){
                if (e.which == 27) {
                    $("#autofilter").val("");
                }
                delayed(200, doFilter);
            });
    };
    var lastChecked = null;
    function kliklist (doMulti)
    {
        $(this).closest("tr").toggleClass("selected", this.checked);
        if(!lastChecked) {
            lastChecked = this;
            return;
        }

        if(doMulti)
        {
            window.getSelection().removeAllRanges(); // Anders blijft door de shift tekst geselecteerd
            $chkboxes = $('input.multiselect');
            var start = $chkboxes.index(this);
            var end = $chkboxes.index(lastChecked);

            $chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1)
                    .prop('checked', lastChecked.checked)
                    .closest("tr").toggleClass("selected", lastChecked.checked);
        }
        toggleFooter.apply($(this).closest("table")[0].id);
        lastChecked = this;
    }
    $(document).ready(function() {
        // Op hele TD klikken voor checkbox
        $('td:has(:checkbox.multiselect)').click(function (e) {
            if (!$(e.target).is('input'))
            {
               $('input:checkbox', this).prop('checked',!$('input:checkbox', this).prop('checked'));
               kliklist.apply($('input:checkbox', this)[0], [e.shiftKey]);
               return false;
            }
        });
        $('th.multiselect:has(:checkbox)').click(function (e) {
            if (!$(e.target).is('input'))
            {
               $('input:checkbox', this).prop('checked',!$('input:checkbox', this).prop('checked'));
               checkAll($(this).closest("table")[0].id, $('input:checkbox', this)[0])
               return false;
            }
        });

        // Bij multi-select Shift-toets gebruiken voor een range
        var $chkboxes = $('input.multiselect');
        $chkboxes.click(function(e) {
                kliklist.apply(this, [e.shiftKey]);
            })
    });
});

function resizeWhenInIFrame()
{
  FcltMgr.resized();
}

function largerWhenInIFrame()
{
  FcltMgr.resized(window, { largerOnly: true });
}

function hideInlineDetails(thisTR)
{
  $(thisTR).find(".inlinedetails").toggleClass("closed");
  $(thisTR).find(".inlinedetails").html("<i class='fa fa-fw fa-plus-square-o'>");
  var thisTABLE = thisTR.parentNode;
  if (thisTABLE.nodeName == "TBODY")
    thisTABLE = thisTABLE.parentNode; // Indien de tabel een <tbody> heeft dan de parent <table> pakken.
  thisTABLE.deleteRow(thisTR.rowIndex + 1); // De volgende rij verwijderen.
  thisTR.inlineVisible = false;
  return false;
}

function hideAllInlineDetails(ID)
{
  $("#" + ID).find("tr[inlineVisible=true]").each(function (i) { hideInlineDetails(this)});
  resizeWhenInIFrame();
}

function showInlineDetails(thisTD, strfnURL, position)
{
  var thisTR = thisTD.parentNode;
  var thisTRid = thisTR.id;
  var thisRowkey = thisTR.getAttribute("ROWKEY");
  if (thisTR.inlineVisible)
      return hideInlineDetails(thisTR);
  $(thisTR).find(".inlinedetails").toggleClass("closed");
  $(thisTR).find(".inlinedetails").html("<i class='fa fa-fw fa-minus-square-o'>");
  thisTR.inlineVisible = true;
  var thisTABLE = thisTR.parentNode;                 // Parent node kan ook <tbody> zijn
  if (thisTABLE.nodeName == "TBODY")
    thisTABLE = thisTABLE.parentNode; // Indien de tabel een <tbody> heeft dan de parent <table> pakken.
  var newRow = thisTABLE.insertRow(thisTR.rowIndex + 1); // De nieuwe rij erna toevoegen.
  newRow.id = thisTRid + "inline"
  newRow.insertCell(0);
  var theCell = newRow.insertCell(1);
  theCell.innerHTML = L("lcl_shared_loading");
  theCell.colSpan=thisTR.children.length - 2;
  if (position == null) position = 3;
  for (var i = 0; i < position - 2; i++)
    newRow.insertCell(1);
  var xurl = eval(strfnURL).call(null, thisTR);
  $.ajaxSetup({ cache: true });
  theCell.id = "tdinline";
  $(theCell).load(xurl, largerWhenInIFrame);
  return false;
}

function loadInlineDetails(url)
{
  $("#tdinline").load(url, largerWhenInIFrame);
}

// forTouch doen we geen mouseover's. Die maken dat je veel te veel moet klikken
function initActions(tableID, hambType)
{
    useHamb = hambType;
    $(function () {
            $("#" + tableID)
                        .on('click', '.multiselect', FcltMgr.stopPropagation)
                        .on('click', '.multiselect', function() { toggleFooter.apply(tableID) } );
            if (hambType == 0) // No hamburger, just mouseOver
            {
                $("#" + tableID)
                            .on('click', 'tr', defaultAction)
                            .on('mouseover', 'tr', showActions)
                            .on('mouseout', 'tr', hideActions);
                $("#allactions_" + tableID +".allactions")
                            .on('mouseover', function (evt) { evt.stopPropagation() } )
                            .on('mouseout', function (evt) { evt.stopPropagation() } );
            }
            else
            {
                $(document).add(parent.document).add(parent.parent.document).click(defaultHamburgerAction);
                $(document).ready(willHide);
                $("#" + tableID)
                            .on('click', 'tr', defaultHamburgerAction)
                            .on('mouseover', 'tr', hambSetCursor);
                if (hambType == 1) // Hamburger onClick
                {
                    $("#" + tableID)
                                .on('click', '.hamburger', showHamburgerActions)
                                .on('click', '.hamburger', FcltMgr.stopPropagation);
                }
                else if (hambType == 2) // Hamburger onMouseOver
                {
                    $("#" + tableID)
                                .on('mouseenter', '.hamburger', showHamburgerActions)
                                .on('click', '.hamburger', FcltMgr.stopPropagation);
                }
            }
    });
}

function $currentActionsDiv()
{
    if (!window)
        return $();
    var tbl = $(window.activerow).closest("table.rstable");
    if (!tbl.length)
        return $();

    return $("#allactions_" + tbl[0].id +".allactions");
}

function toggleFooter()
{
    var show = false;
    var nn = $("#" + this).find(".multiselect:checked").length;
    var footerButtons = $("#" + this).find("#multiactiondiv");
    if (nn)
    {
        footerButtons.css('visibility','visible');
        if (nn == 1)
            $("span#multilabel").text(L("lcl_with_selected1").format(nn));
        else
            $("span#multilabel").text(L("lcl_with_selected").format(nn));
    }
    else
    {
        footerButtons.css('visibility','hidden');
    }
}

function willHide()
{
    $("li#printhamburger").each(function() {
        var attribute = $(this).attr('fcltclick');
        if (attribute)
            $(this).attr('fcltclick', attribute + "hideActions();");
    });
}

function defaultHamburgerAction(event)
{
    var thisTR = $(this).closest('tr')[0];

    if ($('li.byHamburger').length > 0 && !($('li.byHamburger').hasClass('hidden')))
        $('li.byHamburger').toggleClass('hidden');

    hideActions.apply(thisTR, [event]);

    if (!!$(event.currentTarget).attr("ROWKEY"))
        defaultAction.apply(thisTR, [event]);
}

function defaultAction(event)
{
    var key = this.getAttribute("ROWKEY");
    window.activerow = this;
    var $actiondiv = $currentActionsDiv();
    if (!key)
    {
        $actiondiv.hide();
        return;
    }

    var bits = String(this.getAttribute('ACTIONBITS'));
    $actiondiv.find("span.ia2").each(function (i)
    {
        if (bits.substr(i,1) == 1 && this.getAttribute("isdefault") == 1)
        {
            $(this).trigger('click');
        }
    });
}

function updateEventHandlers(showingInline)
{
    if (!window)
        return;
    var tableID = $(window.activerow).closest("table.rstable").attr("id");
    if (showingInline)
    {
        $("#" + tableID)
                    .off('mouseenter', '.hamburger');
        $("div.allactions, div.hamburger, .fa-bars, td.hambCont, span.ia2")
                    .on('mouseleave', function(e) {
                        if (checkRelated(e)) return;
                        hideActions(e);
                    });
    }
    else
    {
        $("#" + tableID)
                    .on('mouseenter', '.hamburger', showHamburgerActions);
        $("div.allactions, div.hamburger, .fa-bars, td.hambCont, span.ia2")
                    .off('mouseleave');
    }
}

// find if anything in array 'haystack' matches anything in array 'arr'
var matchAny = function (haystack, arr) {
    return arr.some(function (v) {
        return haystack.indexOf(v) >= 0;
    });
};

// Checks whether the related class should trigger hideActions() or keep the inline-actions menu open (used for useHamb == 2)
var checkRelated = function(e) {
    if (!e.relatedTarget)
        return false;
    var tg = e.target.className.split(" ");
    var related = e.relatedTarget.className.split(" ");
    var inlineClasses = ["allactions", "ia2"];
    if (!matchAny(related.concat(tg), inlineClasses) &&
        $(e.target).closest("tr").attr("ROWKEY") !== $(e.relatedTarget).closest("tr").attr("ROWKEY"))
            return false;
    var relatedArray = ["hambCont", "allactions"];
    if ($(e.relatedTarget).parents(".hambCont")[0] || $(e.relatedTarget).parents(".allactions")[0] || matchAny(related, relatedArray))
        return true;
    return false;
}

function hideActions(event)
{
    if ((useHamb == 0 && window.activerow != this) || (useHamb != 0 && $currentActionsDiv().css('display') != "none")) // voorkom hide als je muis boven de buttons beweegt
    {
        $currentActionsDiv().hide();
        if (useHamb == 2) updateEventHandlers(false);
    }
    if (event)
        event.stopPropagation();
}

function hambSetCursor(event)
{
    if (this.getAttribute("ROWKEY") == null) return;
    window.activerow = this;
    var $actiondiv = $currentActionsDiv();
    event.stopPropagation();

    var bits = String(this.getAttribute('ACTIONBITS'));
    $actiondiv.find("span.ia2").each(function (i)
    {
        if (bits.substr(i,1) == 1 && this.getAttribute("isdefault") == 1)
            $(window.activerow).css("cursor", "pointer");
    });
}

function showHamburgerActions(event)
{
    if ($currentActionsDiv().css('display') == "none" || useHamb == 1)
    {
        var thisTR = $(this).closest('tr')[0];
        showActions.apply(thisTR, [event]);
    }
}

function showActions(event) // event op de mouseover van resultsettable
{
    var key = this.getAttribute("ROWKEY");
    if (!key
        || $(event.target).is('input:checkbox')
        || $(event.target).find('input:checkbox').length
        || (useHamb != 0 && currentRowKey == key && $currentActionsDiv().css('display') != "none"))
    {
        hideActions(event)
        return;
    }
    else if (useHamb != 0)
        currentRowKey = key;
    if (!$('li.byHamburger').hasClass('hidden'))
        $('li.byHamburger').toggleClass('hidden');
    var mustHide = ( window.activerow != this );

    window.activerow = this;
    var $actiondiv = $currentActionsDiv();
    if (mustHide)
        $actiondiv.stop().hide();
    $actiondiv.fadeIn('fast');
    event.stopPropagation();
    var bits = String(this.getAttribute('ACTIONBITS'));
    // Zet alle actions aan die enabled zijn
    window.ww = 0;
    var actionDivHeight = 0;

    var anyShow = false;
    $actiondiv.find("span.ia2").each(function (i)
    {
        if (bits.substr(i,1) == 1 && this.getAttribute("isdefault") == 1)
            $(window.activerow).css("cursor", "pointer");
        var show = bits.substr(i,1) == 1 && (this.getAttribute("isdefault") != 1 && this.getAttribute("onlymulti") != 1);
        $(this).toggle(show)
        if (show)
        {
            actionDivHeight += 27; // TODO: TEMP hardcoded
            window.ww += $(this).outerWidth();
            anyShow = true;
        }
    });

    if (!anyShow)
    {
        $actiondiv.hide();
        return;
    }

    var isInline = this.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName === "TD";
    var hasMaxHist = $("#rsMaxHistoryB")[0];
    var inlineCorr = isInline ? (hasMaxHist ? 47 : 30) : 0;

    if (useHamb != 0)
    {
        if (useHamb != 0) $actiondiv.css('height', actionDivHeight);

        var hambImg = $(this).find("div.hamburger").children()[0];

        var trHeight = $(this).outerHeight();
        var outBounds = $(window.parent).outerHeight() < $(window).outerHeight();
        var pageHeight = outBounds ? $(window.parent).outerHeight() : $(window).outerHeight();
        var dropDownHeight = $actiondiv.outerHeight();
        var scrollCorr = 0;

        outsideFrame = $(window.frameElement).offset();
        if (outsideFrame && outBounds)
            scrollCorr = $(window.parent).scrollTop() - outsideFrame.top;

        var trTop = $(this).offset().top;
        var pageBottom = pageHeight + scrollCorr;
        var dropDownBottom = trTop + dropDownHeight;

        if (dropDownBottom > pageBottom)
            $actiondiv.css('top', pageBottom - dropDownHeight - inlineCorr); // bottom of div == bottom of page
        else
            $actiondiv.css('top', trTop - inlineCorr);                       // aligned with the hamburger

        if (hambImg) $actiondiv.css('left', $(hambImg).position().left + $(hambImg).width() + "px");
        else
        {
            // afvangen? div.hamburger niet gevonden of heeft geen children()
        }


    }
    else
    {

        $actiondiv.css('top', $(this).offset().top + $(this).outerHeight() - $actiondiv.outerHeight() - 5 - inlineCorr + "px");

        var hasActionsCol = $actiondiv.attr("hasActionsCol");
        var tdhasact = $(this).find("td")[hasActionsCol];

        if (tdhasact)
            $actiondiv.css('left', $(tdhasact).position().left + "px");
        else // dan maar rechts uitlijnen?
        {    // TODO: Forceren dat het niet buiten beeld valt als er een scrollbar is?
            $actiondiv.css('left', $(this).position().left + $(this).width() - window.ww - 10 + "px");
        }
    }
    if (useHamb == 2) updateEventHandlers(true);
    // FcltMgr.resized();
}

//actions[i].multiOnce
function doA(evt, thisSPAN, theAction)
{
  //$(thisSPAN).css('visibility', 'hidden'); // Verwijder de actie direct zodat dubbelklikken geen tweede aanroep kan veroorzaken.
  FcltMgr.stopPropagation(evt);

  eval(theAction).call(null, window.activerow);

  return false;
}

// Als doA maar dan voor actions die ook multiOnce kunnen: geef een rowArray (met één element) door ipv row
function doAm(evt, thisSPAN, theAction)
{
  FcltMgr.stopPropagation(evt);

  var rowArray = [ window.activerow ];
  eval(theAction).call(null, rowArray);

  return false;
}

function getKeyString(rowArray)
{
  var key;
  var keyString = [];
  for (var i = 0; i < rowArray.length; i++)
  {
    key = rowArray[i].getAttribute("ROWKEY");
    keyString.push(key);
  }
  return keyString.join(",");
}

function doMulti(thisID, func, tekst, onceMulti)
{

  var regels = $("#" + thisID + " .multiselect:checked");
  if (regels.length > 0)
  {
    FcltMgr.confirm(L("lcl_shared_doaction").format(tekst, regels.length), function() {
        // Als multiOnce is gedefinieerd dan wordt de actie 1 keer aangeroepen waarbij een string met keys wordt meegegeven aan de actiefunctie
        // anders wordt voor elke aangevinkte regel de actie aangeroepen waarbij elke keer een key wordt meegegeven aan de actiefunctie

        var multiOnce = false;
        var multiOnceArray = new Array();
        var teller = 0;
        $("#" + thisID + " .multiselect:checked").each(function() {
            teller++;
            var rowData = eval('(' + this.parentNode.parentNode.getAttribute("ROWDATA") + ')');
            multiOnce = onceMulti;
            if (multiOnce)
            {
                multiOnceArray.push(this.parentNode.parentNode);
            }
            else
                eval(func).call(null, this.parentNode.parentNode, true); // true voor noconfirm i.g.v. multi actie
        });
        if (multiOnce)
            eval(func).call(null, multiOnceArray, true); // true voor noconfirm i.g.v. multi actie
    });
  }
}

function checkAll(thisID, zelf)
{
  $("#"+thisID+" .multiselect").each(function()
  {
    this.checked = zelf.checked;
  });
  $("#"+thisID+" .master").each(function()
  {
    this.checked = zelf.checked;
  });
  toggleFooter.apply(thisID);
}
function RSdefaultAction(thisID, defaultAction)
{
  var row = $("#"+thisID)[0].getFirstSelectedRow();
  $("#"+thisID)[0].clearSelection();
  eval(defaultAction).call(null, row);
}

// Als op ...meer geklikt bij afgekapte tekst
function expandTruncate(evt, elm)
{
  if (!evt) evt = window.event;
  elm.innerHTML=elm.getAttribute("resttxt").replace(/\n/ig,"<br>");
  elm.className = "";
  FcltMgr.stopPropagation(evt);
  FcltMgr.resized();
  return false;
}