// DESCRIPTION  ---------------------------------------------------------------

/* When the html doc finishes loading:

 - (The Detail and Thumbnails elements are already hidden)
 - Move the thumbnails off stage right (700px)
 - Update the "slideStartPos" var for the next time the thumbnails need to slide. (700px) 
 - Make the Thumbnails visible again now that the're off stage right
 - Set the photo caption text
 - doThumbnailsIntro() to slide the thumbnails into position:
    - Define the slideEndPos (700)
		- slide('forward')
 - updateDetailPhoto()
	  - Set detail photo to 0% opacity
		- Insert "blank" image into the detailPhoto img to avoid seeing the previous image if the new one hasn't loaded yet.
		- Update currentPhoto for access by other functions
		- resetThumbnails() to reduce opacity for a visual off-state
		- Set the opacity back to 100% for the thumbnail representing the current Detail
		- initImage()
			- sets detail photo to 0% opacity
			- sets visibility to "visible"
			- initiates the fade in of the detail
 - preloads the remaining detail images
 




When the user clicks a thumbnail or a detail photo:

	- loadNextDetailPhoto()
	  - assigns the detailID to target the next detailPhoto array reference
		- updateDetailPhoto()
			- Set detail photo to 0% opacity
			- Update currentPhoto for access by other functions
			- resetThumbnails() to reduce opacity for a visual off-state
			- Set the opacity back to 100% for the thumbnail representing the current Detail
			- initImage()
				- sets detail photo to 0% opacity
				- sets visibility to "visible"
				- initiates the fade in of the detail
		- goToThumbnail()
			- Determine slideEndPos (the value to be applied as a left margin)
			- Initiate the slide
 



When the user clicks on one of the arrows to advance a group of thumbnails:

	- advanceThumbnailGroup()
	 - Set the distance that thumbnails needs to slide (400px)
	 - Determine the end position that the thumbnails needs to move to based on direction and distance
	 - Initiate the slide
	 
	 - If the thumbnails haven't scrolled to their left-most position (thumbnailsWidth - 600px to account for the display of 7 thmbs)
	   - Keep moving them leftwards 
		 
	 - If the thumbnails haven't scrolled to their right-most position (0)
	   - Keep moving them rightwards 
 
 */
 
 



// GALLERY CONFIG  ---------------------------------------------------------------

// The "totalPhotos" variable is defined in the page calling this script



// THUMBNAILS & DETAIL PHOTO FUNCTIONALITY ----------------------------------------


// Keeps track of array reference of image being currently viewed.
// We're going to hack this for now by setting it as the very last image in the sequence. It willbe reset in the init block to 0. 
// Need to do this because we compare detailID & currentPhoto in the loadDetail function...

var currentPhoto = (totalPhotos - 1);

// Keeps a reference to our fade-in setTimeouts
var fadeinTimeout;


// The setOpacity function is passed an object and an opacity value. It then sets the opacity of the supplied object 
// using four proprietary ways. It also prevents a flicker in Firefox caused when opacity is set to 100%, by setting 
// the value to 99.999% instead.

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}


// The fadeIn function uses a Timeout to call itself every 100ms with an object Id and an opacity. The opacity 
// is specified as a percentage and increased 10% at a time. The loop stops once the opacity reaches 100%.

function fadeIn(objId,opacity) {
  if (document.getElementById) {
    var obj = document.getElementById(objId);
    if (opacity <= 100) {
      setOpacity(obj, opacity);
      opacity += 5;
      fadeinTimeout = window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 60);
    }
  }
}
 
 
// This function swaps the previous detail photo with the current photo that the user selected

function updateDetailPhoto(detailID) {
	if (detailID != currentPhoto) {
		// Transitoin to the next photo
		$('#photoholder').cycle(detailID);
		// Update the caption using the detail image's "alt" tag
		var caption = $('#detail_' + detailID).attr("alt");
		$('#photoCaption').text(caption);
		currentPhoto=detailID;
		resetThumbnails();
		var obj = document.getElementById('thmb_' + detailID);	
		setOpacity(obj, 100);
	}
}


function loadNextDetailPhoto(detailID) {
	// If no detail photo id has been supplied, determine the next in line...
	if ((!detailID) && (detailID != 0)) {
		if (currentPhoto < (totalPhotos-1)) {
			detailID= currentPhoto + 1;
			}
		else {
			detailID=0;
		}
	}
	var previousPhoto = currentPhoto;
	updateDetailPhoto(detailID);
	goToThumbnail(previousPhoto);
}



// The initImage function makes the photo completely tranpsarent by using the setOpacity function to set  
// its opacity to zero. The photo can then be made visible and faded in using the fadeIn function:

function initImage() {
  var imageId = 'detailPhoto';
  var image = document.getElementById(imageId);
  setOpacity(image, 0);
  image.style.visibility = 'visible';
  fadeIn(imageId,0);
}


// Sets the thumbnails to 50% opacity to represent their off-state

function resetThumbnails() {
	for (var i=0;i<totalPhotos;i++) {
   	var obj = document.getElementById('thmb_' + i);	
		setOpacity(obj, 50);
	}
}


// This function highlights the thumbnail images when user rolls over them

function doRollover( thumbnailID ) {
	// If User is not mousing over the thumbail for the current Detail Photo, do the rollover effect
	if (thumbnailID != currentPhoto) {		
		var obj = document.getElementById('thmb_' + thumbnailID);	
		setOpacity(obj, 100);
		}
 } 
 
 
// This function removes highlight when the user mouses back out

function doRollout ( thumbnailID ) {
	// After the user rolls off the thumbnail image, set it back to normal.
	if (thumbnailID != currentPhoto) {
		var obj = document.getElementById('thmb_' + thumbnailID);	
		setOpacity(obj, 50);
	}
}



// THUMBMNAIL DISPLAY FUNCTIONALITY  --------------------------------------------------


// When the user clicks the detail to advance one image, the thumbnail needs to advance one thumbnail as well.
// Even if the user has slid the thumbnails in order to view an additional display set.
// So we need to set the slideEndPos based on the current Detail x width of the thumbnail

// We should be advancing so that the highlighted thumbnail is in the middle. (7 thumbnails in one display set)
// So if we're at the beginning of the thumbnails, we shouldn't allow the thumbs to incrementally advance until 
// the user is on detail #4.


var slideinTimeout;

// var maxSlidePosition = maxSlidePosition + 300; // adjust for the 300px it takes to get the highlighted thumbnail in the center
var speed = 1.5;
var slideStartPos;
var slideEndPos;

// The width of one thumbnail image
var slideWidth = 100;
// Width of the entire thumbnail strip
var thumbnailsWidth = totalPhotos * slideWidth;
// The furthest point that the thumbnails are allowed to slide (while still keeping 7 displayed in the frame)
var maxSlidePosition = thumbnailsWidth - 700; // (width of seven thumbnails)
// The amount of slides to advance as a group (when user uses one of the arrow buttons)
var thmbGroup = 4;

// This function handles the sliding of the Thumbnails strip back and forth within its' container.
// The slides are achieved by applying positive or negative "margin-left" values to the "thumbnails" div.
// This function calls itself repeatedly until the slide movement is complete

function slide(direction) {
  if (document.getElementById) {
    var obj = document.getElementById('thumbnails');
		// Figure out the current position of the Thumbnails (and convert results to a number)
		var slideCurrentPos = parseFloat(obj.style.marginLeft);
		slideCurrentPos = Math.floor(slideCurrentPos);
		//alert ("slideCurrentPos: " + slideCurrentPos + " / slideEndPos: " + slideEndPos);
		// If we're moving forward (Thumbnails sliding to the left)...
		if (direction == 'forward') {
			if (slideEndPos < -(maxSlidePosition)) {
				slideEndPos = -(maxSlidePosition);
			}
			// Figure out how far the clip still has to go until it reaches it's destination for this slide movement
			// First check to see if we're in the negative realm or not and add accordingly...
			if (slideCurrentPos > 0) {
				var distance = slideEndPos + slideCurrentPos;
			}
			else {
				//alert("in the negatives...");
				var distance = slideEndPos - slideCurrentPos;
			}
			var adjDistance = distance/speed;
			// Apply the adjusted distance to the left-margin value
			// Again, check to see if we're in the negative realm or not and add accordingly...
			if (slideCurrentPos > 0) {
				var marginLeftValue = Math.floor(slideEndPos + adjDistance) + "px";
			}
			else {
				var marginLeftValue = Math.floor(slideEndPos - adjDistance) + "px";
			}
			//alert ("slideCurrentPos: " + slideCurrentPos + "\nslideEndPos: " + slideEndPos + "\ndistance: " + distance + "\nspeed: " + speed + "\nadjDistance: " + adjDistance + "\nmarginLeftValue: " + marginLeftValue);
      obj.style.marginLeft = marginLeftValue;
			// Use setTimeout to call this function again, redelivering the same variables
      slideinTimeout = window.setTimeout("slide('"+direction+"')", 60);
			
			// If we're done with the slide...
			if (slideCurrentPos <= slideEndPos) {
				obj.style.marginLeft = slideCurrentPos;
				// Mark the position for next time.
				slideStartPos = slideCurrentPos;
				showHideArrows();
				// Stop sliding
				// alert("slideCurrentPos: " + slideCurrentPos + "\nslideEndPos: " + slideEndPos + "\n(slideCurrentPos <= slideEndPos) \n forward: clearing the timeout");
				// alert("forward: clearing the timeout");
				clearTimeout(slideinTimeout);
			}
    }
		
		// Or if we're moving backward (Thumbnails sliding to the right) and we haven't reached the limit
		else if (direction == 'backward') {
		 if (slideEndPos > 0) {
				slideEndPos = 0;
			}	
			// Figure out how far the clip still has to go until it reaches it's destination for this slide movement
			var distance = slideEndPos - slideCurrentPos;
			var adjDistance = distance/speed;
			// Apply the adjusted distance to the left-margin value
			var marginLeftValue = Math.ceil(slideEndPos - adjDistance) + "px";
			//alert ("slideCurrentPos: " + slideCurrentPos + "\nslideEndPos: " + slideEndPos + "\ndistance: " + distance + "\nspeed: " + speed + "\nadjDistance: " + adjDistance + "\nmarginLeftValue: " + marginLeftValue);
      obj.style.marginLeft = marginLeftValue;
			// Use setTimeout to call this function again, redelivering the same variables
      slideinTimeout = window.setTimeout("slide('"+direction+"')", 60);
			
			// If we're done with the slide...
			if (slideCurrentPos >= slideEndPos) {
				obj.style.marginLeft = slideEndPos;
				// Mark the position for next time.
				slideStartPos = slideCurrentPos;
				showHideArrows();
				// Stop sliding
				// alert("slideCurrentPos: " + slideCurrentPos + "\nslideEndPos: " + slideEndPos + "\n(slideCurrentPos >= slideEndPos)\n backward: clearing the timeout");
				// alert("backward: clearing the timeout");
				clearTimeout(slideinTimeout);
			}
    }
  }
}


// For sliding a group of thumbnails (using arrow buttons)...
// Determines the emd position of the slide movement we're about to do, based on direction.
// Then it intitiates the slide. 
function advanceThumbnailGroup(direction) {
	//alert ("moving " + direction);
	//Determine the distance the thumbnails need to slide
	var slideDistance = thmbGroup * slideWidth;
	// If we're moving forward (Thumbnails sliding to the left), we need to subtract negative margin-left 
	// values from the current margin-left value
	if (direction == 'forward') {
		slideEndPos = slideStartPos - slideDistance;
	}
	// If we're moving backward (Thumbnails sliding to the right), we margin-left values to the current margin-left value
	else {
		slideEndPos = slideStartPos + slideDistance;
	}
	// Initiate the slide
  slide(direction);
}







// Shows and Hides arrows if we're at the bginning or ebd of the thumbnail strip

function showHideArrows() {
	var obj = document.getElementById('thumbnails');
	var slideCurrentPos = parseFloat(obj.style.marginLeft);
	slideCurrentPos = Math.floor(slideCurrentPos);
	
	if (slideCurrentPos == 0) {
		document.getElementById('leftArrow').style.visibility = 'hidden';
	}
	else {
		document.getElementById('leftArrow').style.visibility = 'visible';
	}
	if (slideCurrentPos == -(maxSlidePosition)) {
		document.getElementById('rightArrow').style.visibility = 'hidden';
	}
	else {
		document.getElementById('rightArrow').style.visibility = 'visible';
	}
	//alert (slideCurrentPos + " | " + maxSlidePosition);
}	






// Determines the emd position of the slide movement we're about to do, based on direction.
// Then it intitiates the slide. 
// Slide type can be set as either "single" or "group"
function goToThumbnail(previousPhoto) {
	// Need to find the exact position. We can't just increment due to the fact that the user may have used the arrows 
	// to advance the thumbnails and the current thumbnails may not be visible.
	// Adjust 300 px in order to center the current thumbnail
	
	
	/* PROBLEM: When the user has used the arrows to advance the thumbnails, but then clicks the detail to advance one, 
	the thumbanisl don't slide correctly. They try to move forward because the user is "advancing" one detail shot...
	
	So I think that what needs to happen is this:
	1. Instead of comparing the detail number, we're going to have to compare the thumbnail position of the detail being 
	clicked to against the position of where the thumbnail's currently at in order to determein whther the slide should move "forward" or "backward"
	*/
		
	// alert ("currentPhoto: " + currentPhoto + " |  previousPhoto: " + previousPhoto + " |  direction: " + direction);
	
	// If we're on the very last detial photo...
	if (currentPhoto == totalPhotos) {
		// Send the thumbnails back to the beginning...
		slideEndPos = 0;
		// Initiate the slide
		slide('backward');
	}
	// Otherwise, advance as usual...
	else {
	
		// Establish the direction we'll need to slide
		// Figure out where the thumbnails are currently
		var obj = document.getElementById('thumbnails');
		var slideCurrentPos = parseFloat(obj.style.marginLeft);
		slideCurrentPos = Math.floor(slideCurrentPos);
		// Determine where the thumbnails need to go	
		slideEndPos = (-(currentPhoto * slideWidth)) + 300;
		// Now, figure out the direction
		if (slideCurrentPos > slideEndPos ) { 
			var direction='forward';
		}
		else {
			var direction='backward';
		}
		// alert ("currentPhoto: " + currentPhoto + " |  slideEndPos: " + slideEndPos);
		// Initiate the slide
		slide(direction);
	}
	//alert ( "currentPhoto: " + currentPhoto + " totalPhotos: " + totalPhotos + " slideEndPos: " + slideEndPos);
}





// This function is called only once after the page loads
// The first time the thumbnails advance, they have to enter from stage right,
// crossing form the right to the left. For this, we need a different function call.
function doThumbnailsIntro() {
	// slideDistance = 700 for the very first slide
	slideEndPos = slideStartPos - 700;
	// Initiate the slide
  slide('forward');
}




// INITIALIZE THE PAGE ELEMENTS  --------------------------------------------------


// First, hide the photo until it is completely cached (when page has finished loading)
document.write("<style type='text/css'>#detailPhoto {visibility:hidden;} </style>");
// Also, hide the thumbnails until we're ready to slide them on as well
document.write("<style type='text/css'>#thumbnails {visibility:hidden;} </style>");

// Also, define the thumbnails until we're ready to slide them on as well
document.write("<style type='text/css'>#thumbnails {width:" + thumbnailsWidth + "px;} </style>");


// Initialize....
// Set this up as a function call that can be called along with other functions in a global window.onload event handler in the html file	
	
	
function initGallery() {
	// Position 'Thumbnails' just off stage right
	var obj = document.getElementById('thumbnails');
	obj.style.marginLeft = "700px";
	slideStartPos = 700;
	// Make the thumbnails visible again (hidden while page loads initially)
	obj.style.visibility = 'visible';
	// load first detail photo & caption
	updateDetailPhoto(0);
	// Slide the thumbnails in to fill the container area
	doThumbnailsIntro();
}



 


