/* galleryRotate.js
 * Mark Hildreth
 * Rotates through multiple gallery/subtexts.

 * Description:
 * Takes an array of images, along with some descriptions of that graphic, and will load and place them on the
 * screen one by one.

 * Usage:
 * Place "gallery_rotate" class on a div. Example:
 * <div class="gallery_rotate"></div>
 *
 * Call run_gallery() with an array of arrays...
 * 	[ "my/img.jpeg", "Some Play Name", 1980, "Extra Tagline", "optional/url.html" ],
 * 	[ "an/img.jpeg", "Some other play", 1982, "A Tagline", "" ]
 * ]
 */



// In milliseconds (1000 millisecond = 1 second)
// Fade speed determines how fast a fade (both in and out) will last.
// Make sure that the gallery does not rotate faster than it can show new pictures!

// 500 millisecond fade in, 500 millisecond fade out... 1 second total fade time.
var fadeSpeed = 500 
// 5 seconds between rotation.
var rotateSpeed = 5000 

// Randomizes an array
// http://sedition.com/perl/javascript-fy.html
function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

gallery = null
galleryDiv = null
visibleDivs = [null, null, null]
nextPictureToShowIndex = 0
nextDivToFillIndex = 0

function run_gallery(the_gallery) {
	gallery = the_gallery
	// Randomize the gallery
	fisherYates(gallery)

	galleryDiv = $("div.gallery_rotate")

	while (visibleDivs[2] == null) {
		runCycle()
	}	

	$.timer(rotateSpeed, runCycle)
}


function getNextPictureGallery() {
	data = gallery[nextPictureToShowIndex]
	nextPictureToShowIndex = (nextPictureToShowIndex + 1) % gallery.length
	return data	
}

function createDiv(imageData) {
	imageHtml = "<img src='" + imageData[0] + "' alt='" + imageData[1] + "' />"
	p1Html = "<p>" + (imageData[3] == "" ? "&nbsp;" : imageData[3]) + "</p>"
	p2Html = "<p>" + imageData[1] + " (" + imageData[2] + ")" + "</p>"
	totalHtml = "<div style='display: none'>" + imageHtml + p1Html + p2Html + "</div>"
	return $(totalHtml)
}

function createNextPictureDom() {
	return createDiv(getNextPictureGallery())
}

function runCycle() {
	if (visibleDivs[nextDivToFillIndex] != null)
	{
		visibleDivs[nextDivToFillIndex].fadeOut(fadeSpeed, replaceWithNext)
	}	
	else
	{
		div = createNextPictureDom()
		visibleDivs[nextDivToFillIndex] = div
		galleryDiv.append(div)	
		nextDivToFillIndex = (nextDivToFillIndex + 1) % visibleDivs.length
		div.fadeIn(fadeSpeed)
	}
}

function replaceWithNext() {
	oldDiv = visibleDivs[nextDivToFillIndex]

	div = createNextPictureDom()
	oldDiv.after(div)

	div.fadeIn(fadeSpeed)
	visibleDivs[nextDivToFillIndex] = div
	nextDivToFillIndex = (nextDivToFillIndex + 1) % visibleDivs.length

	oldDiv.remove()
}
