// routines for the imageRotator
var imageRotatorMoveNext = false;
var imageRotatorInAnimation = false;

$(document).ready(function(){
	var newLeftPos = 0;
	// create image lineup
	$(".imageRotatorPanels div").each(function(index){
		imgWidth=$("img",this).width();
		$(".imageRotatorContent").append(this);
		$(".imageRotatorContent .imageRotatorPanel:last").css('left',newLeftPos);
		newLeftPos+=(imgWidth);
	});
	
	// preload images
	$(".imageRotatorContent img").imgpreload(function(){
		initializeImageRotator();	
	});
	
});

function initializeImageRotator() {
	// add event listener so that auto rotation is turned off while mouseover and turn on when mouseout
	$(".imageRotatorContent").hover(function(){autoRunImageRotator(false);},function(){autoRunImageRotator(true);});
	
	// add event listener so auto rotations stops /starts when the page loses/gains focus
	$(document).blur(function(){ autoRunImageRotator(false); });
	$(document).focus(function(){ autoRunImageRotator(true); });
	
	// auto rotate panels
	autoRunImageRotator(true);
}

function autoRunImageRotator(toggle) {
	if (toggle) {
		// turn on the auto rotation event if it is not already on
		if (!imageRotatorMoveNext) {
			imageRotatorMoveNext=true;
			imageRotatorShowNextPanel();
		}
	} else {
		// turn off the auto rotation event
		if (imageRotatorMoveNext) { imageRotatorMoveNext=false; }
	}
}

function imageRotatorShowNextPanel() {
	if (imageRotatorMoveNext && !imageRotatorInAnimation) {
		// slides the container to the left by the width of the first image
		var slideWidth=$(".imageRotatorContent img:first").width()*-1;
		var newDivPos=0, imgWidth;
		
		imageRotatorInAnimation=true;
		$(".imageRotatorContent").animate({left: slideWidth},3000,function(){
			imageRotatorInAnimation=false;
			// remove the first div tag that is now out of view
			var firstDiv=$(".imageRotatorContent div:first").detach();
			// recalculate LEFT position for each remaining div
			$(".imageRotatorContent div").each(function(index){
				imgWidth=$("img",this).width();
				$(this).css('left', newDivPos);
				newDivPos+=imgWidth;
			});
			// update the image to append with it's new left position prior to appending
			$(firstDiv).css('left', newDivPos);
			$(".imageRotatorContent").append(firstDiv);
			// reorient all of the content to the left
			$(".imageRotatorContent").css('left',0);
			
			if (imageRotatorMoveNext) { imageRotatorShowNextPanel(); }
		});
	}
}
