$(document).ready(function() {

    if ($('#localnav[data-scroll=true]').length) {
        if ($('#localnav .here').length) {
            var here = $('#localnav .here')[0],
                $here = $(here);
            if (here.tagName == 'A') {
                var $index = createIndex();
                if ($index) {
                    $(here.parentNode).after($index.attr('class', 'current'));
                }
            } else if (here.tagName == 'LI') {
                var $index = createIndex();
                if ($index) {
                    $here.append($index);
                }
            } else {
                return;
            }
        };
    };
    $('a[rel="section"]').click(function() {
        var target = $(this).attr('href').split('#');
        $.scrollTo('#' + target[1], {duration:500});
        return false;
    })
});

function createIndex() {
    if ($('article.contents h1[id],article.contents h2[id]').length) {
        var $ul = $('<ul>').attr('id', 'scrollto');
        $('article.contents h1[id],article.contents h2[id]').each(function(index) {
            var $this = $(this), child = this.firstChild, text;

            if ($('img', this).length) {
                text = $('img', this).attr('alt');
                if (text == '') {
                    text = $this.text();
                }
            } else {
                text = $this.text();
            };

            $ul.append($('<li>').append($('<a>').attr('href', '#' + this.id).attr('rel', 'section').text(text)));
        });
        if ($('li', $ul).length) {
            return $ul;
        };
    };
    return false;
}
