$(document).ready(function () {
    var browsers = $('.app\\/sidebar\\/initiatives .browser a');
    var showing = $('.app\\/sidebar\\/initiatives .initiatives-proper .active');
    var first = $('.app\\/sidebar\\/initiatives .initiatives-proper li:first-child');
    var w = showing.width();
    var rotating = true;
    
    function show_initiative(to_show)
    {
        if (to_show.attr('id') == showing.attr('id'))
        {
            return;
        }
        var browser_link = browsers.filter('[href=#'+to_show.attr('id')+']');
        browsers.closest('li').removeClass('active');
        browser_link.closest('li').addClass('active');
        var start_left = -1*w;
        if (to_show.prevAll().index(showing) != -1)
        {
            start_left = w;
        }
        
        to_show.css({left:start_left+'px', opacity:0}).addClass('active');
        showing.animate({
            left:-1*start_left+'px',
            opacity:0
        });
        to_show.animate({
            left:0,
            opacity:1.0
        }, function () {
            showing.removeClass('active');
            showing = to_show;
        });
    }
    
    browsers.click(function (e) {
        e.preventDefault();
        var to_show = $($(this).attr('href'));
        show_initiative(to_show);
    });
    
    // rotation
    var timer = false;
    var rotate_pause = 7000;
    
    function rotate()
    {
        if (!rotating)
        {
            return;
        }
        var after = showing.nextAll();
        if (after.size())
        {
            show_initiative($(after.get(0)));
        }
        else
        {
            show_initiative(first);
        }
        timer = window.setTimeout(rotate, rotate_pause);
    }
    
    $('.app\\/sidebar\\/initiatives').hover(function () {
        rotating = false;
        window.clearTimeout(timer);
    }, function () {
        rotating = true;
        timer = window.setTimeout(rotate, Math.round(rotate_pause/2));
    });
    timer = window.setTimeout(rotate, rotate_pause);
});
