/* Set values for gallery auto-rotation */
var iCurrent=1; // Sets the first gallery image

/* Set inital promo and nav icon on page load */
var currentGallery = "div#rotate"+iCurrent;
var currentNav = "a#rotateNav"+iCurrent;
var currentText = "div#rotateText"+iCurrent;

function prepareRotator() {
	var iMax = $("#imageRotator > div > img").size();
	if (iMax > 0) {
		var rotatorNav = '<div id="rotateNav"><span>Images:</span>' +
						 '<ul>';
		for (i=1; i<=iMax; i++) {
			rotatorNav += '<li><a id="rotateNav' + i + '" class="rotateNav" href="#rotate' + i + '"><span>' + i + '</span></a></li>';
		}
		rotatorNav += '</ul>' +
					  '</div>';
		
		$(".location").before(rotatorNav);
		
		/* Set initial gallery nav state */
		$(currentNav).addClass("selected");
		
		/* add hover intent event function to switch promos */
		$("div#rotateNav a.rotateNav").hoverIntent(
			function () {
				ChangePromo($(currentNav), $(this));
				return false;
			}, function() {}
		);
		/* Remove click function from links */
		$("div#rotateNav a.rotateNav").click( function() { return false; } );
		
		
		
		var rotatorText = '<div id="rotatingText" class="content">'
		for (i=1; i<=iMax; i++) {
			iHide = (i==1) ? "" : " hide";
			rotatorText += '<div id="rotateText' + i + '" class="rotateText' + iHide + '">' +
                           '<p>' + $("#rotate"+i).find("img").attr("alt") + '</p>' +
						   '</div>';
		}
        rotatorText += '</div>';
		if ($("#caseStudyRotatorText")) {
		$("#caseStudyRotatorText").append(rotatorText);
		}
		
	}
}
		
/* Function to switch promos and restart timer */
function ChangePromo(oCurrent, oNew) {
	// If the user hovers on a different item than the current item
	if ($(oCurrent).attr('href') != $(oNew).attr('href')) {

		// Update classes on  nav items
		$(oCurrent).removeClass("selected");
		$(oNew).addClass("selected");
		
		// Update current nav item
		currentNav = $(oNew);

		var newGalleryHref = $(oNew).attr('href');
		var newGallery  = newGalleryHref.substr(newGalleryHref.indexOf("#"), 8)

		$(currentGallery).fadeOut("slow");
		$(newGallery).fadeIn("slow");

		// Update current item
		currentGallery = newGallery;
		iCurrent = Number(currentGallery.substring(7));
		
		// Swap Text if it exists
		newText = $('div#rotateText'+iCurrent);
		if (newText != null) {
			$(currentText).fadeOut("fast");
			newText.fadeIn("fast");
			currentText = newText;
		}
	};
};