(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

var current_num = 1;
var rotation_speed = 7000;
var fade_speed = 2500;

// The next item in our rotating banners
function next_num() {
	current_num += 1;
	if (current_num >= 4) {
		current_num = 1;
	}
	return current_num;
}

jQuery.preLoadImages("/css/images/homepage/1.png", "/css/images/homepage/2.png", "/css/images/homepage/3.png");

function rotate_to(num) {
	if (num) {
		var next = num;
		var fade_speed = 'fast';
	} else {
		var next = next_num();
	}
	
	var past = next-1;
	
	var new_image = 'url(/css/images/homepage/' + next + '.png)';

	$('.rotate h1').fadeOut(fade_speed, function(){
		// Fade out the bad guys and add back the current one
		$('.yui-gb .yui-u:lt(' + (past) + ')').fadeTo('slow', '0.2');
		$('.yui-gb .yui-u:gt(' + (past) + ')').fadeTo('slow', '0.2');
		$('.yui-gb .yui-u:eq(' + (past) + ')').fadeTo('slow', '1');
		
		// Handle the display of the TOC links
		$('ul.toc li').removeClass('active');
		$('ul.toc li:eq(' + past + ')').addClass('active');
		
		$(this).css('backgroundImage', new_image).fadeIn(fade_speed);
	});
}

$(document).ready(function () {
	// Set it up to rotate
	$('.rotate h1').everyTime(rotation_speed, function() {
		rotate_to(null);
	});
	
	// If a user clicks on a number, we go there
	$('ul.toc li').click(function(e) {
		e.preventDefault();
		$('.rotate h1').stopTime();
		rotate_to($(this).attr('rel'));
	});
	
	// And setup our default setup
	$('.yui-gb .yui-u:gt(0)').fadeTo('fast', '0.2');
});