/* Set values for gallery auto-rotation */
var iCurrent=1; // Sets the first gallery image
var timer;  // Variable for timer
var iSeconds = 5; // Number of seconds between rotations
var iMax; // Creates variable for the number of gallery images

/* Set inital promo and nav icon on page load */
var currentGallery = "div#galleryImage"+iCurrent;
var currentNav = "a#galleryNav"+iCurrent;
var currentText = "span#galleryText"+iCurrent;

$(document).ready(function(){
	var gallery = document.getElementById("gallery");
	var aGallery = gallery.getElementsByTagName("img");
	iMax = aGallery.length;

	/* Set initial gallery nav state */
	$(currentNav).addClass("selected");
	/* Start timer */
	timer = setInterval("ChangePromo($(currentNav), $('a#galleryNav'+getNextID()))", (iSeconds*1000));
	
	/* add click event function to switch promos */
	$("div#galleryNav a.galleryNav").click(function () {
		ChangePromo($(currentNav), $(this));
		return false;
	});
	
	/* Pause Button - Stops Timer */
		$("div#galleryNav a#galleryPause").click(function () {
			clearInterval(timer);
			return false;
		});
		
		/* Play Button - Changes to next promo, restarting timer */
		$("div#galleryNav a#galleryPlay").click(function () {
			ChangePromo($(currentNav), $('a#galleryNav'+getNextID()));
			return false;
		});

});
		
/* Function to switch promos and restart timer */
function ChangePromo(oCurrent, oNew) {
	// If the user clicks 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);
		
		// Fade photos to switch
		$(currentGallery).fadeOut("slow");
		$($(oNew).attr('href')).fadeIn("slow");
		
		// Update current item
		currentGallery = $(oNew).attr('href');
		iCurrent = Number(currentGallery.substring(13));
		
		// Swap Text if it exists
		newText = $('span#galleryText'+iCurrent);
		if (newText != null) {
			$(currentText).fadeOut("fast");
			newText.fadeIn("fast");
			
			currentText = newText;
		}

		clearInterval(timer);
		timer = setInterval("ChangePromo($(currentNav), $('a#galleryNav'+getNextID()))", (iSeconds*1000));
	};
};

/* Gets ID of next promo for auto-rotate */
function getNextID() {
	iCurrent==iMax ? iCurrent=1 : iCurrent++;
	return iCurrent;
}
