/*
     $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. $(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);
}
window.lastFilter = "";

function doFilter()
{
    var valThis = $("#autofilter").val().toLowerCase();
    // Zolang je *meer* letters tikt hoeven wel altijd alleen te hiden
    // Dat is op IE11 veel sneller dan toggle
    var hideOnly = valThis.indexOf(window.lastFilter) == 0;
    $("table.rstable > tbody > tr").each(function() {
        var text = $(this).text().toLowerCase();
        var moretext = ($(this).find("span.rsTruncmore").attr("resttxt")||"").toLowerCase();
        var found = text.indexOf(valThis) > -1 || moretext.indexOf(valThis) > -1;
        if (!found)
        {
            this.style.display = 'none'; // Veel sneller met IE11 dan $(this).hide();
            $(this).find("input.multiselect").prop("checked", false);
        }
        else if (!hideOnly)
            $(this).show();
    });
    window.lastFilter = valThis;
    toggleFooter($("table.rstable")[0].id);
    FcltMgr.resized();
}

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

      if ($("table.rstable > tbody > tr").length > 4 && !$('table.rstable[noqfilter="1"]').length)
      {   // 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 $frameHeader = collapse.prev(".fcltframeheader");
          $frameHeader.find("#iframerextratitle").before("<input id='autofilter' type='text' placeholder='" + safe.htmlattr(L("lcl_autofilter")) + "'>");
          if (typeof buttons_hit_test === "function")
              buttons_hit_test();
          $("#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);
          toggleFooter($(this).closest("table")[0].id);

          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);
          }
          lastChecked = this;
      }
      $(function()
      {
          // Op hele TD klikken voor checkbox
          $('table').on('click', 'td:has(:checkbox.multiselect)', function (e) {
              if (!$(e.target).is('input'))
              {
                 $('input:checkbox', this).prop('checked',!$('input:checkbox', this).prop('checked')).change();
                 kliklist.apply($('input:checkbox', this)[0], [e.shiftKey]);
                 return false;
              }
          });
          $('table').on('click', 'th.multiselect:has(:checkbox)', function (e) {
              if (!$(e.target).is('input'))
              {
                 $('input:checkbox', this).prop('checked',!$('input:checkbox', this).prop('checked')).change();
                 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]);
              })
          if (typeof updateTableHeaders === "function")
              updateTableHeaders();
      });
  });

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

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

function hideInlineDetails(thisTR)
{
  var rowData = JSON.parse(thisTR.getAttribute("ROWDATA"));
  $(thisTR).find(".inlinedetails").toggleClass("closed");
  if (rowData.mldOpdrChanged)
      $(thisTR).find(".inlinedetails").html(I("fa-square-exclamation"));
  else
      $(thisTR).find(".inlinedetails").html(I("fa-plus-square"));
  var thisTRParent = thisTR.parentNode; // TBODY of TABLE
  thisTRParent.deleteRow(thisTR.sectionRowIndex + 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("fa-minus-square"));
  thisTR.inlineVisible = true;
  var thisTRParent = thisTR.parentNode; // TBODY of TABLE
  var newRow = thisTRParent.insertRow(thisTR.sectionRowIndex + 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 ()
    {
            toggleFooter(tableID);
            $("#" + tableID)
                        .off('click')
                        .on('click', '.multiselect', FcltMgr.stopPropagation)
                        .on('click', '.multiselect', function() { toggleFooter(tableID) } );
            if (hambType == 0) // No hamburger, just mouseOver
            {
                $("#" + tableID)
                            .on('click', 'tr', defaultAction)
                            .off('mouseover mouseout')
                            .on('mouseover', 'tr', showActions)
                            .on('mouseout', 'tr', hideActions);
                $("#allactions_" + tableID +".allactions")
                            .off('mouseover mouseout')
                            .on('mouseover', function (evt) { evt.stopPropagation() } )
                            .on('mouseout', function (evt) { evt.stopPropagation() } );
            }
            else
            {
                $(document).add(parent.document).add(parent.parent.document).click(defaultHamburgerAction);
                $(willHide);
                $("#" + tableID)
                            .on('click', 'tr', defaultHamburgerAction)
                            .off('mouseover')
                            .on('mouseover', 'tr', hambSetCursor);
                if (hambType == 1) // Hamburger onClick
                {
                    $("#" + tableID)
                                .on('click', '.hambCont', showHamburgerActions)
                                .on('click', '.hambCont', FcltMgr.stopPropagation);
                }
                else if (hambType == 2) // Hamburger onMouseOver
                {
                    $("#" + tableID)
                                .off('mouseenter')
                                .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(tableID)
{
    var nn = $("#" + tableID).find(".multiselect:checked").length;
    var footerButtons = $("#" + tableID).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#printhamburger").find("> .fa-times").toggleClass("fa-bars fa-times");
        $("li.byHamburger").toggleClass("hidden");
    }

    hideActions.apply(thisTR, [event]);

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

function defaultAction(event)
{
    if (window.getSelection().toString()) {
        return;
    }
    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');
    }
}

// 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 related = " " + e.relatedTarget.className + " ";
    var relatedToDropdown = ["allactions", "ia2"];
    var relatedToOther    = ["hambCont"];

    for (var i = 0; i < relatedToDropdown.length; i++)
        if (related.indexOf(" " + relatedToDropdown[i] + " ") != -1)
            return true;

    for (var i = 0; i < relatedToOther.length; i++)
        if (related.indexOf(" " + relatedToOther[i] + " ") != -1)
        {
            if ($(window.activerow) != null && $(window.activerow).attr("ROWKEY") !== $(e.relatedTarget).closest("tr").attr("ROWKEY"))
                // Dezelfde rij dus related
                return false;
            // Niet dezelfde rij, of rij niet gevonden -> niet related
            return true;
        }
    // Niet related dus
    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 != 0)
            $(window.activerow).closest("table.rstable").find(".hamburger > .fa-times").toggleClass("fa-times fa-bars");
        if (useHamb == 2) updateEventHandlers(false);
    }
    if (event)
        event.stopPropagation();
}

function hambSetCursor(event)
{
    if (this.getAttribute("ROWKEY") == null) return;
    // if (window.activerow == null) then $currentActionsDiv() has not been determined yet
    // if ($currentActionsDiv() is visible) then we don't want to change window.activerow
    if (window.activerow == null || $currentActionsDiv().css("display") == "none")
        window.activerow = this;
    var $actiondiv = $currentActionsDiv();
    event.stopPropagation();

    var bits = String(this.getAttribute('ACTIONBITS'));
    var thisRow = this;
    $actiondiv.find("span.ia2").each(function (i)
    {
        if (bits.substr(i,1) == 1 && this.getAttribute("isdefault") == 1)
            $(thisRow).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#printhamburger").find("> .fa-times").toggleClass("fa-bars fa-times");
        $("li.byHamburger").toggleClass("hidden");
    }
    var mustHide = (window.activerow != this);
    if (mustHide) $(window.activerow).find(".hamburger > .fa-times").toggleClass("fa-times fa-bars");

    window.activerow = this;
    $(this).find(".hamburger > .fa-bars").toggleClass("fa-times fa-bars");
    var $actiondiv = $currentActionsDiv();
    if (mustHide)
        $actiondiv.stop().hide();
    if (useHamb == 2)
        $actiondiv.show();
    else
        $actiondiv.stop().fadeIn("fast");
    event.stopPropagation();
    var bits = String(this.getAttribute('ACTIONBITS'));
    // Zet alle actions aan die enabled zijn
    var actionDivHeight = 0;
    var actionSpanHeight;
    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)
        {
            actionSpanHeight = parseFloat($(this).css("height"));
            actionDivHeight = (useHamb == 0 ? Math.max(actionDivHeight, actionSpanHeight) : actionDivHeight + actionSpanHeight); // horizontaal : verticaal
            anyShow = true;
        }
    });

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

    $actiondiv.height(actionDivHeight);

    var newPos = { "left": 0, "top": 0 };
    if (useHamb != 0)
    {
        var hambImg = $(this).find("div.hamburger").children()[0];

        var outBounds = $(window.parent).outerHeight() < $(window).outerHeight();
        var pageHeight = outBounds ? $(window.parent).outerHeight() : $(window).outerHeight();
        var dropDownHeight = parseFloat($actiondiv.css("height"));
        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) // bottom of div == bottom of page
            newPos.top = pageBottom - dropDownHeight;
        else                             // aligned with the hamburger
            newPos.top = trTop;

        if (hambImg)
            newPos.left = $(hambImg).offset().left + $(hambImg).width();
        else
        {
            // afvangen? div.hamburger niet gevonden of heeft geen children()
        }
    }
    else
    {
        newPos.top = $(this).offset().top                   // De offset.top van deze tr
                   + parseFloat($(this).css("height"))      // De hoogte van deze tr
                   - parseFloat($actiondiv.css("height"));  // De hoogte van de $currentActionsDiv

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

        if (tdhasact)
            newPos.left = $(tdhasact).offset().left;
        else // dan maar rechts uitlijnen?
            newPos.left = $(this).offset().left                                         // De offset.left van deze tr
                        + Math.min($(window).width(), parseFloat($(this).css("width"))) // min(window-breedte, tr-breedte)
                        - parseFloat($actiondiv.css("width"))                           // De breedte van de $currentActionsDiv
                        - 6;                                                            // En een paar pixels voor de mooi
    }
    $actiondiv.offset(newPos);
    if (useHamb == 2) updateEventHandlers(true);
}

//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((regels.length == 1 ? L("lcl_shared_doaction1") : 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 = JSON.parse(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").not(":hidden").each(function()
  {
    this.checked = zelf.checked;
    $(this).closest("tr").toggleClass("selected", this.checked);
  });
  $("#"+thisID+" .master").each(function()
  {
    this.checked = zelf.checked;
    $(this).closest("tr").toggleClass("selected", this.checked);
  });
  toggleFooter(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;
}

// columns manipulation functions
$(function ()
{
  if ($("#rscolpicker").length)
  {
    $("#rscolpicker table tbody" ).not('thead tr').sortable({ axis: "y", distance: 10 });
  }

  $("#chkall").click(function () // Allemaal aan of uit
  {
      $("#rscolpicker tr").find("input[type=checkbox][name=usefield]").prop("checked", $(this).prop("checked"));
      if (!$(this).prop("checked"))
        $("#rscolpicker tr").find("input[type=checkbox][name=combine]").prop("checked", false);
  });

  function setRscolsClass()
  {
    // remove classes if usefield is unchecked
    var $this = $(this);
    var $thistr = $this.closest("tr");
    if (!$thistr.find("input[type=checkbox][name=usefield]").prop("checked"))
    {
      $thistr.removeClass("rscols_combined rscols_combined_first rscols_combined_last");
      $thistr.find("input[type=checkbox][name=combine]").prop("checked", false).attr("disabled", true);
    }
    else if(!$thistr.find("input[type=checkbox][name=combine]").attr("disabled"))
    {
      $thistr.find("input[type=checkbox][name=combine]").attr("disabled", false);
    }
    // set combined class
    $("#rscolpicker tr").each(function ()
    {
      var $this = $(this);
      $this.toggleClass("rscols_combined", $this.find("input[type=checkbox][name=usefield]").prop("checked") && $this.find("input[type=checkbox][name=combine]").prop("checked"));
    });
    // set combined_first class
    $("#rscolpicker tr input[type=checkbox][name=usefield]:checked").each(function ()
    {
        var $this = $(this);
        var $thistr = $this.closest("tr");
        if (!$thistr.hasClass("rscols_combined"))
        {
          var $nexttr = $thistr.next("tr");
          while ($nexttr.length && !$nexttr.find("input[type=checkbox][name=usefield]").prop("checked")) {
            $nexttr = $nexttr.next("tr");
          }
          if ($nexttr.length) {
            $thistr.toggleClass("rscols_combined_first", $nexttr.find("input[type=checkbox][name=combine]").prop("checked"));
          }
        }
    });
    // set combined_last class
    $("#rscolpicker tr input[type=checkbox][name=usefield]:checked").each(function ()
    {
      var $this = $(this);
      var $thistr = $this.closest("tr");
      if ($thistr.hasClass("rscols_combined"))
      {
        var $nexttr = $thistr.next("tr");
        while ($nexttr.length && !$nexttr.find("input[type=checkbox][name=usefield]").prop("checked"))
        {
          $nexttr = $nexttr.next("tr");
        }
        $thistr.toggleClass("rscols_combined_last", !$nexttr.length || !$nexttr.find("input[type=checkbox][name=combine]").prop("checked"));
      }
    });
  }

  $("input[type=checkbox]", "#rscolpicker").change(setRscolsClass);

  $("#rscolpicker").click(function(event)
  {
      event.stopPropagation();
  });

  $("#rscolpicker").mouseup(function(event)
  {
      function protectFirstCombine(event)
      {
          $("input[type=checkbox][name=combine], input[type=checkbox][name=usefield]", "#rscolpicker").prop("disabled", false);
          $("input[type=checkbox][name=combine]:first", "#rscolpicker").prop("disabled", true).prop("checked", false);
          $("input[type=checkbox][name=usefield]:first", "#rscolpicker").prop("disabled", true).prop("checked", true);
          $("input[type=checkbox][name=combine]", "#rscolpicker").change();
      }
      setTimeout(protectFirstCombine);
  });
  $("#rscolpicker").mouseup();

});

async function rscols_doReset(type)
{
  $("#rscolpicker").hide();

  if (!await validateForm("u2"))
    return false;
  $("#resetcols").val("1");

  var data = {code: $("#code").val(), resetcols: 1};
  var callback = function (json, textStatus) {
    if (type == "POST")
      doOutput(0);
    else
      FcltCallbackRefresh(json, textStatus);
  };
  protectRequest.dataToken(data);
  $.post("../shared/rs_columns_save.asp", data, callback, "json");
}

async function rscols_doSubmit(type)
{
  $("#rscolpicker").hide();

  if (!await validateForm("u2"))
    return false;

  var cols = [];
  $("#rscolpicker tr").each(function()
      {
          if (!this.id)
              return;

          if (this.id == "chk_pivot")
              return;

          cols.push(this.id + "|" + ($(this).find("input[type=checkbox][name=usefield]").prop("checked")? "V":"I") + "|" + ($(this).find("input[type=checkbox][name=combine]").prop("checked")? "1":"0"));
      }
  );
  $("#columns").val(cols.join(","));

  $("#workFrame").width($(window).width()); // grafieken 'krimpen' slecht

  var data = {code: $("#code").val(), columns: cols.join(",")};
  var callback = function (json, textStatus) {
    if (type == "POST")
      doOutput(0);
    else
      FcltCallbackRefresh(json, textStatus);
  };
  protectRequest.dataToken(data);
  $.post("../shared/rs_columns_save.asp", data, callback, "json");
}
