(function ($) {


    /**
     * Find all the h2, h3 and h4 elements in the content area and make a TOC.
     *
     * @param {jQuery} $parent
     * @returns {jQuery}
     */
    function createTOC($parent) {
        // We need to have a parent that has one ul to be consistent
        var $top = $('<div><ul class="aui-nav"></ul></div>');
        var stack = [{$el: $top, depth: 1}];
        function getUl($parent) {
            var $ul = $parent.children('ul');
            return $ul.length > 0 ? $ul : $('<ul class="aui-nav nested" />').appendTo($parent);
        }

        // Fortunately find will return elements in order
        $parent.find('h2, h3, h4').map(function (i, h) {
            var $h = $(h);

            var name = $h.find('a').first().attr('name');
            // If we haven't found an <a name=""> in the heading, use the heading's ID attribute
            if (!name) {
                name = $h.attr('id');
            }
            var $li = $('<li />').append($('<a />').attr('href', "#" + name).text($h.text()));

            var depth = parseInt(h.nodeName.substring(1), 10);
            var parent = stack[stack.length - 1];
            while (depth <= parent.depth) {
                stack.splice(-1);
                parent = stack[stack.length - 1];
            }
            if (depth >= parent.depth) {
                stack.push({$el: $li, depth: depth});
            }
            getUl(parent.$el).append($li);
        });
        return getUl($top);
    }

    $(document).ready(function(){

        var $content = $('#main-content');
        var $sidebar = $("#sidebar");
        var $attachable = $sidebar.length ? $sidebar : $content;

        // Hide TOC on index page
        if ($('.notoc').length === 0) {
            var $toc = createTOC($content);
            var $nav;
            if ($toc.children().length > 0) {
                $nav = $('<div class="aui-navgroup aui-navgroup-vertical contents"><div class="aui-navgroup-inner"><div class="aui-nav-heading"><h3>Contents</h3></div></div></div>');
                $nav.find(".aui-navgroup-inner").append($toc);
                $attachable.prepend($nav);
            }
        }

    });

}(jQuery));