$(document).ready(function() {
	// Preload Images
	$(".banner_thumbnail").each(function() {
		$.preLoadImages($(this).attr("src").replace("_thumb", ""));
	});

	var banner_array = new Array();
	var new_banner_array = new Array();

	function set_active_banner(image_source, alt_text)
	{
		$(".banner_image").fadeOut(1000, function () {
			$(this).attr("src", image_source);
			$(this).attr("alt", alt_text);
			$(this).fadeIn(1000);
		});
	}

	function cycle_banners()
	{
		if(0 == banner_array.length)
		{
			banner_array = new_banner_array;
			new_banner_array = new Array();
		}
		if(0 == banner_array.length)
		{
			return;
		}
		next_banner();
	}

	function next_banner()
	{
		if(0 == banner_array.length)
		{
			return false;
		}
		var banner = banner_array.shift();
		set_active_banner(banner.attr("src").replace("_thumb", ""), banner.attr("alt"));
		new_banner_array.push(banner);
		return false;
	}

	function previous_banner()
	{
		if(1 >= new_banner_array.length)
		{
			return false;
		}
		var banner = new_banner_array.pop();
		banner_array.unshift(banner);
		var banner = new_banner_array.pop();
		set_active_banner(banner.attr("src").replace("_thumb", ""), banner.attr("alt"));
		new_banner_array.push(banner);
		return false;
	}

	$(".banner_previous_button").click(function () {
		return previous_banner();
	});
	$(".banner_next_button").click(function () {
		return next_banner();
	});

	// Add rollover to the banner images
	$(".banner_thumbnail").each(function (i) {
		banner_array.push($(this));
		// Add rollover
		$.preLoadImages($(this).attr("src").replace(/(.+)(\.[^.]+)/, "$1_hover$2"));
		$(this).mouseover(function () {
			$(this).attr("src", $(this).attr("src").replace(/(.+)(\.[^.]+)/, "$1_hover$2"));
		});
		$(this).mouseout(function () {
			$(this).attr("src", $(this).attr("src").replace("_hover", ""));
		});
	});
	$(".banner_thumbnail_link").each(function (i) {
		$(this).click(function () {
			$("#main_image_link").attr("href", $(this).attr("href"));

			var $thumbnail = $(this).children("img.banner_thumbnail");

			set_active_banner($thumbnail.attr("src").replace("_thumb_hover", ""), $thumbnail.attr("alt"));

			$(document).stopTime("banner_loop")
			$(document).everyTime("7s", "banner_loop", function() {
				cycle_banners();
			});

			return false;
		});
	});

	// Prevent the first banner from displaying for twice as long
	new_banner_array.push(banner_array.shift());

	$(document).everyTime("7s", "banner_loop", function() {
		cycle_banners();
	});
});
