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

     File:   Facilitor.asp

     =============== FACILITOR 5i MAIN ENTRY POINT =============
*/
%>
<!--#include file="../Shared/common.inc" -->
<!--#include file="../shared/iface.inc" -->
<!--#include file="fac_menu.inc" -->
<!--#include file="fac_header.inc" -->
<!--#include file="../aut/login.inc" -->
<!--#include file="../fac/fac_nieuws_forum.inc" -->

<%
  // Als we hier komen hebben we gegarandeerd een user_key > 0

  if (user.isGroupedUser() || Session("login_by_fallback"))
  {
    doLogoff();
    shared.simpel_page(L("lcl_no_auth"));
  }

  FCLTHeader.Requires({ plugins: ["jQuery"],
                        js: ["jquery-ui.js"]}); // css voor header.asp

  var noMenu = false;  // option: do not show a menu
  var noHeader = false;// option: do not show a header
  var noTabs = false;  // option: do not do tabs
  // Logging              option: for internal debugging purposes, bitcoded
  // IHateTabs            option: do not use our internal tabmanager
  // Jumpto               option: for deeplinking, uses an alternate body

  if (Request.QueryString("noMenu").Count>0)    noMenu = true;
  if (Request.QueryString("noHeader").Count>0)  noHeader = true;
  if (Request.QueryString("IHateTabs").Count>0) noTabs = true;

  __Log("Welcome.asp expired?");
  var sql = "DELETE FROM fac_menu"
          + " WHERE fac_menu_altgroep = 5"
          + "   AND fac_menu_alturl = " + safe.quoted_sql(S("fac_firstlogin_url"))
          + "   AND prs_perslid_key = " + user_key
          + "   AND fac_menu_aanmaak < SYSDATE - " + S("fac_firstlogin_expire");
  Oracle.Execute(sql, true);

  // autoopen ophalen uit database
  var autoopen = [];
  var sql = "SELECT fac_menu_altlabel"
          + "     , fac_menu_alturl"
          + "     , fac_menu_key"
          + "     , fac_menu_filter"
          + "     , fac_menu_advfilter"
          + "  FROM fac_menu"
          + " WHERE fac_menu_altgroep = 5"
          + "   AND prs_perslid_key = " + user_key
          + " ORDER BY fac_menu_volgnr";
  var oRs = Oracle.Execute(sql);
  while (!oRs.eof)
  {
    var menu_tab = { u: oRs("fac_menu_alturl").Value || "",
                     t: oRs("fac_menu_altlabel").Value || "",
                     k: oRs("fac_menu_key").Value || ""
                   };
    if (menu_tab.u == S("fac_firstlogin_url"))
      menu_tab.activate = true;
    autoopen.push(menu_tab);
    oRs.MoveNext();
  }
  oRs.Close();

  // URL param jumpto can be set like:
  // http://facws001/trunk/default.asp?jumpto=visitors/register_input.asp
  if (Request.QueryString("Jumpto").Count>0) // Remember it
    Session("FirstPage")=''+Request.QueryString("Jumpto")

  if (Session("FirstPage") && typeof(Session("FirstPage"))!="undefined" )
  {   // Deeplinking
      autoopen = [{ u: Session("FirstPage"), activate: true, nopin: true }]; // de standaard autoopen dan niet meer
  }
  Session.Contents.Remove("FirstPage"); // zeker weg

  if (autoopen.length == 0 || !noTabs)
  {
      if (S("widgetportal") > 0)
          firstPage = "appl/fac/fac_widget_page.asp?fp=1&wgt_page_key=" + S("widgetportal");
      else
          firstPage = "appl/fac/myfacilitor.asp";
      var hasActivate = false;
      for (var menu in autoopen)
      {
          hasActivate |= autoopen[menu].activate;
      }
      autoopen.unshift({ u: firstPage, t: L("lcl_body_portal"), noclose: true, nopin: true, activate: !hasActivate });
  }

if (Session("interface") == "touch") { %>
<html>
<% } else { %>
<html style='overflow:hidden'>
<% } %>
<head>
<%
    FCLTHeader.Generate()
    // If we think the user uses an unsupported browser, we warn the user.
    // Note: this check is informative only, the user could continue despite the unsupported browser (like IE6)
%>
    <script type="text/javascript">
        $(function() {
            if (<%=(!device.test(device.isSupported) && S("checkBrowser") == 1 ? "true" : "false")%> || !(Modernizr.promises && Modernizr.strictmode && Modernizr.arrow)) {
                FcltMgr.alert(L("lcl_invalid_browser"));
            }
        });
    </script>
<%

  %><link rel="shortcut icon" type="image/x-icon" href="<%= rooturl + "/" + S("fac_favicon_folder") %>/favicon.ico" />
    <link rel="apple-touch-icon"                  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon.png" />
    <link rel="apple-touch-icon" sizes="57x57"    href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-57x57.png" />
    <link rel="apple-touch-icon" sizes="72x72"    href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-72x72.png" />
    <link rel="apple-touch-icon" sizes="76x76"    href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-76x76.png" />
    <link rel="apple-touch-icon" sizes="114x114"  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-114x114.png" />
    <link rel="apple-touch-icon" sizes="120x120"  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-60@2x.png" />
    <link rel="apple-touch-icon" sizes="144x144"  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-144x144.png" />
    <link rel="apple-touch-icon" sizes="152x152"  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-76@2x.png" />
    <link rel="apple-touch-icon" sizes="180x180"  href="<%= rooturl + "/" + S("fac_favicon_folder") %>/Icon-60@3x.png" />
    <%

    if (Session("interface") == "touch")
    {
        noTabs = true;
        noHeader = true;
        noMenu = true;
    }
%>
<script>
    var tabid = "<%=customerId + "_" + shared.random(16)%>";
    var menuHeaderHTML = "";
    var globalSubmenuDelay = <%=S("submenu_open_delay")%>;
    var scrollbarWidth;
    var timeoutInstance;

    <% if (Session("interfaceforce") == 1) { %>
        window.localStorage.setItem("interface", "<%safe.jsstring(Session("interface"))%>");
    <% } else { %>
        var interface = window.localStorage.getItem("interface");
        if (interface && interface != "<%safe.jsstring(Session("interface"))%>")
        {  // we hadden verkeerd gegokt, localStorage weet het beter
            window.localStorage.setItem("interface", ""); // voor als hij invalid blijkt te zijn
            parent.location.href = "../../default.asp?interface=" + interface;
        }
    <% }
    Session.Contents.Remove("interfaceforce");
    %>

    var notitieFilter = window.localStorage.getItem("notitiefilter");
    if (!notitieFilter) // Als dit item nog niet bestaat, vul dan de default in
        window.localStorage.setItem("notitiefilter", "S,s,S");

    // Functie om de breedte van een scrollbar te berekenen
    function getScrollBarWidth() {
        var $outer = $("<div>").css({visibility: "hidden", width: 100, overflow: "scroll"}).appendTo("body");
        var widthWithScroll = $("<div>").css({width: "100%"}).appendTo($outer).outerWidth();
        $outer.remove();
        return 100 - widthWithScroll;
    }

    function RefreshFacilitor()
    {
      FcltMgr.alert(L("lcl_session_expired"));
      window.location.href="<%=rooturl%>/default.asp?fac_id=<%=customerId%>";
    }

    function myResize(animated)
    {
        var menuIsHidden = $('div#menudivider').hasClass('dividerclosed');
        var hasNoHeader = $("#menutabs > .ui-tabs-nav").hasClass("noToggle");
        var duration = animated ? 300 : 0; // ms
        var animParams = { queue: false, duration: duration };

        if ($("#menutabs").length)
        {
            // Bepaal de breedte van de individuele tabjes
            var menuWidth = menuIsHidden ? 41 : parseFloat($("#menutabs").css("width"));
            var menuDividerWidth = parseFloat($("#menudivider").css("width"));
            var newWidth = $(window).width() - menuWidth - menuDividerWidth;

            $("#menudivider").animate({ left: menuWidth }, animParams);
            $("#maintabs").animate({ left: menuWidth + menuDividerWidth }, animParams);
            $("#maintabs").animate({ width: newWidth }, animParams);
        }
        else
        {
            $("#maintabs").css("left", "0px");
            $("#maintabs").width("100%");
        }

        var topDividerHeight = parseFloat($("#topdivider").css("height"));
        var divTop = ($("#frheader").is(":visible") ? parseFloat($("#frheader").css("height")) : 0);
        var newTop = divTop + topDividerHeight;
        var newHeight = $(window).height() - newTop;

        var tabsHeaderHeight = (menuIsHidden || hasNoHeader) ? 0 : parseFloat($("#menutabs > .ui-tabs-nav").css("height"));
        var heightBetweenTopDividerAndMenu = (menuIsHidden ? parseFloat($("#menutabs > .ui-menu-tabs").css("height") || 0) : 0) + parseFloat($("#menutabs > .menuHeadSpacer").css("height"));
        var filterHeight = menuIsHidden ? 0 : parseFloat($("#menufilter").outerHeight(true));
        var contentHeight = newHeight - heightBetweenTopDividerAndMenu - tabsHeaderHeight - filterHeight;

        $("#topdivider").animate({ top: divTop }, animParams);
        $("#headtoggler").animate({ left: ($(window).width() - 23) }, animParams);

        $("#maintabs, #menutabs, #menudivider").animate({ top: newTop }, animParams);
        $("#menutabs").animate({ height: newHeight }, animParams);
        $("#maintabs").animate({ height: newHeight }, animParams);
        $("#menutabs .ui-layout-content").css("overflow", (menuIsHidden ? "hidden" : "auto")).animate({ height: contentHeight }, animParams).attr("aria-expanded", (menuIsHidden ? "false" : "true"));

        $("#menutoggler").animate({ top: (newHeight - 25) }, animParams);
        $("#menudivider").animate({ height: newHeight }, animParams);

        setTimeout(function () { FcltMgr._pageManager._resize_forMaxTabs(); }, duration);
        FcltMgr._pageManager._timedResizeActiveTab(duration);
    }

    function dropDown(action, animate)
    {
        if ($("#maintabs").is(":animated"))
            return;

        var duration = (typeof animate == "undefined" || animate ? "fast" : 0);
        var openDropdown = !$(".ui-tabs-submenu").is(":hidden");
        var menuIsHidden = $('div#menudivider').hasClass('dividerclosed');

        if (action == "hide" || (!menuIsHidden && !$(this).children("ul").is(":hidden")))
        {
            if (openDropdown)
                $("div.ui-tabs-submenu").stop().fadeOut(duration);
            else
                window.clearTimeout(timeoutInstance);
        }
        else if (globalSubmenuDelay != -1)
        {
            var content = $(this).find("ul").clone(true, false);
            var submenuHeader = $(this).find("span.menukop").html();

            if (submenuHeader && submenuHeader != "")
                content.prepend("<li class=\"submenuHeader mks\">" + submenuHeader + "</li>");

            window.clearTimeout(timeoutInstance);

            timeoutInstance = window.setTimeout(function(that)
            {
                var left = $("#menudivider").get(0).getBoundingClientRect().left;
                if ($(".ui-layout-content").css("overflow") != "hidden" && $(".ui-layout-content").get(0).scrollHeight > $(".ui-layout-content").get(0).clientHeight) // hasScrollbar?
                    left -= scrollbarWidth;

                // Fill submenu with information and style it
                $("div.ui-tabs-submenu").html(content)
                                        .css("left", left)
                                        .css("top", $(that).position().top)
                                        .stop().fadeIn(duration);
                $("div.ui-tabs-submenu ul").css("display", "block")
                                           .addClass("menuDropDown");
                $("div.ui-tabs-submenu ul li").css("display", "list-item");

                if ($(that).position().top + $("div.ui-tabs-submenu").outerHeight() > $("#menutabs").outerHeight()) ////////////////////////////////////////////////
                    $("div.ui-tabs-submenu").css("top", Math.max(-1 * parseFloat($("#menutabs").position().top),    // if (div.dropdownmenu valt onder uit beeld) //
                                                                 ($("#menutabs").outerHeight() -                    //    dan 'submenu.bottom = window.bottom'    //
                                                                  $("div.ui-tabs-submenu").outerHeight())));        //   maar nooit; 'submenu.top < window.top'   //
                timeoutInstance = null;                                                                             ////////////////////////////////////////////////
            }, (openDropdown ? 0 : globalSubmenuDelay), this);
        }
    }

    var checkRelated = function(e) {
        if (!e.relatedTarget) return false;
        var related = " " + e.relatedTarget.className + " ";
        var relatedArray = ['mk', 'mi', 'micon', 'tabicon', 'menuDropDown', 'submenuHeader', 'menuHeadSpacer'];
        for (var i = 0; i < relatedArray.length; i++)
            if (related.indexOf(" " + relatedArray[i] + " ") != -1) return true;
        return false;
    }

    function menuToggles(open)
    {
        var visibility = open ? "visible" : "hidden";
        var padding = open ? ".2em .2em 0" : "0px";
        makeMenuHeaderIcon();
        $('#menutabs').find("li.mklogo").css("visibility", visibility);
        $('#menutabs').find("li.mi").toggle();
        $(".ui-menu-tabs").toggle();
        $('#menutabs .ui-layout-content').find("span.menukop").css("visibility", visibility);
        if (!$("#menutabs>.ui-tabs-nav").hasClass("noToggle"))
            $("#menutabs>.ui-tabs-nav").toggle();
    }

    function makeMenuHeaderIcon()
    {
        if ($("#menutabs").data("ui-tabs") && $("#menutabs").tabs("instance").tabs.length > 1)
        {
            var activeTabIndex = $("#menutabs").tabs("option", "active");
            var activeTab      = $("#menutabs").tabs("instance").tabs[activeTabIndex];
            var newClass       = ["pers", "prof", "mgt"][activeTabIndex];

            $(".ui-menu-tabs").attr("class", "ui-menu-tabs " + newClass);
            $(".tabicon").text($(activeTab).text().slice(0, 1));
        }
    }

    function toggleMenu(init)
    {
        FcltMgr.stopPropagation();
        $("div#menudivider").toggleClass("dividerclosed");
        $("div.ui-tabs-submenu").hide();
        var menuIsClosed = $("div#menudivider").hasClass("dividerclosed");
        if (menuIsClosed)
        {
            if ($("#menufilter").val())
                $("#menufilter").val("").trigger("keyup");
            window.scrollTo(0, 0);

            localStorage.setItem("menuCollapsed", "1");

            globalSubmenuDelay = 0;
            $("li.mk").off("click.open");
            if (!init) // Niet bij initialisatie, dat is al gebeurd
                switchTab();

            window.myResize(!init);
            setTimeout(menuToggles, init ? 0 : 300);
            $('#menutabs').children("input").toggle();
            $("#menutoggler").html("<%=I("fa-caret-right", {fastyle: "fas"})%>");
        }
        else
        {
            localStorage.setItem("menuCollapsed", "0");

            globalSubmenuDelay = <%=S("submenu_open_delay")%>;
            $("li.mk").on("click.open", function()
            {
                window.clearTimeout(timeoutInstance);
                $("div.ui-tabs-submenu").hide();
            });
            $("#menutoggler").html("<%=I("fa-caret-left", {fastyle: "fas"})%>");
            window.myResize(true);
            menuToggles(true);
            setTimeout(function() { $('#menutabs').children("input").toggle().focus() } , 300);
        }
        $(".nomicon").each(function() {
            $(this).text(menuIsClosed ? $(this).siblings(".menukop").text().substr(0, 1) : " ");
        });
    }

    // Function that (re-)creates the skeleton for the tabs-submenu
    function getTabsDropdown(index)
    {
        var tabs = $("#menutabs").tabs("instance").tabs;
        var tabsDropdown = "<ul>";
        var activeTabIndex = index == null ? $("#menutabs").tabs("option", "active") : index;
        for (var i = 0; i < tabs.length; i++)
        {
            var tab_naam = $(tabs[i]).find("span.menutab").text();
            if (i == activeTabIndex)
                tabsDropdown = "<span class='menukop' style='display: none;'>" + safe.html(tab_naam) + "</span>" + tabsDropdown;
            else
                tabsDropdown += "<li class='mi' onclick='switchTab("+i+")' style='display: "+(index == null ? "list-item" : "none")+";'>" + safe.html(tab_naam) + "</li>";
        }
        return "<span class='tabicon'>&nbsp;</span>"+tabsDropdown+"</ul>";
    }

    function switchTab(index)
    {
        // Remake the skeleton for the tabs-submenu (because the active tab changed)
        $("#menutabs li.header-tabs").html(getTabsDropdown(index));

        // Actually switch tabs
        $("#menutabs").tabs({ active: index });

        makeMenuHeaderIcon();
    }

    $(function()
    {
        FcltMgr.setData("expired", RefreshFacilitor);

        scrollbarWidth = getScrollBarWidth();

        $('#menutabs').click(function () {
            $("#menufilter").focus();
        });

        $("#menufilter").keyup(function(e) {
            if (e.which == 27) {
                $("#menufilter").val("");
            }
        });

        $('#menutabs').dblclick(function (evt) {
            // Empty space in menu
            if (evt && evt.target && $(evt.target).hasClass("ui-layout-content"))
                toggleMenu();
        });

        // voegt onClick toe aan portaal iconen
        $("div.portalmenukop.withimg").children().not("ul").each(function() {
            $(this).on("click", function() {
                $(this).siblings("ul").find("li").trigger("click");
            }).css("cursor", "pointer");
        });

<% if (!noTabs) { %>
        FcltMgr.HostTabs("maintabs");
        window.onbeforeunload = /*FcltMgr.*/confirmExit;
        window.onunload = /*FcltMgr.*/forcedExit;
        function confirmExit()
        {
            var anyHot = false;
            var i;
            for (i = FcltMgr._pageManager._$tabshost.find( ".ui-tabs-nav li" ).length-1; i > 0 && !anyHot; i--)
            {
                if (FcltMgr._pageManager._panelHot(i))
                    anyHot = true;
            }
            if (anyHot)
                return L("lcl_shared_closeandignore");
            else
                return;
        }

        function forcedExit()
        {
            var i;
            for (i = FcltMgr._pageManager._$tabshost.find( ".ui-tabs-nav li" ).length-1; i > 0; i--)
            {
                var hotwnd = FcltMgr._pageManager._panelHot(i);
                if (hotwnd && hotwnd.onCloseHot)
                    hotwnd.onCloseHot();
            }
        }
        $(window).resize(function() { myResize() });
        window.setTimeout("myResize()", 10);

<%      }
        extra="";
        if (__Logging > 0 && this.Oracle)
        {
            var extra = " {"+custpath.substr(custpath.length-4)+':'+Oracle.RealConnection.Properties("User Name")+'@'+Oracle.RealConnection.Properties("Data source") + "}"
            extra = extra.toUpperCase();
        }
%>
        window.parent.document.title = window.ttl_prefix + L("lcl_facilitor_ie_title") + "<%=extra%>";
<%
        var anyactivate = false;
        if (!noTabs)
        {   // De gepinde tabs op het scherm toevoegen bij <ul><!--hier komen de tabs--></ul>.
            for (var menu in autoopen)
            {
                var pg = autoopen[menu]; // TODO: minder lelijk de ../../ er af.
                if (pg.u.substr(0,6) == "../../")
                    pg.u = pg.u.substr(6);
                if (pg.k)
                    pg.u += (pg.u.indexOf("?")>0?"&":"?") + "has_filters=1&tab_menu_key=" + pg.k;
                if (pg.activate)
                    anyactivate = true;

                %>FcltMgr.openDetail("<%=safe.jsstring(pg.u)%>",
                                      "<%=safe.jsstring(pg.t)%>",
                                      { noactivate: <%=pg.activate?0:1%>,
                                        noclose: <%=pg.noclose?1:0%>,
                                        delayload: true,
                                        showpin: <%=pg.nopin?0:1%>,
                                        menu_key: <%=(pg.k || -1)%> });<%
            }
        }
%>
        $("#menutabs").tabs();
        var selectedTabId = localStorage.getItem("selectedMenuTab");
        if (selectedTabId === null)
            selectedTabId = ($("#PersFAC").length && $("#ProfFAC").length) ? 1 : 0;
        $("#menutabs").tabs("option", "active", selectedTabId);
        $("#menutabs").tabs({
                    beforeActivate:
                        function ( event, ui )
                        {
                            if ($("#menufilter").val()) // reset filter bij tabwissel
                                $("#menufilter").val("").trigger("keyup");
                        }
                    });

<%      if (!noTabs && S("menu_tab_toggles_portalmenu")==1)
        {
            var menuitems  = fillMenuArray(1, { "portalOnly": true });
%>
        if (selectedTabId == 0) // Zelfservice?
        {
<%          if (menuitems && menuitems[0]?1:0) // filled? Als er al een andere actief is gemaakt doen wij het niet meer
            { %>
            FcltMgr.openDetail("appl/fac/fac_portal_menu.asp?groep=0",
                              { titel: $("#menutabs .ui-tabs-active").text(), reuse: true, noactivate: <%=anyactivate?1:0%> });
<%          } %>
        }

        $("#menutabs").tabs({ activate: function(event, ui)
            {
                var filled = [ <%=menuitems[0]?1:0%>,<%=menuitems[1]?1:0%>,<%=menuitems[2]?1:0%> ];
                var groep = { "PersFAC": 0,
                              "ProfFAC": 1,
                              "MgtFAC": 2
                            }[ui.newPanel[0].id];
                if (filled[groep] == 1)
                {
                    FcltMgr.openDetail("appl/fac/fac_portal_menu.asp?groep=" + groep, { titel: ui.newTab.text(), reuse: true });
                }
            }
        });

<%      } %>

        $("li.mk[aria-controls]").on("click keypress", function(e) {
            if ($(e.target).hasClass("ui-sortable")) {
                return;
            }
            let expanded = $(this).attr("aria-expanded") === "true";
            $("#" + $(this).attr("aria-controls")).toggle(!expanded);
            $(this).attr("aria-expanded", !expanded);

            // Probeer het net geopende blok in beeld te brengen
            var top = $(this).position().top - $(this).closest("div").position().top;
            var bottom = top + $(this).height();

            var div = $(this).closest("div.ui-layout-content");
            if (bottom > div.height() + div.scrollTop())
                div.scrollTop(Math.min(top, bottom - div.height() + 5));
        }).on("click.open", function() {
            window.clearTimeout(timeoutInstance);
            $("div.ui-tabs-submenu").hide();
        });

        <% if (Session("interface") != "touch") { %>
             $("#menutabs").filterMenuByText("#menufilter");
             $("#menufilter").focus();
        <% } %>

        // Add dropdown menu for the tabs
        if ($("#menutabs").data("ui-tabs") && $("#menutabs").tabs("instance").tabs.length > 1)
        {
            var fixedHeight = $("#menutabs > .ui-tabs-nav").get(0).getBoundingClientRect().height;
            $("#menutabs > .ui-tabs-nav").before("<div class='ui-menu-tabs' style='height: "+fixedHeight+"px'><ul><li class='mk header-tabs'>"+getTabsDropdown()+"</li></ul></div>");
            $(".ui-menu-tabs").toggle();
        }

        $(".ui-tabs-panel ul li.mk, .ui-menu-tabs ul li.mk")
            .on("mouseenter", dropDown);

        $(".ui-tabs-panel ul li.mk, .ui-menu-tabs ul li.mk, .ui-tabs-submenu, .micon, .tabicon, .menuDropDown, .menuHeadSpacer")
            .on("mouseleave", function(e) {
                if (checkRelated(e)) return;
                dropDown("hide");
            });

        $(".ui-tabs-submenu, .menuDropDown, li.mi")
            .on('click.nameSpace', function() { dropDown("hide", false); });

        var menuCollapsed = localStorage.getItem("menuCollapsed");
        if (menuCollapsed)      // if menuCollapsed is set, use it
        {
            if (menuCollapsed == "1")
                toggleMenu(true);
        }
        else                    // if menuCollapsed is not set, use S("menu_start_open")
        {
            <% if (!S("menu_start_open")) { %>
                toggleMenu(true);
            <% } %>
        }

        $("#menutabs").on("tabsactivate", function(event, ui)
        {
            var selectedTabId = $("#menutabs").tabs("option", "active");
            localStorage.setItem("selectedMenuTab", selectedTabId);
        });

        $("#moretab").on("click", function(e)
            {
                FcltMgr.stopPropagation();
                if ($("#moretab").hasClass("moretab-active"))
                {
                    $("#moretab").removeClass("moretab-active");
                    not_morelist_event("off");
                }
                else
                {
                    var content = generateHiddenTabmenu();
                    $("#morelist").empty().append(content);
                    $("#moretab").addClass("moretab-active");
                    not_morelist_event("on");
                }
            });

        // Sort and save favorite side menu tabs
        $("#PersFAC .favorites").sortable({
            helper: "clone",
            items: "li.fav",
            axis: "y",
            distance: 5,
            update: function(event, ui) {
                var previousMenuKey = parseInt(ui.item.prevAll("li.fav").first()?.find("span")?.data("menu-key"), 10) || -1;
                var menuKey = parseInt(ui.item.find("span").data("menu-key"), 10) || -1;
                var nextMenuKey = parseInt(ui.item.nextAll("li.fav").first()?.find("span")?.data("menu-key"), 10) || -1;

                if(menuKey > 0 && (previousMenuKey > 0 || nextMenuKey > 0)) {  // If previous and next are both -1, no need to update
                    var data = {
                        previous_menu_key: previousMenuKey,
                        menu_key: menuKey,
                        next_menu_key: nextMenuKey,
                        mgroep: 6
                    };

                    protectRequest.dataToken(data);
                    $.post("fac_sort_menu_save.asp",
                    data,
                    FcltCallback,
                    "json");
                }
            }
        });
    }); // jQuery.ready

<%  if (__Logging & 2) { %>
    FcltMgr.windowopen("./fac_StreamFile.asp?logger=0", "logger<%=customerId%>");
    self.focus();
<% }

if (S("NotifyMessageInterval")>0)
{ %>
    function process_message(data)
    {
        if (data.noti && data.noti.length > 0)
        {
            var totalMsg = "";
            for (var i = 0; i < data.noti.length; i++)
            {
                if (totalMsg != "")
                    totalMsg += "<br>";
                totalMsg += data.noti[i].prefix;
                if (data.noti[i].url != "" && data.noti[i].refkey != -1)
                    totalMsg += "<span class='fld details' onclick='FcltMgr.openDetail(\"appl/" + safe.htmlattr(data.noti[i].url)+data.noti[i].refkey + "\")'>" + safe._htmlEncode(data.noti[i].msg) + "</span>";
                else
                    totalMsg += safe._htmlEncode(data.noti[i].msg);
            }
            FcltMgr.alert(totalMsg, { ishtmlsafe: true, closeOnClick: data.noti.length == 1 });
        }
        if (data.nextCheck > 0)
            window.setTimeout("getNotification()", data.nextCheck);
    }
    function getNotification()
    {
        if (document.visibilityState == 'hidden') // safe fallback voor browsers die visibilityState niet zetten
        {
            //console.log("skipping invisible notification");
            window.setTimeout("getNotification()", 2000); // elke 2 seconde kijken of we nog hiddenzijn
        }
        else
            $.getJSON("NotifyMessage.asp?tabid=" + tabid, process_message);
    }
    // Uitstellen opdat andere onderdelen van de voorpagina
    // een fractie sneller in beeld komen
    window.setTimeout("getNotification()", 1000);
<% } %>

function menu(evt, item, titel, menu_key)  // Eén menuitem
{
    FcltMgr.stopPropagation(evt);
    if (menu_key > 0)
    {
        if ($(evt.target).attr("infomsg"))
        {
            FcltMgr.alert($(evt.target).attr("infomsg"), {title: L("lcl_menumessage")});
        }
        item += item.indexOf("?") > -1?"&":"?";
        item += "from_menu_key=" + menu_key;
    }
    FcltMgr.openDetail(item, titel);
}

function not_morelist_event(zet)
{
    if (zet == "on")
    {
        $(document).on("click.notMoreList", function()
        {
            if ($("#morelist:hover").length == 0)
            {
                $("#moretab").click();
            }
        });
    }
    else
    {
        $(document).off("click.notMoreList");
    }
}

function generateHiddenTabmenu()
{
    var tablist_content = "";
    var $main = $("#maintabs").find("ul");
    $main.find("li").each(function()
    {
        if ($(this).attr("inmore"))
        {
            var v_id = $(this).find("a").prop("id");
            var v_title  = $(this).find("span").attr("ttl") || $(this)[0].innerText;
            var v_pin = $(this).find("span.tabpinned");
            var v_menukey = $(this).find("a span:eq(1)").attr("data-menu-key");
            v_tab = '<div class="morelistitem nowrap" onclick="set_current_tab(\'' + v_id + '\')" data-menu-key=' + v_menukey + '>'
                  +     I((v_pin.length ? "fa-thumbtack" : "fa-angle-right"), { fastyle: "far" }) + safe.html(v_title)
                  + "</div>";
            tablist_content = v_tab + tablist_content;
        }
    });
    return tablist_content;
}

function set_current_tab(selector)
{
    FcltMgr.tabbedManager.renewTab(selector);
    myResize(false);
}

</script>

</head>
<%
 if (Session("interface") == "desktop") {  %>
<body>
  <form name="u2" action="../aut/LogOff.asp" method="post" onSubmit="logOff();">
<% IFACE.FORM_END(); %>
  </form>
<% if (!noHeader) {  %>
  <div id="frheader">
    <% generateHeader(); %>
  </div>
  <div id="topdivider" class='ui-layout-resizer' onclick="$('#frheader').toggle();$(this).toggleClass('dividerclosed');window.myResize(true);toggleHead();">
    <div id="headtoggler" class='toggler' title='<%=safe.htmlattr(L("lcl_toggler"))%>'></div>
  </div>

<script>
function toggleHead(){
    if($("#topdivider").hasClass("dividerclosed")){
        $("#headtoggler").html("<%=I("fa-caret-down", {fastyle: "fas"})%>");
    } else {
        $("#headtoggler").html("");
    }
}
    jQuery.fn.filterMenuByText = function(textbox, selectSingleMatch) {
      return this.each(function() {

        var menu = this;
        var lastActive = null;
        $(textbox).on('change keyup', function() {
          if (!lastActive)
            lastActive = $("#menutabs").find("div.ui-tabs-panel:visible").attr("id");
          $(menu).find("li.mk,li.mklogo").show(); // Alle koppen zichtbaar
          $(menu).find("li.mk ul").show(); // Alle koppen open
          $(menu).find("div.filtermenukop").show(); // En vervangen door eigen filterkoppen
          $(menu).find("div.ui-tabs-panel").show(); // Alle panels tonen

          var search = $(this).val().trim().toLowerCase();
          if (!search)
          {
            $(menu).find("li.mk ul").hide(); // Alle koppen dicht
            $(menu).find("div.ui-tabs-panel").each(function () {
                if ($("li.mk ul", this).length <= <%=S("menu_collapse_threshold")%>)
                    $("li.mk ul", this).show() // Maar tabjes met weinig koppen zijn doorgaans default open
               });
            $(menu).find("li.mi").show();
            $(menu).find("div.filtermenukop").hide();
            $(menu).find("div.ui-tabs-panel").hide(); // Alle panels verbergen
            $("#" + lastActive).show() // maar de actieve weer terug
            lastActive = null;

            return;
          }

          // Nu het echte zoeken
          $(menu).find("li.mi").each(function(){
            var text = $(this).text().toLowerCase();
            var moretext = ($(this).prop('title')||"").toLowerCase();
            $(this).toggle(text.indexOf(search) > -1 || moretext.indexOf(search) > -1);
          });

          // Koppen hidden waar niets over is
          $(menu).find("li.mk,li.mklogo").each(function(){
            // mist inactieve tabs var cnt=$(this).find("li.mi:visible").length;
            var cnt = $(this).find("li.mi").filter(function() {
                  return $(this).css('display') !== 'none';
                }).length;
            $(this).toggle(cnt > 0);
          });
          return;
        });
      });
    };

</script>
<% }

if (S("PerformInterval")>0 && user.checkAutorisation("WEB_PERMON", true)) { %>
 <iframe id="bgPerformance"  src="../Fac/PerformanceTester.asp" style="display:none"><!--het frame voor performancemetingen--></iframe>
<% }
    if (!noMenu) {
    %>
    <div id="menutabs">
        <%  generateMenu(1); %>
        <div class="ui-tabs-submenu" style="display: none"><ul class="menuDropDown"></ul></div>
    </div>
      <div id="menudivider" class='ui-layout-resizer' onclick='toggleMenu()'>
        <div id="menutoggler" class='toggler' onclick='toggleMenu()' title='<%=L("lcl_toggler")%>'><%=I("fa-caret-left", {fastyle: "fas"})%></div>
      </div><%
    }
%>    <div id="maintabs">

<% if (noTabs) { /* de onload is voor FireFox */ %>
    <iframe src="../../<%=safe.htmlattr(autoopen[0].u)%>" name="firstpage"
            style='min-height: 100%;'
            width="100%" marginwidth="0" marginheight="0" frameborder="0" scrolling="auto"
            onload="$(this).height(window.innerHeight-2)"></iframe>
<% } else { %>
        <div id="moretab" class="moretab">
          <span class=""><%=L("lcl_more_tabs")%></span><%=I("fa-chevron-down", { "fastyle": "far" })%>
        </div>
        <div id="morelist" class="morelist"></div>
        <span class="tabcloseall"
              title="<%=L("lcl_close_all_tabs")%>"
              onClick="FcltMgr.closeAll()"><%=I("fa-times")%></span>
        <span class="pincurrenttab"
              title="<%=L("lcl_current_tab")%>"
              onClick="FcltMgr.saveTab()"><%=I("fa-thumbtack")%></span>
        <ul><!--hier komen de tabs--></ul>
<%          // zie: De gepinde tabs op het scherm toevoegen.
   }
%>
    </div>
</body>
<% } // if (!isTouch)
else { //if (isTouch)

%>
<body class="touch">
  <div id="touchmenu">
  <% generateMenu(2); %>
  </div>
  <% generateHeaderFunctions({touch: true}); %>
  <script>
    $("#touchmenu").tabs();
    var n = $("#touchmenu ul.ui-tabs-nav li").length;
    var w = (96/n);
    $("#touchmenu ul.ui-tabs-nav li").width(w+'%');
   </script>
</body>
<% }
%>
</html>
<% ASPPAGE_END(); %>
