$(document).ready(function () {

    // cache some stuff
    var container = $('#container');
    var inner_container = container.children('#inner_container');
    var bg = container.children().children('#background_highlight');
    var ul = container.children().children('ul');
    var bb = container.children('#bottom_bar');

    var i = 0;
    var containerLen = ul.children('li').length;

    var rotateSpeed = 5000;
    var featureTimeout = setTimeout(featureRotate, rotateSpeed);


    function featureRotate() {

        var active_tab = $('#container ul').find('li.selected');
        var next_tab = active_tab.next();

        if (next_tab.length) {
            next_tab.find('a').trigger('click');
        } else {
            $('#container ul').find('li:first a').trigger('click');
        }

        featureTimeout = setTimeout(featureRotate, rotateSpeed);

        return false;

    }

    $("#container").bind("mouseenter", function () {
        clearTimeout(featureTimeout);
        featureTimeout = false;
        return false;
    }).bind("mouseleave", function () {
        featureTimeout = setTimeout(featureRotate, rotateSpeed);
        return false;
    });




    ul.children('li').children('a').click(function () {
        $$ = $(this);

        $$.parent().parent().find('li').removeClass('selected');
        $$.parent("li").addClass('selected');

        var img = $$.attr('href').substr(1);

        // do ye old image switch with fade
        inner_container.hide().css('background', 'url(images/' + img + ') no-repeat');
        inner_container.fadeIn(500, function () {
            container.css('background', 'url(images/' + img + ') no-repeat');
            inner_container.hide();
        });

        bb.fadeOut(function () {
            $(this).html($$.siblings('span').html());

            bb.fadeIn();
        });

        ul.children('li').children('p').hide();

        // move the background
        bg.animate({
            top: $$.position().top + 'px'
        }, function () {
            $$.siblings('p').slideDown();
        });

        return false;
    });

});
