$(function(){
    //all links ( current and future ) should retrieve new pages using ajax. If JS is not available, gracefully show the page
    $("a:not([rel^='lightbox']|[rel^='direct'])").live( 'click', function(){
        var defaultContainer = '#contentWrapper';

        var new_page = $(this).attr('href');

        //if( Site.page != new_page ){
            $('#loader').fadeIn();
            var container = $(this).attr('rel') || defaultContainer;
            $(container).fadeOut('fast', function(){
                $(container).load(new_page, '',function(){
                    $('#loader').fadeOut();
                    $(this).fadeIn('fast');
                    //hard-coded workaround - clean it up! TODO
                    toggleScrolls( '#phoneContent', '.scrollUp', '.scrollDown' );

                    Site.page = new_page;
                    //if this is a link from the main menu - show it as hash
                    if( container == defaultContainer )
                        window.location.hash = new_page;
                });
            });
        //}
        return false;
    });

    //mainMenu classes
    $('#mainMenu a').click( function(){
        $('#mainMenu li').removeClass('current');
        $(this).parent().addClass('current');
    });

    $('#logo a').click( function(){
        $('#mainMenu li').removeClass('current');
    });

    //scrolls
    $('.scrollUp').live( "click", function(){
        var el = $($(this).attr('rel'));
        var to = Math.max( el.scrollTop() - el.innerHeight(), 0 );
        el.stop().scrollTo( to, 1000, { easing: 'swing' } );
    });

    $('.scrollDown').live( "click", function(){
        var el = $($(this).attr('rel'));
        var to = Math.min( el.scrollTop() + el.innerHeight(), el.attr('scrollHeight') );
        el.stop().scrollTo( to, 1000, { easing: 'swing' } );
    });

    //see if the user is coming from a hash
    var landing_page = Site.page || window.location.hash.replace( '#', '');
    if( landing_page ){
        $('a[href='+landing_page+']').click();
    }
});
