var hljs;
var doclist;

if (typeof(sidebar_right_display) === undefined) {
    var sidebar_right_display = 0;
}
if (typeof(sidebar_left_display) === undefined) {
    var sidebar_left_display = 0;
}

function doclistdisplay(entry) {

    output = entry.sort((a,b) => (a['so'] - b['so']));

    entry.forEach(function(docref) {
        $( '#full-library-list' ).append('<li><h3>' + docref.grouptitle + '</h3><ul>' + doclistdocdisplay(docref.children) + '</ul></li>');
    });
}

function doclistdocdisplay(entry) {
    var listtext = '';

    output = entry.sort((a,b) => (a['so'] - b['so']));

    output.forEach(function(docref) {
        listtext = listtext + '<li><a href="' + baseloc + docref.url + '">' + docref.title + '</a></li>';
    });
    return(listtext);
}

function load_redirects() {
    var query = new URLSearchParams(window.location.search);
    if (query.has('redirected')) {
        $('div.dateinfo').after('<div class="msgs" id="redirectsmsg">This page has recently been moved to this URL; please update any bookmarks or links</div>');
        $('div#redirectsmsg').fadeIn().delay(10000).fadeOut();
    }
    if (query.has('archived')) {
        $('div.archivemsg').after('<div class="msgs" id="archivesmsg">You have been redirected to the archives as the original page and manual have been archived. You can download the corresponding manual below</div>');
        $('div#archivesmsg').fadeIn().delay(10000).fadeOut();
    }
    if (query.has('highlight')) {
        var container = document.getElementById("mainarticle");
        InstantSearch.highlight(container,decodeURIComponent(query.get('highlight')));
        $('article').before('<button class="filterbutton" id="removehighlight" onclick="removehighlight()"><b>Remove Highlighting</b></button>');
    }
}

function removehighlight()
{
    $('span.highlighter').each(function() {
        var old = this.innerHTML;
        this.replaceWith(old);
    }
                              );
    $('#removehighlight').remove();
}

function load_doclist() {
    httpRequest = new XMLHttpRequest();
    httpRequest.open("GET", baseloc + "/js/doclist.js", true);
    httpRequest.send();
    httpRequest.addEventListener("readystatechange", function() {
	if (this.readyState === this.DONE) {
            doclist = JSON.parse(this.response);
            doclistdisplay(doclist);
	}
    });
}

function idishidden(anchorid) {
    var x = document.getElementById(anchorid);
    if (window.getComputedStyle(x).display === "none") {
        return 1;
    }
    return 0;
}

function initialize_page() {
    windowloc = window.location;
    patharray = window.location.pathname.split('/');
    pathname = patharray[patharray.length-1];

    if (archivebuild && (archivebuild == 1)) {
        $('header div.bg-gray-900').css("background","bg-gray-300");
    }
    else if (windowloc.host.match(/^localhost/)) {
        $('header div.bg-gray-900').css("background","blue");
        $('span.homelogo').html("LogScale Documentation (Local via HTTP)");
    }
    else if (windowloc.host == '') {
        $('header div.bg-gray-900').css("background","blue");
        $('span.homelogo').html("LogScale Documentation (Development via file)");
    }

    const contentwords = Array.from(document.querySelector('article').children, ({textContent}) => textContent.trim()).filter(Boolean).join(' ');
    const contenttime = contentwords.trim().split(/\s+/).length/200;

    $('div.dateinfo').prepend('<div class="readingtime"><span class="updatetitle">Reading time:</span> <span class="updatetime">' + Math.round(contenttime) + ' minutes</span></div>');

    var currenttoc = $('div.nav-toc a.current').get(0);

    if (currenttoc) {
        scrolltoitem(currenttoc.id);
    }

    $('a').each(function() {
        if (htmllinkhelp[$(this).attr('href')]) {
            $(this).attr('title',htmllinkhelp[$(this).attr('href')] + " (click for more information)");
        }
    });

    $('#full-library-button').click(function() {
        $(this).toggleClass("selected");
        if (!$(this).hasClass("populated")) {
            load_doclist();
            $(this).addClass("populated");
        }

        if ( $( this ).hasClass( 'selected' ) ) {
            $( '#full-library-list' ).show();
        } else {
            $( '#full-library-list' ).hide();
        }
    });

    if (typeof sorttable !== 'undefined') {
        sorttable.init;
    }

    $('main').scroll(function(){
        var scrollTop = $(document).scrollTop();
        var anchors = $('main div[id]');
        for (var i = 0; i < anchors.length; i++){
            id = $(anchors[i]).attr('id');
            if (((scrollTop + 85) > $(anchors[i]).offset().top) && ((scrollTop+50) < ($(anchors[i]).offset().top + $(anchors[i]).height()))) {
                $('a[href="' + pathname + '#' + id + '"]').addClass('tocactive');
            } else {
                $('a[href="' + pathname + '#' + id + '"]').removeClass('tocactive');
            }
        }
    });

    $(document).keydown(function() {
        if(event.altKey && event.keyCode == 70) {
            $('#inlinesearchtext').focus();
            return false;
        }
    });

    init_page();

    build_collapsed();
    build_tabbed();
    build_hidden_beta();

    switchtocontent();

    $('article .titlepage').first().find('.title').first().addClass("pageheadertitle");

    load_redirects();
}

function switchtocontent() {
    var myanchor = self.location.href.split('#')[1];

    if (myanchor) {

        // Trim query arguments if there are any
        myanchor = myanchor.split('?')[0];
        // Determine if the selected anchor is actually part of a tab

        var anchorelem = document.querySelector('#'+myanchor);

        jsanchor = $('#' + myanchor);

        if (jsanchor.hasClass('collapsedsection')) {
            linkpara = jsanchor.find("p.collapsedsection");
            button = jsanchor.find("button.sectionhide");
            show_section(linkpara,button);
            scrolltoitem(myanchor);
        }
        else if (jsanchor.hasClass('collapsiblesection')) {
            scrolltoitem(myanchor);
        } else {

            var tabelem = anchorelem.closest(".tab");

            if (tabelem) {
                tabelemid = tabelem.getAttribute("id");
                if (idishidden(tabelemid)) {
                    urltabgroup = tabelemid.split('-')[0];
                    tabshow(tabelemid,urltabgroup);
                }
            }

            var tabanchors = document.getElementsByClassName('tab');

            if (myanchor in tabanchors) {
                urltabgroup = myanchor.split('-')[0];
                tabshow(myanchor,urltabgroup);
            } else {
                urltabgroup = '';
                const activeurl = pathname + '#' + myanchor;
                activelink = $('div.navigation-sibling-link a[href="' + activeurl + '"]');
                activelink.addClass("tocactive");
                const inpagetoc = $('.navigation-sibling-link a.tocactive').get(0);
                if (inpagetoc) {
                    scrolltoitem(inpagetoc.id);
                }
                scrolltoitem(myanchor);
            }
        }

    } else {
        urltabanchor = '';
        urltabgroup = '';
    }
}

function scrolltoitem(elementid) {
    scrollloc = document.getElementById(elementid);
    if (scrollloc) {
        setTimeout(function() {
            scrollloc.scrollIntoView({behavior: 'instant', block: 'start'});
            scrollloc.classList.add('highlightborder');
        },100);

        setTimeout(function() {
            scrollloc.classList.remove('highlightborder');
        },10000);
    }
}

function build_hidden_beta() {

    var numItems = $('.betahidden').length;

    $(".betahidden").hide();

    if (numItems > 0) {
        $('div.titlepage').after('<button id="buttonshowhide" class="showbetahidden">Show Beta Features</button>');
        $('button#buttonshowhide').click(function() {
            $("button.showbetahidden").toggleClass('betaenabled');
            $(".betahidden").toggle();
            $(".betahidden").css({"border-left":"solid purple 5px"});
        });
    }
}

function build_sortable_tables() {
    $('article').find('table').each(function(){
        var issortable = $(this).closest('.notsortable');
        if (issortable.length > 0 ) {
            $(this).addClass('notsortable');
        }
        else {
            $(this).addClass('sortable');
        }
    });
}

function hide_section(origpara,button) {
    sectiontohide = origpara.parent();
    sectiontohideid = sectiontohide.attr("id");

    sectiontohide.find("*").each(function() {
        $(this).hide();
    });

    sectiontohide.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').css('display','inline-block');
    sectiontohide.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').parent('div').css('display','inline-block');

    origpara.show();
    origpara.find("*").each(function() {
        $(this).show();
    });

    sectiontohide.find('div.titlepage').first().show();
    sectiontohide.find('div.titlepage').find("*").each(function() {
        $(this).show();
    });

    $('#' + sectiontohideid + '_showhidebutton').text(' + ');
    $('#' + sectiontohideid + '_showhidebutton').off('click').click(function(ev) { ev.stopPropagation(); show_section(origpara,button); });
    $('#' + sectiontohideid + '_showhidebutton').show();
}

function show_section(origpara,button) {
    sectiontoshow = origpara.parent();
    sectiontoshowid = sectiontoshow.attr("id");

    sectiontoshow.find("*").each(function() {
        $(this).show();
    });
    sectiontoshow.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').css('display','inline-block');
    sectiontoshow.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').parent('div').css('display','inline-block');

    origpara.show();
    origpara.find("*").each(function() {
        $(this).show();
    });

    sectiontoshow.find('div.titlepage').first().show();
    sectiontohide.find('div.titlepage').find("*").each(function() {
        $(this).show();
    });

    $('#' + sectiontoshowid + '_showhidebutton').text(' - ');
    $('#' + sectiontoshowid + '_showhidebutton').off('click').click(function(ev) { ev.stopPropagation(); hide_section(origpara,button); } );
    $('#' + sectiontoshowid + '_showhidebutton').show();
}

function build_collapsed() {
    var ulid = 1;

    $('p.collapsedsection').each(function() {
        origpara = $(this);
        sectiontohide = $(this).parent();
        sectiontohide.addClass('collapsedsection');
        sectiontohideid = sectiontohide.attr("id");
        sectiontohide.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').first().after('<button class="sectionhide" id="' + sectiontohideid + '_showhidebutton' + '" title="Show content">&nbsp;+&nbsp;</button>');
        button = $('#' + sectiontohideid + '_showhidebutton');
        hide_section(origpara,button);
    });

    $('p.collapsiblesection').each(function() {
        origpara = $(this);
        sectiontohide = $(this).parent();
        sectiontohide.addClass('collapsiblesection');
        sectiontohideid = sectiontohide.attr("id");
        sectiontohide.find('h2.title,h3.title,h4.title,h5.title,h6.title,h7.title').first().after('<button class="sectionhide" id="' + sectiontohideid + '_showhidebutton' + '" title="Hide content">&nbsp;-&nbsp;</button>');
        button = $('#' + sectiontohideid + '_showhidebutton');
        show_section(origpara,button);
    });


    $('ul.itemizedlist.collapsed').each(function() {
        var itemid = 'collapselist'+ulid;

        if (($(this).parent().prevAll('p.collapsehandle').length > 0) &&n
            ($(this).parent().prevAll('p.expandhandle').length > 0)) {

            $(this).attr('id',itemid);

            $(this).parent().prevAll('p.expandhandle').first().prepend('<div class="expandhandle-img" title="Expand detail"/>').click(function() {
                $(this).prevAll("p.collapsehandle").first().show();
                $('#'+itemid).show();
                $(this).hide();
            });

            $(this).parent().prevAll('p.collapsehandle').first().prepend('<div class="collapsehandle-img" title="Hide detail"/>').click(function() {
                $(this).nextAll("p.expandhandle").first().show();
                $('#'+itemid).hide();
                $(this).hide();
            });

            $(this).parent().prevAll("p.expandhandle").first().show();
            $(this).parent().prevAll("p.collapsehandle").first().hide();
            $(this).hide();
            ulid++;
        }
    });

    $('ul.itemizedlist.collapsible').each(function() {
        if ($(this).parent().prevAll('p.collapsehandle').length > 0) {
            $(this).parent().prevAll('p.collapsehandle').prepend('<div class="collapsehandle-img" title="Expand detail"/>');
            $(this).parent().prevAll("p.collapsehandle").click(function() {
                if ($(this).parent().find('ul').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('ul').slideToggle();
            });
        }
    });

    $('ol.orderedlist.collapsed').each(function() {
        var itemid = 'collapselist'+ulid;

        if (($(this).parent().prevAll('p.collapsehandle').length > 0) &&
            ($(this).parent().prevAll('p.expandhandle').length > 0)) {

            $(this).attr('id',itemid);

            $(this).parent().prevAll('p.expandhandle').first().prepend('<div class="expandhandle-img" title="Expand detail"/>').click(function() {
                $(this).prevAll("p.collapsehandle").first().show();
                $('#'+itemid).show();
                $(this).hide();
            });

            $(this).parent().prevAll('p.collapsehandle').first().prepend('<div class="collapsehandle-img" title="Hide detail"/>').click(function() {
                $(this).nextAll("p.expandhandle").first().show();
                $('#'+itemid).hide();
                $(this).hide();
            });

            $(this).parent().prevAll("p.expandhandle").first().show();
            $(this).parent().prevAll("p.collapsehandle").first().hide();
            $(this).hide();
            ulid++;
        }
    });

    $('ol.orderedlist.collapsible').each(function() {
        if ($(this).parent().prevAll('p.collapsehandle').length > 0) {
            $(this).parent().prevAll('p.collapsehandle').prepend('<div class="collapsehandle-img" title="Expand detail"/>');
            $(this).parent().prevAll("p.collapsehandle").click(function() {
                if ($(this).parent().find('ul').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('ul').slideToggle();
            });
        }
    });

    $('div.proglist.collapsed').each(function() {
        var itemid = 'collapseproglist'+ulid;

        $(this).attr('id',itemid);

        $(this).prevAll('p.expandhandle').first().prepend('<div class="expandhandle-img" title="Expand detail"/>').click(function() {
            $(this).prevAll("p.collapsehandle").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsehandle').first().prepend('<div class="collapsehandle-img" title="Hide detail"/>').click(function() {
            $(this).nextAll("p.expandhandle").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandhandle").first().show();
        $(this).prevAll("p.collapsehandle").first().hide();
        $(this).hide();
        ulid++;

        $(this).prevAll('p.expandbutton').first().click(function() {
            $(this).prevAll("p.collapsebutton").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsebutton').first().click(function() {
            $(this).nextAll("p.expandbutton").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandbutton").first().show();
        $(this).prevAll("p.collapsebutton").first().hide();
        $(this).hide();
        ulid++;
    });

    $('div.proglist.collapsed').each(function() {
        if ($(this).parent().prevAll('p.collapsehandle').length > 0) {
            $(this).parent().prevAll('p.collapsehandle').prepend('<div class="collapsehandle-img" title="Expand detail"/>');
            $(this).parent().prevAll("p.collapsehandle").click(function() {
                if ($(this).parent().find('div.proglist').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.proglist').slideToggle();
            });
        }
        if ($(this).parent().prevAll('p.collapsebutton').length > 0) {
            $(this).parent().prevAll("p.collapsebutton").click(function() {
                if ($(this).parent().find('div.proglist').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.proglist').slideToggle();
            });
        }
    });

    $('div.collapsed').each(function() {
        var itemid = 'collapsediv'+ulid;

        $(this).attr('id',itemid);

        $(this).prevAll('p.expandhandle').first().prepend('<div class="expandhandle-img" title="Expand detail"/>').click(function() {
            $(this).prevAll("p.collapsehandle").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsehandle').first().prepend('<div class="collapsehandle-img" title="Hide detail"/>').click(function() {
            $(this).nextAll("p.expandhandle").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandhandle").first().show();
        $(this).prevAll("p.collapsehandle").first().hide();
        $(this).hide();
        ulid++;

        $(this).prevAll('p.expandbutton').first().click(function() {
            $(this).prevAll("p.collapsebutton").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsebutton').first().click(function() {
            $(this).nextAll("p.expandbutton").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandbutton").first().show();
        $(this).prevAll("p.collapsebutton").first().hide();
        $(this).hide();
        ulid++;
    });

    $('div.collapsed').each(function() {
        if ($(this).parent().prevAll('p.collapsehandle').length > 0) {
            $(this).parent().prevAll('p.collapsehandle').prepend('<div class="collapsehandle-img" title="Expand detail"/>');
            $(this).parent().prevAll("p.collapsehandle").click(function() {
                if ($(this).parent().find('div.proglist').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.proglist').slideToggle();
            });
        }
        if ($(this).parent().prevAll('p.collapsebutton').length > 0) {
            $(this).parent().prevAll("p.collapsebutton").click(function() {
                if ($(this).parent().find('div.proglist').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.proglist').slideToggle();
            });
        }
    });

    $('div.collapsible').each(function() {
        var itemid = 'collapsiblediv'+ulid;

        $(this).attr('id',itemid);

        $(this).prevAll('p.expandhandle').first().prepend('<div class="expandhandle-img" title="Expand detail"/>').click(function() {
            $(this).prevAll("p.collapsehandle").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsehandle').first().prepend('<div class="collapsehandle-img" title="Hide detail"/>').click(function() {
            $(this).nextAll("p.expandhandle").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandhandle").first().hide();
        $(this).prevAll("p.collapsehandle").first().show();
        $(this).show();
        ulid++;

        $(this).prevAll('p.expandbutton').first().click(function() {
            $(this).prevAll("p.collapsebutton").first().show();
            $('#'+itemid).show();
            $(this).hide();
        });

        $(this).prevAll('p.collapsebutton').first().click(function() {
            $(this).nextAll("p.expandbutton").first().show();
            $('#'+itemid).hide();
            $(this).hide();
        });

        $(this).prevAll("p.expandbutton").first().show();
        $(this).prevAll("p.collapsebutton").first().hide();
        $(this).show();
        ulid++;
    });

    $('div.collapsible').each(function() {
        if ($(this).parent().prevAll('p.collapsehandle').length > 0) {
            $(this).parent().prevAll('p.collapsehandle').prepend('<div class="collapsehandle-img" title="Expand detail"/>');
            $(this).parent().prevAll("p.collapsehandle").click(function() {
                if ($(this).parent().find('div.collapsible').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.collapsible').slideToggle();
            });
        }
        if ($(this).parent().prevAll('p.collapsebutton').length > 0) {
            $(this).parent().prevAll("p.collapsebutton").click(function() {
                if ($(this).parent().find('div.collapsible').is(":visible")) {
                    $(this).find('div.collapsehandle-img').removeClass('collapsehandle-img').addClass('expandhandle-img').attr('title','Expand detail');
                } else {
                    $(this).find('div.expandhandle-img').addClass('collapsehandle-img').removeClass('expandhandle-img').attr('title','Hide detail');
                }
                $(this).parent().find('div.collapsible').slideToggle();
            });
        }
    });

}

function build_tabbed() {
    var tabbed_groups = document.getElementsByClassName("tabbed-bar");

    var tabids = [];

    for(k = 0; k< tabbed_groups.length; k++) {
        tabgroup = tabbed_groups[k];
        tabids.push(tabgroup.id);
    }

    tabbuttons = [];

    for(k = 0; k< tabids.length; k++) {
        tabgroup = document.getElementById(tabids[k]);

        const prefixmatch = new RegExp('^' + tabgroup.id + '-');

        buttons = '<div class="tabcol"><span class="prefix">Show:</span></div><div class="tabcol">';
        first = 0;
        tabs = document.getElementsByClassName("tab");

        for(j = 0; j< tabs.length; j++) {
            tab = tabs[j];
            titletexts = tab.getElementsByTagName("b");
            titletext = "Button";
            if (titletexts.length) {
                titletext = titletexts[0].innerHTML;
            }

            tabtitles = tab.getElementsByClassName("tabtitle");

            if (tabtitles.length > 0) {
                titletext = tab.getElementsByClassName("tabtitle")[0].innerHTML;
                tab.getElementsByClassName("tabtitle")[0].style.display = 'none';
            }

            if (tab.id) {
                matches = prefixmatch.exec(tab.id);
                if (matches) {
                    tab.classList.add("tab_" + tabgroup.id);
                    button = '';

                    if (!first) {
                        button = '<button id="button_' + tab.id + '" class="tabbed-bar-button active" onclick="tabshow(\'' + tab.id + '\',\'' + tabgroup.id + '\');">' + titletext + '</button>';
                        first = 1;
                    } else {
                        button = '<button id="button_' + tab.id + '" class="tabbed-bar-button" onclick="tabshow(\'' + tab.id + '\',\'' + tabgroup.id + '\');">' + titletext + '</button>';
                        document.getElementById(tab.id).style.display = 'none';
                    }
                    buttons = buttons + button;
                }
                var link = '#' + tab.id;
                $('a[href$="'+link+'"]').each(function() {
                    $(this).attr('onclick','tabshow(\''+tab.id+'\',\''+tabgroup.id+'\')');
                });
            }
        }

        tabgroup.innerHTML = buttons + "</div>";
    }
}

function tabshow(showtab,tabgroup) {

    var tabs = document.getElementsByClassName('tab_' + tabgroup);
    for(i=0;i<tabs.length;i++) {
        tab = tabs[i];
        document.getElementById("button_" + tab.id).classList.remove("active");
        tab.style.display = 'none';
    }
    document.getElementById(showtab).style.display = "block";
    document.getElementById("button_" + showtab).classList.add("active");
    self.location.href = '#' + showtab;

    setTimeout(function() {
        document.getElementById(tabgroup).scrollIntoViewIfNeeded({behavior: 'instant',block: 'start'});
    },100);
}

function sidebar_toggle(elobj,parentid,direction) {
    elobj.classList.toggle("narrow");
    if (elobj.classList.contains("narrow")) {
	if (direction) {
	    elobj.innerHTML = "&raquo;";
            elobj.title = "Show manual table of contents";
	} else {
	    elobj.innerHTML = "&laquo;";
            elobj.title = "Hide manual table of contents";
	}
    } else {
	if (direction) {
	    elobj.innerHTML = "&laquo;";
            elobj.title = "Show page contents and related links";
	} else {
	    elobj.innerHTML = "&raquo;";
            elobj.title = "Hide page contents and related links";
	}
    }

    if (parentid == 'sidebarb') {
        document.getElementById("sidebar-version").classList.toggle("hidden");
        document.getElementById(parentid).classList.toggle("grid-area-" + parentid);
        document.getElementById(parentid).classList.toggle("grid-area-" + parentid + "-narrow");
        document.getElementById("grid-area-main").classList.toggle("grid-area-extend-right");
        $('#rsidebar-nav').toggle();
    }
    else {
        document.getElementById(parentid).classList.toggle("grid-area-" + parentid);
        document.getElementById(parentid).classList.toggle("grid-area-" + parentid + "-narrow");
        $('#lsidebar-nav').toggle();
        document.getElementById("grid-area-main").classList.toggle("grid-area-extend-left");
    }
}

function add_copylink_events(elemlist,basetag) {

    for(i = 0; i <elemlist.length; i++) {
        header = elemlist[i];

        var url = new URL(document.location);
        var path = new String(url.pathname);
        var paths = path.split('/');

        pagename = new String(paths[paths.length - 1]);
        pagebase = pagename.split('.')[0];

        header.addEventListener("mouseover", function clickable() {

            if (this.closest(basetag)) {
                var linkid = this.closest(basetag).id;
                var title = this.querySelector(".title");

                if (linkid != pagebase) {
                    if (title) {
                        title.classList.add("linkable");
                        this.classList.add("copylink");
                    } else {
                        header.classList.add("copylink");
                        this.classList.add("linkable");
                        this.classList.add("copylink");
                    }
                } else {
                    this.removeEventListener("mouseover",clickable);
                }
            }
        });

        header.addEventListener("click", function() {
            if (this.classList.contains("copylink")) {
                if (this.closest(basetag).id) {
                    var parentid = this.closest(basetag).id;
                    var url = new URL(document.location);
                    var link = new String (url);
                    link = link.split('#')[0];
                    link = link + '#' + parentid;
                    navigator.clipboard.writeText(link);
                    this.insertAdjacentHTML("afterbegin",'<div id="copytooltipparent" class="intextcopytooltip"><span id="copytooltip" class="intextcopytooltiptext"></span></div>');
                    tooltiptext = document.getElementById('copytooltip');
                    tooltiptext.style.visibility = 'visible';
                    tooltiptext.style.opacity = 1;
                    tooltiptext.innerHTML="Copied link to clipboard";
                    setTimeout(function() {
                        var copies = document.getElementsByClassName("intextcopytooltip");
                        for(i = 0; i <copies.length; i++) {
                            copies[i].remove();
                        }
                    },1000);
                }
            }
        });
    }
}

function init_page() {
    var basearticle = document.getElementsByTagName("article");
    var headers = document.getElementsByClassName("titlepage");
    var tablerows = document.getElementsByTagName("td");
    var tablecells = document.getElementsByTagName("td");

    add_copylink_events(headers,'div [id]');
    add_copylink_events(tablerows,'tr [id]');
    add_copylink_events(tablecells,'td [id]');

    if (sidebar_right_display == 0) {
        sidebar_toggle(document.getElementById("rsidebar-openclose"),'sidebarb',0);
    }

    if (sidebar_right_display == -1) {
        if (sidebar_right_default == 0) {
            sidebar_toggle(document.getElementById("rsidebar-openclose"),'sidebarb',0);
        }
    }

    if (sidebar_left_display == 0) {
        sidebar_toggle(document.getElementById("lsidebar-openclose"),'sidebar',1);
    }

    if (sidebar_left_display == -1) {
        if (sidebar_left_default == 0) {
            sidebar_toggle(document.getElementById("lsidebar-openclose"),'sidebar',1);
        }
    }

    if (hljs) {
        hljs.highlightAll();
    }
}

var InstantSearch = {

    "highlight": function (container, highlightText)
    {
        var internalHighlighter = function (options)
        {

            var id = {
                container: "container",
                tokens: "tokens",
                all: "all",
                token: "token",
                className: "className",
                sensitiveSearch: "sensitiveSearch"
            },
                tokens = options[id.tokens],
                allClassName = options[id.all][id.className],
                allSensitiveSearch = options[id.all][id.sensitiveSearch];
            
            function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll) {
                var nodeVal = node.nodeValue, parentNode = node.parentNode,
                    i, j, curToken, myToken, myClassName, mySensitiveSearch,
                    finalClassName, finalSensitiveSearch,
                    foundIndex, begin, matched, end,
                    textNode, span, isFirst;

                for (i = 0, j = tokenArr.length; i < j; i++) {
                    curToken = tokenArr[i];
                    myToken = curToken[id.token];
                    myClassName = curToken[id.className];
                    mySensitiveSearch = curToken[id.sensitiveSearch];

                    finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);

                    finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);

                    isFirst = true;
                    while (true) {
                        if (finalSensitiveSearch)
                            foundIndex = nodeVal.indexOf(myToken);
                        else
                            foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());

                        if (foundIndex < 0) {
                            if (isFirst)
                                break;

                            if (nodeVal) {
                                textNode = document.createTextNode(nodeVal);
                                parentNode.insertBefore(textNode, node);
                            }

                            parentNode.removeChild(node);
                            break;
                        } 

                        isFirst = false;

                        begin = nodeVal.substring(0, foundIndex);
                        matched = nodeVal.substring(foundIndex, foundIndex + myToken.length);

                        if (begin) {
                            textNode = document.createTextNode(begin);
                            parentNode.insertBefore(textNode, node);
                        } 

                        span = document.createElement("span");
                        span.className += finalClassName;
                        span.appendChild(document.createTextNode(matched));
                        parentNode.insertBefore(span, node);

                        nodeVal = nodeVal.substring(foundIndex + myToken.length);
                    } 
                } 
            }; 

            function iterator(p) {
                if (p === null) return;

                var children = Array.prototype.slice.call(p.childNodes), i, cur;

                if (children.length) {
                    for (i = 0; i < children.length; i++) {
                        cur = children[i];
                        if (cur.nodeType === 3) {
                            checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
                        } else if (cur.nodeType === 1) {
                            iterator(cur);
                        }
                    }
                }
            }; 

            iterator(options[id.container]);
        };

        internalHighlighter(
            {
                container: container,
                all: {
                    className: "highlighter"
                },
                tokens: [
                    {
                        token: highlightText,
                        className: "texthighlight",
                        sensitiveSearch: false
                    }
                ]
            }
        ); 

    } 
};

function select_version(option) {
    window.location.assign(option.value);
}
