/**
 * Image banner for Cal Poly Supermileage
 * Copyright 2009 Bob Somers
 */

var bannerImages = {"images/banner/awards.jpg": "The 2009 team accepts their second place finish at the awards ceremony.",
					"images/banner/interview.jpg": "Veteran driver Kevin Fang talks to the media before a run.",
					"images/banner/enginework.jpg": "Team lead Denny Truong works on the engine in the pit.",
				 	"images/banner/techinspection.jpg": "The team waits for the Black Widow to clear technical inspection.",
					"images/banner/fuelingup.jpg": "Verteran driver Kevin Fang waits for the Black Widow to get fueled up.",
				 	"images/banner/startingline.jpg": "The Black Widow gets the green flag the starting line."};

var bannerIndex = 1;
var bannerSize = 0;
var bannerCycleTime = 5000;

function initBanner()
{	
	// inject images into the dom
	for (var i in bannerImages)
	{
		$("#imagebanner").append('<img src="' + i + '" alt="' + bannerImages[i] + '" />');
		$("#imagebanner img").css("position", "absolute").css("display", "none");
		$("#imagebanner img:first").css("display", "inline").css("z-index", "2");
		bannerSize++;
	}
	
	// inject caption bar into the dom
	$("#imagebanner").append('<div id="captionbar"></div>');
	var topMargin = parseInt($("#imagebanner").css("height")) - (parseInt($("#captionbar").css("height")) + parseInt($("#captionbar").css("padding-top"))) + "px";
	$("#captionbar").css("position", "absolute").css("margin-top", topMargin).css("z-index", "3").fadeTo(0, 0.75);
	var caption = "";
	for (i in bannerImages)
	{
		$("#captionbar").text(bannerImages[i]);
		break;
	}
	
	setTimeout(rotateBanner, bannerCycleTime);
}

function rotateBanner()
{	
	// calculate next and current indexes
	nextIndex = bannerIndex;
	curIndex = (bannerIndex + (bannerSize - 1)) % bannerSize;
	
	// shuffle the next image in front of the current one
	$("#imagebanner img:eq(" + curIndex + ")").css("z-index", "1");
	$("#imagebanner img:eq(" + nextIndex + ")").css("z-index", "2");
	
	// do the fade
	$("#imagebanner img:eq(" + nextIndex + ")").fadeIn(1000, function()
	{
		// calculate current and previous indexes
		curIndex = bannerIndex;
		prevIndex = (bannerIndex + (bannerSize - 1)) % bannerSize;
		
		// hide the previous image and reset the z-index
		$("#imagebanner img:eq(" + prevIndex + ")").css("display", "none").css("z-index", "");
		
		// increment the banner index
		bannerIndex = (bannerIndex + 1) % bannerSize;
		
		// reschedule the timeout
		setTimeout(rotateBanner, bannerCycleTime);
		
		// set the text in the caption bar
		var caption = "";
		var index = 0;
		for (i in bannerImages)
		{
			if (index == curIndex)
			{
				caption = bannerImages[i];
				break;
			}
			index++;
		}
		$("#captionbar").text(caption);
	});
}