$(document).ready(function() {
    var $nav = $('#subnav li a.selected').parent('li').addClass('sub');
    $nav.append('<ul></ul>');
    
    var oheight = 0;
    $('.bio h2').each(function() {
        var $parent = $(this).parents('.bio');
        var name = $(this).html().replace(',', '');
        var id = $parent.addClass('js').attr('id');
        
        $nav.find('ul').append('<li><a href="#' + id + '">' + name + '</a></li>');
    });
    
    $('#content .copy:first').append('<div class="paging"><ul><li><a class="prev" href="#prev">&laquo; Previous Bio</a></li><li><a class="next" href="#next">Next Bio &raquo;</a></li></ul></div>');
    
    $('#content a.prev').click(function(event) {
        event.stop();
        var id = $('.visible').prev('div').attr('id');
        $('a[href$=#' + id + ']').click();
    });
    $('#content a.next').click(function(event) {
        event.stop();
        var id = $('.visible').next('div').attr('id');
        $('a[href$=#' + id + ']').click();
    });
    
    $('.bio').hide();
    
    function showHideNav() {
        if(!$('.visible').next('.bio').length) {
            $('.next').hide();
        } else {
            $('.next').show();
        }
        if(!$('.visible').prev('.bio').length) {
            $('.prev').hide();
        } else {
            $('.prev').show();
        }
    }
        
    $nav.find('ul a').unbind('click').bind('click', function(event) {
        event.stop();
                
        $nav.find('ul a').removeClass('selected');
        $(event.currentTarget).addClass('selected');
        var id = '#' + $(event.currentTarget).attr('href').split('#')[1];
        
        if($('.visible').length) {
            $('.visible').fadeOut(200, function() {
                $('.visible').removeClass('visible');
                $(id).addClass('visible').fadeIn(500, function() {
                    showHideNav();
                    window.location.hash = id;
                });
            });
        } else {
            $(id).addClass('visible').fadeIn(500, function() {
                showHideNav();
                $(this).show();
                window.location.hash = id;
            });
        }
    });
    
    if(window.location.hash.length) {
        $('a[href$=' + window.location.hash + ']').click();
    } else {
        $('#subnav li ul a:first').click();
    }
});
