$(document).ready(function() {
    $('a[rel=alternative]').live('click', function(e) {
        $('#' + e.target.href.split('#')[1]).toggle('fast'); 
        e.preventDefault();
    });  

    $('body#help #areaContent a[rel!=], body#news_show #areaContent a[rel!=]').live('click', function(e) {
        var a = $(e.target).closest('a');

        if (a.closest('div').attr('id') === 'areaLeft' || a.hasClass('back')) {
            return;
        }

        var href = a.attr('href');
        $.address.value(href);

        var lis = $('#subAreaNavigation li');

        var directions = function() {
            if (lis.index(lis.find('a[href=' + href + ']').closest('li')) < lis.index(lis.filter('.active'))) {
                return { hide: 'right', show: 'left' };
            } else {
                return { hide: 'left', show: 'right' };
            }
        }();

        $('#chapterContent').attr('id', 'oldChapterContent');
        $('#oldChapterContent').hide('slide', { direction: directions.hide }, 500, function() {
            $(this).remove();
        });

        $.getJSON(href, function(data) {
            document.title = data.title + ' : 5Street';

            var newBody = $(data.html.body);

            $('#subPageNavigation').after(newBody.filter('#chapterContent'));
            $('#chapterContent').show('slide', { direction: directions.show }, 500);

            $('#subAreaNavigation li.active').removeClass('active');
            $('#subAreaNavigation li a[href= ' + this.url + ']').closest('li').addClass('active');

            var newSubPageNavigationLinks = newBody.filter('#subPageNavigation').find('a, span');

            $('#subPageNavigation #prev_chapter').replaceWith(newSubPageNavigationLinks.filter('#prev_chapter'));
            $('#subPageNavigation #next_chapter').replaceWith(newSubPageNavigationLinks.filter('#next_chapter'));

            FiveStreet.prepareContentVideos();
        });
        e.preventDefault();
    });
});
