//Tracks the current slide's index.
currentSlide = 0;

//thumbref is an array containing all of the slide ids. Combined with currentSlide, it allows
//for random access of a slide by the id of its XML counterpart.
thumbRef = new Array();

numSlides = 0;

//Interval timer object for interval tracking.
slideInterval = 0;

//delay in miliseconds.
slideDelay = 6000;

getSlidePath = 'cms/slideshow/getslide';
getThumbsPath = 'cms/slideshow/getthumbs';

addEventHandler( window, 'load', initSlides );

base_url_path = 'http://www.petra.com/';


function addEventHandler( obj, eventName, handler ) {
	if (document.attachEvent) {
		obj.attachEvent("on" + eventName, handler);
	} else if (document.addEventListener) {
		obj.addEventListener(eventName, handler, false);
	}
}

function createRequest() {
	try {
		request = new XMLHttpRequest();
	} catch (tryMS) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (otherMS) {
		try {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (failed) {
			request = null;
		}
			}
	}	
	return request;
}

function initSlides() {

	if (document.body.className.match('cms-index-index') ) {
		//only execute if we're on the index page.

		document.getElementById("prevButton").onclick = prevSlide;
	
		document.getElementById("playbackButton").onclick = togglePlayPause;
	
		document.getElementById("nextButton").onclick = nextSlide;

		var canvas = document.getElementById("slideCanvas");
		canvas.className = "loading";

		getThumbs();
	}

}


function togglePlayPause() {
	var playbackButton = document.getElementById("playbackButton");
	var playbackClasses = playbackButton.className.split(" ");
	if (playbackClasses[1] == 'play') {
		playSlides();
		playbackButton.className = playbackClasses[0] + ' pause';
	} else {
		pauseSlides();
		playbackButton.className = playbackClasses[0] + ' play';
	}
}

function getThumbs() {
	//sets up the asynchronous request to fetch the thumbnails.
	requestThumbs = createRequest();
	if (requestThumbs == null) {
		alert("Unable to create request");
		return;
	}
	selectedClass = this.className;
	var url= getThumbsPath;
	requestThumbs.onreadystatechange = displayThumbs;
	requestThumbs.open("GET", url, true);
	requestThumbs.send(null);
}

function displayThumbs() {
	if (requestThumbs.readyState == 4 ) {
		if (requestThumbs.status == 200 ) {
			var thumbsXML = requestThumbs.responseXML;
			var thumbnails = thumbsXML.getElementsByTagName("thumbnail");
			numSlides = thumbnails.length;
			for (var i = 0; i < numSlides; i++) {
				//Extracts XML for thumbnail data and converts it into XHTML. 
				thumbHTML = document.getElementById("slideThumbs");
				var thumbLi = document.createElement("li");
				thumbLi.setAttribute("class","inactive");
	
				var aNode = document.createElement("a");
				aNode.setAttribute("href", "#");
				aNode.setAttribute("title",thumbnails[i].getAttribute("id"));
				aNode.onclick = getSlide;

				var imgNode = document.createElement("IMG");
				imgNode.setAttribute("src", base_url_path + thumbnails[i].getElementsByTagName("image")[0].firstChild.nodeValue );
				imgNode.setAttribute("border","0");
				aNode.appendChild( imgNode );
	
				var captionTxt = document.createTextNode( thumbnails[i].getElementsByTagName("caption")[0].firstChild.nodeValue );
				var pNode = document.createElement("P");
				pNode.appendChild(captionTxt);

				aNode.appendChild(pNode);
				thumbLi.appendChild( aNode );
				thumbHTML.appendChild( thumbLi );
			
				//this array of thumbnails gives each thumbnail an id. Since it is an array,
				//it can be accessed in sequence allowing for Previous and Next buttons,
				//but because each thumbnail has an id, it can be accessed randomly as well.
				//This gets around the JS limitation of not having associative arrays.
				thumbRef[i] = thumbnails[i].getAttribute("id");
			}
			//Now that the thumbnails have been initialized, we can get our first slide
			//and start playback.
			getSlide();
			playSlides();
		}
	}
}


function playSlides() {
	clearInterval(slideInterval);
	slideInterval = setInterval('nextSlide()', slideDelay);
}
function pauseSlides() {
	clearInterval(slideInterval);
}

function resetSlideInterval() {
	// in case the slides are playing and the user clicks on a button, this resets the counter
	// to prevent confusion.

	var playbackButton = document.getElementById("playbackButton");
	var playbackClasses = playbackButton.className.split(" ");
	if (playbackClasses[1] == 'pause') {
		clearInterval(slideInterval);
		slideInterval = setInterval('nextSlide()', slideDelay);
	}
}

function nextSlide() {
	//gets the next slide, and rotates to the beginning if we're at the end of the list.
	if (currentSlide < numSlides - 1 ) {
		currentSlide++;
	} else {
		currentSlide = 0;
	}
	getSlide();
}

function prevSlide() {
	//gets the previous slide, and rotates to the end if we're at the beginning of the list.
	if (currentSlide > 0 ) {
		currentSlide--;
	} else {
		currentSlide = numSlides - 1;
	}
	getSlide();
}

function getSlide() {
	requestSlide = createRequest();
	if (requestSlide == null) {
		alert("Unable to create request");
		return;
	}

	if ( this.title ) {
		//This checks if the getSlide was called from a thumbnail onclick event instead of a playback button.
		//Since the title of the thumbnail is the id of the splash image, we can use this to check the title.
		var thumbTitle = this.title;
		for (var i=0; i < thumbRef.length; i++) {
		//This finds the slide with the matching title.
			if (thumbRef[i] == thumbTitle) {
				break;
			}
		}
		currentSlide = i;
	}

	var url= getSlidePath;
	var requestData = "slide=" + thumbRef[currentSlide];
	requestSlide.onreadystatechange = displaySlide;
	requestSlide.open("POST", url, true);
	requestSlide.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	requestSlide.send(requestData);
}



function displaySlide() {
	if (requestSlide.readyState == 4) {
		if (requestSlide.status == 200) {
			var slideXML = requestSlide.responseXML;
			var canvas = document.getElementById("slideCanvas");
			if ( canvas.childNodes.length > 0 ) {
				//it's not the first time we're showing this slide, so just modify what's there.
				var aElement = canvas.getElementsByTagName("a")[0];
				aElement.setAttribute("href", slideXML.getElementsByTagName("url")[0].firstChild.nodeValue );

				var imgElement = canvas.getElementsByTagName("img")[0];
				imgElement.setAttribute("src", base_url_path + slideXML.getElementsByTagName("image")[0].firstChild.nodeValue );
			} else {
			// if it's the first time we're showing a slide, we must create the objects first.
				var aNode = document.createElement("a");
				aNode.setAttribute("href", slideXML.getElementsByTagName("url")[0].firstChild.nodeValue );
				var imgNode = document.createElement("IMG");
				imgNode.setAttribute("src", base_url_path + slideXML.getElementsByTagName("image")[0].firstChild.nodeValue );
				imgNode.setAttribute("border","0");
				imgNode.setAttribute("width","540");
				imgNode.setAttribute("height","190");
				aNode.appendChild( imgNode );
				canvas.appendChild(aNode);
			}

			//set all thumbnails to "inactive", then set the selected thumbnail to "active".
			var thumbnails = document.getElementById("slideThumbs").getElementsByTagName("LI");
			for (var i= 0; i < thumbnails.length; i++ ) {
				thumbnails[i].className = 'inactive';
			}
			thumbnails[currentSlide].className = 'active';
			resetSlideInterval();
			canvas.className = "complete";
		}
	}
}