/**
 * JS Code to animate the banner slideshow
 * on the welcome page
 * 
 * Expects following variables:
 *   banners - array of banner details
 *   banner_fade_time - Time to take upon fading the banner
 */
$(document).ready(function() {
	var index = 1; // The next banner to display
	var image_cache = new Array(banners.length); // Please to store cached images
	
	/**
	 * Switch the banners with a fade.
	 */
	function SwitchBanners()
	{
		var $$ = $('#offer a:last');		
		
		// Lets wrap the current stuff and add what we need
		// to perform the switch		
		$$.parent() // div element
			.prepend('<a href=""></a>')
			.find('a:first') // new a element
			.attr('href',banners[index][0])
			.prepend('<img>')
			.find('img:first')	// new img element
			.attr('src',image_cache[index].src);
		
		// Move the initial image over the top
		$$.css({
				'position' : 'absolute',
				'top' : 0,
				'left' : 0
			});
		
		// Now fade it out
		$$.animate({'opacity':0},banner_fade_time*1000, null, function()
		{
			// Remove the old link and image
			$$.remove(); 
		});
		
		// Set timer for next switch
		setTimeout(SwitchBanners, banners[index][2]*1000);
		
		// Inc Index
		index = index + 1;		
		if(index >= banners.length)
		{
			index = 0;
		}		
		
		PreloadImage();
	}

	/**
	 * Preload the next image and save it into the
	 * cache array
	 */
	function PreloadImage()
	{
		if(image_cache[index] == null)
		{
			image_cache[index] = new Image();
			image_cache[index].src = banners[index][1];
		}
	}
	
	// Preload next image in sequence and start timer
	PreloadImage();
	setTimeout(SwitchBanners, banners[0][2]*1000);
});
