
// Returns a jQuery-wrapped array with integers x such that
// 
//     a <= x <= b
// 
$.range = function(a,b)
{
    var out = [];
    for( var i = a; i <= b; i++ )
        out.push(i);
    return $(out);
};

// number of seconds to hold on the current banner image
var BANNER_DELAY = 4;

// number of banners.  each must be a div like <div id="lhsX" class="lhs">
// for X = 1,2,3,...
var BANNERSC = 3;

// @return the number of seconds in the day that have passed
var get_seconds = function()
{
    var now  = new Date();
    return (now.getHours() * 60 * 60) 
            + (now.getMinutes() * 60) 
            + now.getSeconds();
};

// when the banner was last changed
var last_changed_time = get_seconds();

var switch_handler = function(n, forced)
{
    var now = get_seconds();
    // if it's been BANNER_DELAY or more seconds or we're forced
    // to change, then do it:
    if ( now >= last_changed_time + BANNER_DELAY || forced ) {
        // indicate when we last changed banners
        last_changed_time = now;
        switch_to_banner((n%BANNERSC)+1);
        // set to check again in BANNER_DELAY seconds
        setTimeout(function(){
            switch_handler((n%BANNERSC)+1, false);
        },BANNER_DELAY * 1000);
    }
};


var switch_to_button_image = function(n)
{
    $('#buttons img').each(function(i){
        var src = $(this).attr('src');
        $(this).attr('src',
            src.replace( 
                /(\d).*\.jpg/,
                '$1' + (i+1==n?'on':'off') + '.jpg' 
        ));
    });
};

var switch_to_banner = function(n)
{
    $('#lhs div.lhs:visible').fadeOut('fast',function(){
        $('#lhs'+n).fadeIn('fast');
    });
    $('#banner .rhs').css('background','url(/images/home/rotate/rhs'+n+'.jpg)')
    switch_to_button_image(n);
};

var inject_buttons = function()
{
    var prefix = '/images/home/rotate/';
    var div    = $('#buttons');
    $.range(1,BANNERSC).each(function(){
        var off = '<img src="'+prefix+this+'off.jpg" />';
        div.append(off);
    });
    // need each() since we need the index
    div.children('img').each(function(n){
        $(this).click(function(){
            switch_handler(n,true);
        });
    });
};

$(function(){
    inject_buttons();
    $('#lhs div.lhs:first').show();
    switch_handler(0,true);
});