(function(){
    // TODO: Create js hierarchy and nested html lists
    // Include page ? - https://www.xwiki.org/xwiki/bin/view/FAQ/IncludeInVelocity
    // WebHome?
    document.addEventListener('DOMContentLoaded', createTableOfContent, false);

    function createTableOfContent(){
        var contentContainer = document.querySelector("#xwikicontent");
        var pxContentContainer = document.querySelector("#px-content-main");
        var sidebarElement = document.querySelector("#px-sidebar");

        if(!sidebarElement){
            return false;
        }

        (function createTableOfContentLevel(){
            var listElement = document.createElement("ul");
            listElement.className = "px-sidebar-list";

            var headingsInContent = false,
                i = 0;

            for(i; i < contentContainer.childNodes.length; i++){
                var element = contentContainer.childNodes[i];
                var headerRegex = /^H[1-6]$/;
                

                if(headerRegex.test(element.nodeName)){
                    headingsInContent = true;

                    var listItemElement = document.createElement("li");
                    var linkElement = document.createElement("a");

                    var headingContent = element.textContent;
                    var headingContentWithoutSpaces =  headingContent.replace(/\s/g, '')
                    var headingNumber = parseInt(element.nodeName.split("")[1]);
                    
                    linkElement.textContent = headingContent;
                    linkElement.href = "#H" + headingContentWithoutSpaces;
                    listItemElement.className = "px-sidebar-list-h" + headingNumber;

                    listItemElement.appendChild(linkElement);
                    listElement.appendChild(listItemElement);

                    previousElement = element;
                }
            }

            if(!headingsInContent){
                sidebarElement.parentNode.removeChild(sidebarElement);
                pxContentContainer.className = "px-content-main col-md-12";
            }

            sidebarElement.appendChild(listElement);
        })();
    }
})();