/*---------------------------------------
	Initial Global Variables
---------------------------------------*/

var t = '';
var playGallery = "yes";

var showClass = "show";
var hideClass = "hide";

var thumbsID = "thumbnails";
var thumbHighlightClass = 'thumbHighlight';

var galleryID = "gallery";
var galleryElem = "div";
var galleryLength = '';


var nextImage = '';
var thisImage = '';
var isAnimating = 'false';
var currentItem = '';

var rotationLength = '8000';

var thumbDetails = new Array();
var descriptionArray = new Array();
var elems = new Array();
/*------------------------------------------------------------
initGallery()
	
Called from setup.js addLoadListener() function.
	
As an accessibility feature, initGallery() applies a master class to gallery by which all other styles are controlled.  Therefore, if JavaScript is not loaded, CSS can still render, but none of the font coloring, absolute positioning, etc. are used, allowing for a clean and ordered view of the content.

If JavaScript is loaded, initGallery() loops over the main gallery container, looking for elements with a class equal to galleryElem (set in global vars).  Then, "show" and "hide" classes are applied to each gallery element.  This is another accessibility feature.  If JavaScript is not loaded, the "show" and "hide" CSS classes will not be applied to the gallery elements, allowing all content in the gallery to render visible.

After classes are applied, the createLinks() function is called to initialize the gallery controls.

Finally, the gallery timer function autoPlay() is called to begin the timed rotation of content.
------------------------------------------------------------*/

function initGallery() {
    if (!Spry.$(galleryID)) {
        return;
    }
	var galleryCol = getElementsByClass('newsitem');
	galleryLength = galleryCol.length;
	for(i=0;i<galleryLength;i++) {
		// Start by finding the currently highlighted div (image, text, etc)
		if(i==0) {
			Spry.Utils.addClassName(galleryCol[i], showClass);
		}
		else {
			Spry.Utils.addClassName(galleryCol[i], hideClass);
		}
	}

	/*var thumbCol = Spry.$(thumbsID).getElementsByTagName('img');
	for(i=0;i<thumbCol.length;i++) {
		Spry.Utils.addEventListener(thumbCol[i],'click',startGallery,false);
		if(splitString(thumbCol[i].id,1) ==0) {
			Spry.Utils.addClassName(thumbCol[i],thumbHighlightClass);
			currentItem = thumbCol[i];
		}
	}*/
	
	var control = Spry.$('control');
	Spry.Utils.addEventListener(control,'click',setControl,false);
	
	loadContent();
}

function loadContent() {
	setTimeout('startSlideShow()',2200);	
}

function startSlideShow() {
	var loading = Spry.$('loading');
	var pictures = Spry.$('pictureframe');
	loading.parentNode.removeChild(loading);
	pictures.style.display='block';
	showDescription()
}

function splitString(ele,pos) {
	var stringArray = ele.split('-');
	return stringArray[pos];
}


/*------------------------------------------------------------
getElementsByClass()

Called from multiple functions

A simply utility that grabs and returns an array of elements (here, only div's) that have a class equal to or containing the value passed to the function.
------------------------------------------------------------*/
function getElementsByClass(className) {
	var collection = Spry.$(galleryID).getElementsByTagName('div');
	var counter = 0;
	for(i=0;i<collection.length;i++) {
		if(collection[i].className.match(className)) {
			elems[counter] = collection[i];
			counter++;
		}
	}
	return elems;
}

/*------------------------------------------------------------
removeEventListeners()

Called from startGallery()

In order to prevent users from creating multiple instances of the startGallery() function (by clicking repeatedly or before the function is done running), the event listeners on the thumbnails are removed, thus preventing the function from being called again until event listeners are added back
------------------------------------------------------------*/
function removeEventListeners() {
	/*var thumbCol = Spry.$(thumbsID).getElementsByTagName('img');
	for(i=0;i<thumbCol.length;i++) {
		Spry.Utils.removeEventListener(thumbCol[i],'click',startGallery,false);
	}	*/
	var control = Spry.$('control');
	Spry.Utils.removeEventListener(control,'click',setControl,false);
}
/*------------------------------------------------------------
addEventListeners()

Called from autoPlay()

autoPlay() is always called after all animation and effects functions are done running, so this is the ideal time to add the event listeners back to the thumbnails without creating a flickering problem.
------------------------------------------------------------*/
function addEventListeners() {
	/*var thumbCol = Spry.$(thumbsID).getElementsByTagName('img');
	for(i=0;i<thumbCol.length;i++) {
		Spry.Utils.addEventListener(thumbCol[i],'click',startGallery,false);
	}	*/
	var control = Spry.$('control');
	Spry.Utils.addEventListener(control,'click',setControl,false);
}

/*------------------------------------------------------------
autoPlay()

Called from initGallery(), startGallery()

A simple function, autoPlay() simply creates a Timeout event and calls the startGallery() function after the specified interval.
------------------------------------------------------------*/
function autoPlay() {
	
	isAnimating='false';
	addEventListeners();
	if(playGallery=="yes") {
		t=setTimeout('startGallery()',rotationLength);
	}
}

/*------------------------------------------------------------
stopGallery()

Called from startGallery()

stopGallery() merely clears the Timer object created by autoPlay().  This is necessary, because if the timeout is not cleared every time the gallery advances, an additional timer is created, and chaos ensues.
------------------------------------------------------------*/
function stopGallery() {
	clearTimeout(t);	
}

/*------------------------------------------------------------
setControl()

Called from initGallery()

setGallery() determines whether the gallery autoPlay() should be enacted and alters the control text
------------------------------------------------------------*/
function setControl() {
	var control = Spry.$('control');
	
	if(playGallery=="no") {
		playGallery = "yes";
		control.innerHTML = 'Pause';
		startGallery();
		return null;
	}
	if(playGallery=="yes") {
		playGallery = "no";
		control.innerHTML = 'Play';
		stopGallery();
		return null;
	}
}

/*------------------------------------------------------------
startGallery()

Called from autoPlay() and links created from createLinks()

This function is really the heart of the gallery, and therefore has the most amount of code.  A good bit of it, however, is simply logic which checks to see whether a gallery action taken is from an arrow or paging click.

The highlight of this function is the Effect Cluster which is applied.  The Effect Cluster allows the fade in and fade out effects on the changing images to happen simultaneously.
------------------------------------------------------------*/

function startGallery() {
	// Kill the timer object that just finished; we don't want several timers running at the same time...
	// It's not pretty when that happens, unless you can read REALLY REALLY fast :)
	stopGallery();
	removeEventListeners();
	
	if(this.id) {
		var next = splitString(this.id,1);	
	}
	else {
		var next = '';
	}
	
	/*getCurrentThumbnail(next);*/	
	
	// If there is an animation in process, OR the clicked thumbnail is the current "active" one, ignore the additional startGallery() call and just let the timer run (if enabled)
	if(isAnimating=='true' ) {
		autoPlay();
		return null;
	}
	if(this.id) {
		nextImage = splitString(this.id,1);
	}
	else {
		var str = 	getCurrentItem().current.id;
		var id 	=	splitString(str,1);
		if(Math.floor(id*10/10+1)<elems.length) {
			nextImage=Math.floor(id*10/10+1);
		}
		if(Math.floor(id*10/10+1)==elems.length) {
			nextImage = 0;
		}		
	}

	// Set isAnimating to true so that multiple instances of startGallery() cannot be called
	isAnimating='true';
	hideDescription();		
}

/*------------------------------------------------------------
getCurrentThumbnail()

Called from startGallery()

This function determines the current and "next" thumbnail in the widget.  If "next" is defined, a specific, non-order specific thumbnail is passed to the "next" node of the returned array; otherwise, the function assumes a synchronous order of thumbnails.
------------------------------------------------------------*/
function getCurrentThumbnail(next) {
	var thumbCol = Spry.$(thumbsID).getElementsByTagName('img');
	for(i=0;i<thumbCol.length;i++) {
		if(thumbCol[i].className == thumbHighlightClass) {
			thumbDetails.current = thumbCol[i];
			break;
		}
	}
	if(!next) {
		if((Math.floor(splitString(thumbDetails.current.id,1))+1) == thumbCol.length) {
			thumbDetails.next = thumbCol[0];
		}
		else {
			var nextID = (Math.floor(splitString(thumbDetails.current.id,1))+1);
			thumbDetails.next = thumbCol[nextID];
		}
		
	}
	else {
		thumbDetails.next = thumbCol[next];	
	}
	return thumbDetails;
}

/*------------------------------------------------------------
getNextItem()

Called from multiple functions

This function determines which "item" is next in succession (e.g., ready to be animated).  It returns an array of the current item container, and the image container.
------------------------------------------------------------*/
function getNextItem(num) {
	var galleryCol = getElementsByClass('newsitem');
	var nextArray = new Array();
	for(i=0;i<galleryCol.length;i++) {
		// Start by finding the currently highlighted div (image, text, etc)
		if(i==num) {
			var children = galleryCol[i].childNodes;
			for(x=0;x<children.length;x++) {
				if(children[x].className=='image') {
					nextArray.image = children[x];
				}
			}
			nextArray.current = galleryCol[i];
			return nextArray;
		}
	}
}

/*------------------------------------------------------------
getCurrentItem()

Called from multiple functions

This function determines which "item" is currently highlighted.  It returns an array of the current item container, the image container, the description container and the description text.
------------------------------------------------------------*/
function getCurrentItem() {
	var galleryCol = getElementsByClass('newsitem');
	for(i=0;i<galleryCol.length;i++) {
		// Start by finding the currently highlighted div (image, text, etc)
		if(galleryCol[i].className.match(showClass)) {			
			descriptionArray.current = galleryCol[i];
			var children = galleryCol[i].childNodes;
			for(x=0;x<children.length;x++) {
				if(children[x].className=='image') {
					descriptionArray.image = children[x];
				}
				if(children[x].className == 'description') {
					descriptionArray.outer = children[x];
					var grandChildren = children[x].childNodes;
					for(y=0;y<grandChildren.length;y++) {
						if(grandChildren[y].className == 'description-inner') {
							descriptionArray.inner = grandChildren[y];	
						}
					}
				}
				
			}
			return descriptionArray;
		}
	}
}

/*------------------------------------------------------------
hideDescription()

Called from startGallery()

This function simply animates the description container and text to the "hidden" position
------------------------------------------------------------*/
function hideDescription() {
	var description = getCurrentItem();
	var slideOut = new Spry.Effect.Slide(description.outer, {duration:300, from:'100%', to:'0%', toggle:false, finish:hideCurrentImage});
	slideOut.start();
}

/*------------------------------------------------------------
hideCurrentImage()

Called from hideDescription()

This function simply animates the image container to the "hidden" state
------------------------------------------------------------*/
function hideCurrentImage() {
	var description = getCurrentItem();
	description.outer.style.height = 'auto';
	description.outer.style.visibility = 'hidden';
	description.inner.style.top = '0';
	/*var thisItem = getCurrentItem();*/
	var fadeOut = new Spry.Effect.Fade(description.current, {duration: 500, from: 100, to: 0, finish:showNextImage, toggle:false});
	fadeOut.start();
	
	/*Spry.Utils.addClassName(thumbDetails.next,thumbHighlightClass);
	Spry.Utils.removeClassName(thumbDetails.current,thumbHighlightClass);
	currentItem = thumbDetails.next;*/
}

/*------------------------------------------------------------
showCurrentImage()

Called from hideCurrentImage()

This function simply animates the "next" image container to the "show" state
------------------------------------------------------------*/
function showNextImage() {
	var thisItem = getCurrentItem();
	Spry.Utils.removeClassName(thisItem.current,showClass);
	Spry.Utils.addClassName(thisItem.current,hideClass);
	thisItem.current.style.zIndex = 0;
	var nextItem = getNextItem(nextImage);
	nextItem.current.style.zIndex=1000;
	var fadeIn = new Spry.Effect.Fade(nextItem.current, {duration: 500, from: 0, to: 100, finish:showDescription, toggle:false});	
	fadeIn.start();
	Spry.Utils.addClassName(nextItem.current,showClass);
	
	
}

/*------------------------------------------------------------
showDescription()

Called from showNextImage()

This function simply animates the description container and text to the "show" position
------------------------------------------------------------*/
function showDescription() {
	var thisItem = getCurrentItem();
	Spry.Utils.removeClassName(thisItem.current,hideClass);
	if(/MSIE/.test(navigator.userAgent)&&(!thisItem.outer.hasLayout)) {
		height = Spry.Effect.getDimensionsRegardlessOfDisplayState(thisItem.outer).height + 5;
		thisItem.current.style.filter = '';
		thisItem.outer.style.filter = 'alpha(opacity=70)';
	}
	else {
		height = Spry.Effect.getDimensionsRegardlessOfDisplayState(thisItem.outer).height;
	}
	var slideIn = new Spry.Effect.Slide(thisItem.outer, {duration:300, from:'0%', to: height, toggle:true, finish:autoPlay});
	slideIn.start();
}
