/*
Rotating Images Script
Author: Gavyn Jones
Year: 2009
*/


var delay = 4000;
var timer;
var images;
var current = 0;
var prev = 0;
var max = 0;

$(document).ready(function(){
	
	images = $("#rotation div.image");
	max = images.length - 1;
	prev = max;
	$(images[0]).show();
	timer = setTimeout(rotateImages, 2000);
	
	$(".control").click(function(){
		
		if($(this).hasClass('pause')){
			clearTimeout(timer);
			$(this).text('Play');
		}else{
			timer = setTimeout(rotateImages, 0);
			$(this).text('Pause');	
		}
		
		$(this).toggleClass('play');
		$(this).toggleClass('pause');
		
		return false;
	});
	
	$("#promo").hover(
		function(){
			setTimeout(fadeInControls, 1000);
		},
		function(){
			setTimeout(fadeOutControls, 2000);
		}
	);
	
});

function fadeInControls(){
	$("#controls").fadeIn();
}

function fadeOutControls(){
	$("#controls").fadeOut();
}

function rotateImages(){
	
	// Hide spinner as first image should have loaded by now
	$("#rotation-loading").hide();
	
	$(images[prev]).fadeOut('slow');
	$(images[current]).fadeIn('slow');
	
	$("#image-title").text($(images[current]).contents().find("img").attr('alt'));
	
	if(current == max){
		prev = max;
		current = 0;
	}else{
		prev = current;
		current++;
	}	
	
	timer = setTimeout(rotateImages, delay);	
	
}