/*
	Name				: 	slideshow.js
	Purpose				:	This will create a slideshow out of multiple images automatically displaying the next image in the list
	Created				:	01/15/2004
	Author				:	Charles Taylor

*/

//Setup an array variable for use later
var slideShowTimerArray = []; //array to cache slideshow instances
//Global var only used if using a specific directory for an image

//This function sets up the name of the image and the controls used in the slide show
function SetupSlideShowSettings(){
	//These defaults can and probably should be OVERRIDDEN by the user
	/******************* Configuration Variables **********************************/
	this.imageName = "photo"; //the name of the image to rotate
	this.showNavControls = true; //show back next and stop/play
	this.showNavControlsAsText = false; //by default the nav controls are shown as images
	this.showPicTotals = true // Show how many photos are showing and what photo they're currently viewing
	this.imageRotateSpeed = 5000; // The speed of the slide show transition
	this.imagesPath = "images/"; // The location of where the slide show images are located
	this.navControlImagesPath = "/buttons/"; //This is the location of the nav control button images
	this.imagePicTotalsSpanID = "photoTotal"; // This tells the user how many photos are being viewed	
	this.stopText = "Stop"; // This will be used if user opts for text instead of image button nav controls
	this.playText = "Play"; //This will be used if the user opts for text instead of image button nav controls
	this.spanIDForPlayPauseControl = "playPause"; //This is the span for the text or image controls play/stop
	this.cssStyleSheetForTexControls = ""; // may be used later to apply a style to the text controls	
	this.pauseBeforeRestartingPlayOnJumpToImage = false; // this is used to delay the rotation when jumping to a specific image while the slideshow is running
				
} // end funciton SetupSlideShowSettings()

//This is the constructor for the RunSlideShow Object. It passes in a SetupSlideShowSettings Object to initialize it
function RunSlideShow(localVarSlideShowName, slideShowSettings) {
		
		/******************* Configuration Variables **********************************/
		this.localVarSlideShowName = localVarSlideShowName //This is a pointer to the slide show variable the user has placed on the page to run this slideshow
		this.imageName = slideShowSettings.imageName; //only using name instead of id for backward compatibility with IE4
		this.showNavControls = slideShowSettings.showNavControls; // This determines if we are going to show the next, stop and back buttons
		this.showPicTotals = slideShowSettings.showPicTotals; // This determines if we're going to show the user how many pictures are to be displayed
		this.showNavControlsAsText = slideShowSettings.showNavControlsAsText; // Show nav controls as text or images
		this.rotateSpeed = slideShowSettings.imageRotateSpeed; //changes to the next image every 5 seconds
		this.imageArray = []; //holds all the images to be rotated
		this.imageCounter = 0; //This is the counter that keeps track of what image we're on
		this.timer = 0; //This is the timer that controls the next rotate
		this.timerIsRunning = false //determines if the timer is on
		this.imagePath= slideShowSettings.imagesPath; //if no path is set this is just blank	
		this.navControlImagesPath = slideShowSettings.navControlImagesPath;
		this.browser = this.getBrowserType(); //Get the type of browser the client is running
		this.imageNumSpanID = slideShowSettings.imagePicTotalsSpanID; //This is the span tag that tells what image number we're currently on and the image totals		
		//local variable
		slideShowTimerArray[slideShowTimerArray.length]=this //put the RunSlideShow Object into this array
		this.slideShowID= (slideShowTimerArray.length-1) //get the current slide show instance number
		this.stopText = slideShowSettings.stopText; //the text to show while the slide show is playing
		this.playText = slideShowSettings.playText; //the text to show while the slide show is stopped
		this.spanIDForPlayPauseControl = slideShowSettings.spanIDForPlayPauseControl; //This is the span for the text controls or all image controls
		this.currentMozillaOpacity = 1; //Keeps track of image transitions for Mozilla browser FF && NN
		this.beginMozFadeOut = true; //begins the fadeout
		this.mozTimer = 0; // the timer for the Mozilla fade
		this.pauseBeforeRestartingPlayOnJumpToImage = slideShowSettings.pauseBeforeRestartingPlayOnJumpToImage;
				
} // end RunSlideShow constructor


/******************* Member Functions *****************************************/

RunSlideShow.prototype.getBrowserType = function(){
	var browserType = "unknown";
	if (document.all && !document.getElementById){
			browserType = "ie4";
		} else if (document.all && document.getElementById){
			browserType = "ie5+";
		} else if (!document.all && document.getElementById){
			browserType = "ns6firefox";
		}			
		return browserType; //return the type of browser found

} //end function getBrowserType()


//This function allows you to add multiple images at the same time
RunSlideShow.prototype.addImages = function(){

	var currentImage; //create a local variable	
	//loop through all the images that were passed as parameters to the addImages function	
	for(var curImg=0; curImg < arguments.length; curImg++)
		{
			currentImage = new Image(); //construct a new image			
			//May have a directory specified other than the default					
			if (isArray(arguments[curImg])){				
				var imgDirArray = arguments[curImg];								
				currentImage.src = imgDirArray[0] + imgDirArray[1];
			} else{			
				currentImage.src = this.imagePath + arguments[curImg]; //set the source of the new image
			}
			this.imageArray[this.imageArray.length] = currentImage; //Add it to the end of the imagesArray array variable
		} //end for

} //end function addImages()

/*This function adds one single image at a time to the ImagesArray array variable
  This may be an easier function to call in a loop from .NET or ColdFusion than th addImages function
*/
RunSlideShow.prototype.addImage = function(imageToAdd){

		var img = new Image(); //construct a new image object
		if (isArray(imageToAdd)){ //the user is specifying a different directory for the image			
			img.src = imageToAdd[0] + imageToAdd[1];			
		}else{
			img.src = this.imagePath + imageToAdd; //this gets the actual image we want to store
		}
		this.imageArray[this.imageArray.length] = img //Store this image in the images array 		
		
} //end function addImage()


// This function is the one that shows the image to the viewer
RunSlideShow.prototype.setImageSource = function(){
	
		//Now set the photo to be the one to be currently viewed in the slide show
		if (document.images[this.imageName]) { //first make sure it exists			
			document.images[this.imageName].src= this.imageArray[this.imageCounter].src; 							
		} //end if document.images

}

//This function Initializes the slide show
RunSlideShow.prototype.start = function() {	
	
	//Only run the slideshow if there is more than one image
	if (this.imageArray.length > 1){
			this.startTimer(); //Starts the timer	
			
			if (this.showNavControls){
				if (!this.showNavControlsAsText){	
					this.writeImageNavControlsHTML(this.stopText); //Show the initial controls set to play
				} //end if NOT showNavControlsAsText	
			} // end if showNavControls
	}
	
	//Only if the programmer wants to show the totals
	if (this.showPicTotals) {
		this.writeImageTotal(); // only do this if the interface needs to see how many images are being displayed		
	} //end if	
			
} //end function start


//This is the heart of the slide show where the rotating of images takes place
RunSlideShow.prototype.rotate = function(){
		//alert("Counter: " + this.imageCounter)
		if ((this.imageCounter+1) >= this.imageArray.length){
				this.imageCounter = 0; //reset the counter if it's at the end
		} else {
				++this.imageCounter; //increment the image counter
		}  //end if		
		//Now switch the Photo 		
			if (this.browser == "ie4" || this.browser == "ie5+"){ //Initialize fancy transition for ie4 browsers
				this.runInternetExplorerTransition();
			} else{
			 	//Assume a Mozilla Browser here 
				this.runMozillaTransition();
			} //end if this.browser												
				//Now Write out the image totals
				this.writeImageTotal();			
		
				
} // end function rotate()


RunSlideShow.prototype.runInternetExplorerTransition = function(){

				document.images[this.imageName].style.filter="blendTrans(duration=2)";
				document.images[this.imageName].filters.blendTrans.Apply();					
				//Set the image to the next image in our array
				this.setImageSource(); //Place the image for display 			
				document.images[this.imageName].filters.blendTrans.Play();
	
} //end of running IE transition

RunSlideShow.prototype.runMozillaTransition = function(){					
				//fade out then in
				this.mozTimer = setInterval("slideShowTimerArray["+this.slideShowID+"].fadeMozillaPhoto()",100);		
				
} //end of running Mozilla transition

RunSlideShow.prototype.fadeMozillaPhoto = function(){
	
	var imageBeingSwapped = this.getProperElementSelector(this.imageName);
	var FullyOpaque = 1;
	var ZeroOpacity = 0.20;		
	//var MathArray = [0,0.05,0.10,0.15,0.20,];
	  //  alert(this.currentMozillaOpacity)
	if (this.currentMozillaOpacity > ZeroOpacity && this.beginMozFadeOut){ //fade out
			//alert("Greater than zero capacity " + this.currentMozillaOpacity);
			this.currentMozillaOpacity -= parseFloat(0.1);
			imageBeingSwapped.style.MozOpacity = this.currentMozillaOpacity;
	}else if (this.currentMozillaOpacity < ZeroOpacity){ //swap with new image
			//place the image			
			this.setImageSource(); //Place the image for display 
			this.currentMozillaOpacity = 0.20;			
			this.beginMozFadeOut = false;
			
	}else if (this.currentMozillaOpacity < FullyOpaque && !this.beginMozFadeOut){ // fade in
			//alert("fading back in" + this.currentMozillaOpacity);
			this.currentMozillaOpacity += parseFloat(0.1);
			//alert(this.currentMozillaOpacity)
			if (parseFloat(this.currentMozillaOpacity) >= 0.90 && parseFloat(this.currentMozillaOpacity) < FullyOpaque){
				//alert(this.currentMozillaOpacity)
				this.currentMozillaOpacity = 1;
				//imageBeingSwapped.style.MozOpacity = this.currentMozillaOpacity;				
			}else{			
				imageBeingSwapped.style.MozOpacity = this.currentMozillaOpacity;
			}	
	}else if (this.currentMozillaOpacity >= FullyOpaque && !this.beginMozFadeOut){
				
				if (this.mozTimer != null){ //make sure the timer is still going
        			clearInterval(this.mozTimer) //clear the timer.
					this.mozTimer = null; //totally clear the timer
				}	//end inner if	
				//alert("done" + this.currentMozillaOpacity)
				this.currentMozillaOpacity = 1; //reset				
				this.beginMozFadeOut = true;
	}
	

} //end fadeMozillaPhoto()



//This function returns the proper div or span element to work with the object later
RunSlideShow.prototype.getProperElementSelector = function(elementID){
			
			if (this.browser == "ie4"){	//only use this for ie4
				theElementSelector = document.all[elementID];			
			} else{
				theElementSelector = document.getElementById(elementID);
			} //end if this.browser
			
			return theElementSelector;

} //end function getProperElementSelector()

//This function is in charge of wrting the text "Showing x of N" so the user knows what picture they're on and how many there are in total
RunSlideShow.prototype.writeImageTotal = function(){
	
	if (!this.showPicTotals) { return; } //Don't do anything if they don't want to show totals
	
		var curImgNumText = this.getProperElementSelector(this.imageNumSpanID); //Now Set the proper element's text value
		//content
		var photoTotalContent = "Showing Photo <b>" + (this.imageCounter + 1) + "</b> of <b>" + this.imageArray.length + "</b>";	
		
		//now write the content to the screen
		this.writeDivOrSpanContent(curImgNumText, photoTotalContent);		
		
} // end writeImageTotal()


// This function deals with taking the slideShow directly to a particular image
RunSlideShow.prototype.jumpToImage = function(imageToJumpTo){
		
	var restartRotation = false; // using this variable to know if we need to keep the rotation going after displaying the new image
		
	if  (this.timerIsRunning){ //if the timer is running then stop it		
		restartRotation = true; //This slideshow was rotating, so set this var to true
		this.pauseBeforeRestartingPlayOnJumpToImage = true; //pause before restarting slideshow if it's currently running
		this.clearTimer(); //Stops the timer	
	} // end timerIsRunning if	
		
		this.imageCounter = imageToJumpTo; //reset which image the image array is currently on
		//Now show the photo as the one being currently viewed in the slide show
		this.setImageSource(); //Place the image for display 

			//If the rotation was originally running, then restart it now
			this.writeImageTotal();
			if (restartRotation){ this.play(); } 
			
			//Turn off the global pause
			this.pauseBeforeRestartingPlayOnJumpToImage = false;

} // end function jumpToImage()


//This function will stop the slideshow from running.
//It takes the span id of the span text to change
RunSlideShow.prototype.pause = function(){	
	
	//Get the span to write to
	var spanObj = this.getProperElementSelector(this.spanIDForPlayPauseControl);
	
	this.clearTimer(); //Stops the timer	
	
	if (this.showNavControlsAsText){	
		//now write the content to the screen
		this.writeDivOrSpanContent(spanObj, this.playText);		
	
	}else{ // write out the image button nav controls		
		this.writeImageNavControlsHTML(this.playText);
	} 
} //end function pause()

//This function will restart the slideshow
RunSlideShow.prototype.play = function(){
	
	var playPauseObject = this.getProperElementSelector(this.spanIDForPlayPauseControl); //get spanID
	
	//Only call the rotate function if we need to immediately start rotating again
	if (!this.pauseBeforeRestartingPlayOnJumpToImage){		
		this.rotate(); //start the rotation going immediately	
	}
	//Restart the timer
	this.startTimer();	//Now set the next rotation interval
	
	if (this.showNavControlsAsText){				
		//now write the content to the screen
		this.writeDivOrSpanContent(playPauseObject, this.stopText);			
		
	}else{ // write out the image button nav controls
		this.writeImageNavControlsHTML(this.stopText);
	} //end if this.showNavControlsAsText
	
} // end function play()

// This function is only used by play/pause controls shown as a text link
RunSlideShow.prototype.playOrPause = function() {
														
	//Now either stop the show or resume it
		if (playPauseObject.innerHTML == RunSlideShow.stopText) {			
			this.pause(playPauseObject); //Start playing the slide show again			
		}else{			
			this.play(playPauseObject); //Pause the slide show			
		} //end if
		
} // end function playOrPause()


// Starts the timer for the slide show
RunSlideShow.prototype.startTimer = function(){
	
	this.timer = setInterval("slideShowTimerArray["+this.slideShowID+"].rotate()",this.rotateSpeed);	
	this.timerIsRunning = true; //starting the timer

} // end function startTimer()


// Clears out the timer for the slide show
RunSlideShow.prototype.clearTimer = function(){
	
	if	(this.timerIsRunning){ //if the timer is running then stop it
		if (this.timer != null){ //make sure the timer is still going
        	clearInterval(this.timer) //clear the timer.
			this.timer = null; //totally clear the timer
		}
     	this.timerIsRunning = false; //set whether or not timer is running to false		
	} // end outer if
	
} // end function clearTimer()

//This function will show the previous image in the slideshow
RunSlideShow.prototype.showPrevious = function(){
								
				//If the counter is at zero, set it to the last image in the imagesArray
				if (this.imageCounter==0){
					this.imageCounter = (this.imageArray.length-1);
				}else{
					this.imageCounter--; //decrement the image counter
				}
				//alert(this.imageCounter + " Array" + this.imageArray.length);				
				this.setImageSource(); //Place the image for display 
				
				//Now Write out the totals
				this.writeImageTotal();
				
} // end function showPrevious()

//This function will show the next image in the slideshow
RunSlideShow.prototype.showNext = function(){				
				//alert(this.imageCounter + " Array" + this.imageArray.length);
				if (this.imageCounter >= (this.imageArray.length-1)){
					this.imageCounter = 0; //Reset the counter if it greater than the imageArray
				}else{
					this.imageCounter++; //increment the counter
				}			
				
				this.setImageSource(); //Place the image for display 
				
				//Now Write out the totals
				this.writeImageTotal();
} // end function showNext()

//Used for mouseover and mouseout events for the play/stop next and back buttons
RunSlideShow.prototype.swapImageControl = function(imageName, swapImageFile) {			
			if (document.images[imageName]){			
				document.images[imageName].src =  this.navControlImagesPath + swapImageFile; 			
			} //end if			
}	// end function swapImageControl()


RunSlideShow.prototype.writeImageNavControlsHTML = function(playOrPause){
		
			var navControlHTML = "";
			 navControlHTML += "<table width=\"50\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
			 navControlHTML += " <tr>";
			 navControlHTML += "<td width=\"34\"><a href=\"javascript:" + this.localVarSlideShowName + ".showPrevious();\" onmouseover=\"" + this.localVarSlideShowName + ".swapImageControl('prevButton', 'prev_hover.gif')\" onmouseout=\"" + this.localVarSlideShowName + ".swapImageControl('prevButton', 'prev_off.gif')\"><img src=\"" + this.navControlImagesPath + "prev_off.gif\" name=\"prevButton\" width=\"18\" height=\"19\" vspace=\"5\" border=\"0\" /></a></td>";
			 navControlHTML += "<td>&nbsp;</td>";
			 navControlHTML += "<td width=\"56\">";
			 if (playOrPause == this.stopText){
				 navControlHTML += "<a href=\"javascript:" + this.localVarSlideShowName + ".pause();\" onmouseover=\"" + this.localVarSlideShowName + ".swapImageControl('playStopButton', 'stop_hover.gif')\" onmouseout=\"" + this.localVarSlideShowName + ".swapImageControl('playStopButton', 'stop_off.gif')\"><img src=\"" + this.navControlImagesPath + "stop_off.gif\" name=\"playStopButton\" width=\"18\" height=\"19\" vspace=\"5\" border=\"0\" /></a>";
			 }else{
				 navControlHTML += "<a href=\"javascript:" + this.localVarSlideShowName + ".play();\" onmouseover=\"" + this.localVarSlideShowName + ".swapImageControl('playStopButton', 'play_hover.gif')\" onmouseout=\"" + this.localVarSlideShowName + ".swapImageControl('playStopButton', 'play_off.gif')\"><img src=\"" + this.navControlImagesPath + "play_off.gif\" name=\"playStopButton\" width=\"18\" height=\"19\" vspace=\"5\" border=\"0\" /></a>";			 
			 } //end if
			 navControlHTML += "</td>";
			 navControlHTML += "<td>&nbsp;</td>";
			 navControlHTML += "<td width=\"34\"><a href=\"javascript:" + this.localVarSlideShowName + ".showNext();\" onmouseover=\"" + this.localVarSlideShowName + ".swapImageControl('nextButton', 'next_hover.gif')\" onmouseout=\"" + this.localVarSlideShowName + ".swapImageControl('nextButton', 'next_off.gif')\"><img src=\"" + this.navControlImagesPath + "next_off.gif\" name=\"nextButton\" width=\"18\" height=\"19\" vspace=\"5\" border=\"0\" /></a></td>";
			 navControlHTML += "</tr></table>";
			 
			 //Now write out the content to the screen
			 this.writeDivOrSpanContent(this.getProperElementSelector(this.spanIDForPlayPauseControl), navControlHTML);			
			
		}
		
// This function is in charge of actually writing the content into the innerHTML of the div or span
RunSlideShow.prototype.writeDivOrSpanContent = function(theSpanOrDivToWriteTo, theContent){
		theSpanOrDivToWriteTo.innerHTML = theContent;
} // end function writeDivOrSpanContent()


//This is just used to test the RunSlideShow function
RunSlideShow.prototype.toString = function() {
	
	return "hello " + this.browser;
}


/******************* HELPER Functions *****************************************/

//Helper function for dropping array objects into the addImage and addImages functions
//This allows someone setting up the slideshow to have different images use different directories
function imageAndDir(imageDirectory, imageFile) {
				if (arguments.length < 2){ 
					alert("ERROR: You must include both an image and a directory");
					return;
				} 
				var newArrayObject = new Array(arguments.length)				
				newArrayObject[0] = imageDirectory;
				newArrayObject[1] = imageFile;							
				return newArrayObject;
}

//Determines if the object being passed is an array
function isArray(obj){
   return isObject(obj) && obj.constructor == Array; 
}

//Determines if the item being passed is an array
function isObject(obj){
   return (obj && typeof obj == 'object');
}
