var scrollTimerId;

var BUENO = (function(window, document, $, undefined) {
    //-- private variables
    var activeOpacity = 0.35,
        inactiveOpacity = 1.00,
        subNav = {
            initHeight: 95,
            finalHeight: 195
        },

        navigation = {},
        background = {},
        contentSelector = '#content',

        bodySelector = '#home',
        $body = null,
        navigationSelector = '#navigation',
        $navigation = null,
        $subNav = null,
        mainSelector = '#main',
        $main = null,
        logoSelector = '#logo',
        $logo = null;

    //-- Sub classes
    background = (function() {
        return {
            slideDown: function (callback) {

                $body.stop().animate({backgroundPosition:"(50% -90px)"}, 500);
                //-- We don't display a SubNav when in the initial state
                navigation.subNav.clear();

                $main.stop().animate( { top: 0 }, 500, callback);
            },
            slideUp: function (callback) {

                $body.stop().animate({backgroundPosition:"(50% -345px)"}, 500);
                // Grow the subnav
                $subNav.stop().animate({height: subNav.finalHeight});

                // Slide the main content upward
                $main.stop().animate( { top: -250 }, 500, callback );
            }
        };
    })();

    navigation = (function() {
        return {
            subNav: {
                clear: function() {
                    $subNav
                        .find('div')
                            .html('')
                        .end()
                        .stop().animate({'height': subNav.initHeight});
                },
                hide: function(callback) {
                    var $currentPage = $subNav.find('.current-page'),
                        $subPages = $subNav.find('.other-pages');

                    $currentPage.stop().fadeOut('slow', callback);
                    $subPages.stop().fadeOut('fast', function () {
                        $subPages.html('');
                    });
                },
                show: function() {
                    var title = (''+ $('#content .content-section').attr('id')).toLowerCase(),
                        $newSubNav = $('#content .subnav'),
                        $currentPage = $subNav.find('.current-page'),
                        $otherPages = $subNav.find('.other-pages');

                    if ( title.indexOf(' ') !== -1 ) {
                        alert('error: ""'+ title +'" should not have a space in it!"');
                    }

                    function showOtherPages() {
                        var html = $newSubNav.html();

                        if ( html ) {
                            $otherPages
                                .html("<ul>"+ html +"</ul>")
                                .fadeIn('slow');
                        }
                    }

                    showOtherPages();
                }
            },
            activate: function() {
                //-- First Level links
                $navigation.find('.nav a').live('click', function() {
                    var $clickedLink = jQuery(this),
                        $clickedLi = $clickedLink.parents('li');

                    $('.content-section').hide();
                    slideBackgroundAndContent(this.href);
                    $clickedLi.siblings('li[class!=nav-date]').stop().fadeTo("slow", inactiveOpacity);
                    $clickedLi.stop().fadeTo("slow", activeOpacity);

                    // Force the browser to stay at the top of the content
                    // after the animation
                    $(window).scroll(function(){ return false; });
                    return false;
                });

                //-- Subnavigation Links
                //-- Make the links do something!
                $subNav
                    .find('a')
                    .die('click')
                    .live('click', function() {
                        var $subNavClickedLink = $(this),
                            $subNavClickedLi = $subNavClickedLink.parents('li');

                        //-- Bring in the content, but don't fade out the subnav
                        slideBackgroundAndContent(this.href, false);

                        //-- Make the current link faded, and show the others
                        $subNavClickedLi.siblings('li').fadeTo("slow", inactiveOpacity);
                        $subNavClickedLi.fadeTo("slow", activeOpacity);

                        $(".content").css("top", 0);
                        return false;
                    });

            }
        };
    })();//-- Private functions

    function trackPageClick(page) {
        try {
            pageTracker._trackPageview(page);
        } catch(e) {
            //nothing here
        }
    }

    function activateLogo() {
        $(logoSelector).bind('click', function() {
            $(contentSelector).hide();
            $navigation.find('li').stop().fadeTo("slow", inactiveOpacity);

            background.slideDown();
        });
    }

    function hideContent(target, callback) {
        var $content = $('#content');
        $content
            .stop()
            .fadeOut('normal', function(){
                $content
                    .load(target, '', function() {
                        navigation.subNav.show();
                        $content.stop().fadeIn("slow", function() {
                          scroll_apply();
                        });

                    });

            });
            $(".content").css("top", 0);
            trackPageClick(target);
    }

    function loadContent(target, hideSubNavFirst, callback) {
        if ( "function" !== typeof(hideSubNavFirst) && hideSubNavFirst !== false ) {
            navigation.subNav.hide(function(){
                hideContent(target, callback);
            });
        } else {
            hideContent(target, callback);
        }
    }

    function slideBackgroundAndContent(target, hideSubNavFirst) {
        background.slideUp(function() {
            loadContent(target, hideSubNavFirst);
        });
    }


    function activateTabs(selectorRoot) {
        var $tabs = jQuery(selectorRoot||'' + ".tabs a");

        $tabs.live('click', function() {
            var $clickedTab = jQuery(this),
                $clickedLi = $clickedTab.parents('li'),
                $tabContainer = $clickedTab.parents('.tabs').parent(),
                className = $clickedTab.parent().attr('class');

            //-- Only do the animation if we clicked on a new tab
            if ( $tabContainer.children('.tab.' + className + ':not(:hidden)').size() === 0 ) {
                //-- Change the tab colors
                $clickedLi
                    .fadeTo('fast', activeOpacity)
                    .addClass('selected');
                $clickedLi.siblings()
                    .removeClass('selected')
                    .fadeTo('fast', inactiveOpacity);

                //-- Transition the tab content
                $tabContainer.children('.tab:visible').fadeOut('fast', function() {
                    $tabContainer
                        .find('.tab.' + className)
                        .removeClass('hidden')
                        .fadeIn('fast')
                        .find('.scrollcontainer .content')
                        .css("top", 0);
                });
            }
            return false;
        });
    }

    function activateThumnails() {
        $('.thumbnail').live('mouseenter mouseleave', function(event) {
            var $thumbContainer = jQuery(this);
            if (event.type == 'mouseenter' || event.type == 'mouseover') {
                $thumbContainer.find('img').css('opacity', 0.8);
                $thumbContainer.find('a').css('visibility', 'visible');
            } else {
                $thumbContainer.find('img').css('opacity', 1);
                $thumbContainer.find('a').css('visibility', 'hidden');
            }
        });
    }

    function activateNewsLinks() {
        $('#news a.news_link').live('click', function(e) {
            var $newsContent = $("#news .scrollcontainer .content");
            $newsContent
                .css("top", 0)
                .stop()
                .fadeOut('fast', function () {
                    $newsContent.load(e.target.href, function() {
                        scroll_apply();
                        $newsContent.stop().fadeIn("slow");
                        trackPageClick(e.target.href);
                    });
                });
            return false;
        });
    }

    function activatePageLinks() {
        $(".pagelink").live('click', function(){
            var $clickedLink = $(this),
                $clickedLi = $clickedLink.parents('li');

            $('#homecontent').hide();
            $('.content-section').hide();

            slideBackgroundAndContent(this.href);
            $clickedLi.siblings('li[class!=nav-date]').stop().fadeTo("slow", 1.00);
            $clickedLi.stop().fadeTo("slow", 0.35);

            // Force the browser to stay at the top of the content
            // after the animation
            $(window).scroll(function(){ return false; });
            return false;
        });
    }


    //-- Public Functions
    return {
        init: function() {
            $body = $(bodySelector);
            $main = $(mainSelector);
            $navigation = $(navigationSelector);
            $subNav = $navigation.find('.sub-nav');
            $logo = $(logoSelector);

            navigation.activate();
            activateLogo();
            activateTabs();
            activateThumnails();
            activateNewsLinks();
            activatePageLinks();

            //-- Setup scroll links
            $("a.dn")
                .click( function() { return false; } )
                .live("mouseover", function(e){ scroll_dn(); return false; })
                .live("mouseout", function(e){ clearTimeout( scrollTimerId ); return false; });
            $("a.up")
                .click( function() { return false; } )
                .live("mouseover", function(e){ scroll_up(); return false; })
                .live("mouseout", function(e){ clearTimeout( scrollTimerId ); return false; });
        }
    };
})(this, this.document, jQuery);

jQuery(document).ready(function() {
    BUENO.init();
});

    //---------------------------
    //-- Start Scroll Functions -
    //---------------------------
    var scrollSpd = 10; // Smaller = Faster
    var scrollJmp = 2;  // Bigger = Bigger jump
    var scrollbarHeight = 120; // Set default
    var scrollAltFunction = false;

    function scroll_dn() {
        var $scrollContainer = $('#content .scrollcontainer:visible'),
            $contentClass = $scrollContainer.find('.content:visible'),
            h=$contentClass.height(),
            topVal = parseInt($contentClass.css("top"), 10) * 1-scrollJmp;

        if ( h === 0 ) {
            h=$('#content .subpagediv:visible').height();
        }

        if ( (h + topVal + scrollbarHeight) > $scrollContainer.height()) {
            $("#content .content").css("top", topVal);
            scrollTimerId=setTimeout(function() { scroll_dn(); }, scrollSpd);
        }

        return false;
    }
    function scroll_up() {
        var $scrollContainer = $('#content .scrollcontainer:visible'),
            $contentClass = $scrollContainer.find('.content:visible'),
            topVal = parseInt($contentClass.css("top"), 10) * 1+scrollJmp;
        if ( topVal <= 0 ) {
            $("#content .content").css("top", topVal);
            scrollTimerId=setTimeout(function() { scroll_up(); }, scrollSpd);
        }
        return false;
    }
    function scroll_apply() {
        //-- Add Scroll Box buttons and apply their functions
        var $content = $('#content'),
            $scrollcontainer = $content.find('.scrollcontainer'),
            $contentClass = $content.find('.content'),
            $contentSection = $content.find('.content-section'),
            $scrollButtons;
        if ( $scrollcontainer.attr('class') ) {
            var h=$contentClass.height();
            if ( h === 0 ) {
              h=$contentSection.height();
            }
            var topVal = parseInt($contentClass.css("top"),10) * 1-scrollJmp;

            if ( h+topVal+scrollbarHeight > parseInt($scrollcontainer.css('height'),10)) {
                $scrollButtons = $('.scrollbuttons');

                if ( $scrollButtons.length === 0 ) {
                    $scrollcontainer.prepend(
                        '<div class="scrollbuttons" style="display: none;">' +
                        '<a href="#" class="dn"></a>' +
                        '<a href="#" class="up"></a>' +
                        '</div>'
                    );
                    $scrollcontainer.find('.scrollbuttons').stop().fadeIn('slow');
                }
            } else {
                $scrollButtons = $('.scrollbuttons');

                if ( $scrollButtons.length > 0 ) {
                    $scrollButtons.fadeOut('fast', function() {
                        $scrollButtons.remove();
                    });
                }
            }
        }
    }
    //--------------------------
    //-- End Scroll Functions -
    //--------------------------
/**/

