/***********************************************************************************************\
*	thumbscroller.js
*	created: 1/6/07 by Darren Smith
*
*	purpose: create a horozontally scrolling thumbnail navigator with an XML input
*
*	usage:
*	Set arrowPath variable to the path where left.gif and right.gif are located.  These images 
*	may be replaced, but the dimensions of the images must remain the same.  
*
*	Create and style the "stage" div where full-size images will be displayed.  Set the name of this
*	div in the stageDiv variable.
*
*	Create and style the "details" div where title, date, description, and details will be displayed.
*	Set the name of this div in the detailsDiv variable.
*
*	Create and style a container div for the thumbnails (including borders, background, width,
*	height, position, etc).  Call initThumbscroller() passing it the ID of the div and
*	the path to the XML file, like so: 
*	<body onLoad="initThumbscroller('scroller', '/_data/getPics.php');">
*
*	picture info XML should be in the following format:
*	<container_node>
*		<pic>
*			<filename>image.jpg</filename>
*			<title><![CDATA[ title ]]></title>
*			<description><![CDATA[ description ]]></description>
*			<date>date</date>
*			<details><![CDATA[ details ]]></details>
*			<category><![CDATA[ category ]]></category>
*		</pic>
*		...
*	</container_node>
*
*	Create an XML document of options.  These decide whether to display the date, description and 
*	detials of the photos.  This should be a 0 or 1.  Set the path to this file in the optionsPath
*	variable.  Format like so:
*	<settings>
*		<date>[0|1]</date>
*		<description>[0|1]</description>
*		<details>[0|1]</details>
*	</settings>
*
\***********************************************************************************************/

var arrowPath = "images/";
var detailsDiv = "details";
var stageDiv = "mainImage";
var optionsPath = "_data/getGalleryOptions.php";

var showGalleryDate;
var showGalleryDescription;
var showGalleryDetails;

var scrollContainer;
var scrollInterval;
var scrollerWidthInterval;
var leftArrowContainer;
var rightArrowContainer;
var thumbsWidth = 0;
var scrollRate = 10;
if(isIE()){
	scrollRate = 5;
}
var currentMargin;
var arrowOffset = 4;
var loadedCount = 0;
var picCount;
var picsXML;

var objDivReceived;
var urlReceived;

function initThumbscroller(objDiv, url){
	objDivReceived = objDiv;
	urlReceived = url;
	loadXMLData(optionsPath, "saveSettings");
}

function saveSettings(){
	settingsXML = xmlData;
	showGalleryDate = Number(settingsXML.firstChild.childNodes[0].firstChild.nodeValue);
	showGalleryDescription = Number(settingsXML.firstChild.childNodes[1].firstChild.nodeValue);
	showGalleryDetails = Number(settingsXML.firstChild.childNodes[2].firstChild.nodeValue);
	loadThumbData();
}

function loadThumbData(){
	thumbsWidth = 0;
	currentMargin = 0;
	if(document.getElementById(objDivReceived)){
		scrollContainer = document.getElementById(objDivReceived);
		scrollContainer.innerHTML = "";
		scrollContainer.style.overflow = "hidden";
		loadXMLData(urlReceived, "loadThumbs");
	}
}

function loadThumbs(){
	picsXML = xmlData;
	var arrImages = new Array();
	loadedCount = 0;
	
	var picHeight = elemHeight(scrollContainer.getAttribute("id")) - 10;
	
	var thumbscroller = window.document.createElement("div");
	thumbscroller.setAttribute("id", "thumbscroller");
	scrollContainer.appendChild(thumbscroller);
	
	if(!document.getElementById("thumbsWidthDiv")){
		var thumbsWidthDiv = window.document.createElement("div");
		thumbsWidthDiv.setAttribute("id", "thumbsWidthDiv");
		document.body.appendChild(thumbsWidthDiv);
		thumbsWidthDiv.style.position = "absolute";
		thumbsWidthDiv.style.left = "-10000px";
		thumbsWidthDiv.style.top = "-" + (picHeight*3) + "px";
	} else {
		var thumbsWidthDiv = document.getElementById("thumbsWidthDiv");
		thumbsWidthDiv.innerHTML = "";
	}
	picCount = picsXML.firstChild.childNodes.length;
	var strThumbs = '<table id="thumbTable"><tr>';
	for(var i = 0; i < picCount; ++i){
		strThumbs += '<td>';
		strThumbs += '<a href="#" onClick="loadImage(' + i + '); return false;">'; 
		strThumbs += '<img src="photos/' + picsXML.firstChild.childNodes[i].firstChild.firstChild.nodeValue + '"';
		strThumbs += 'style="height: ' + picHeight + 'px; margin: 1px 2px 1px 2px; border: 1px solid #000;" alt="thumbnail image" />';
		strThumbs += '</a>';
		strThumbs += '</td>';
		arrImages[i] = document.createElement('img');
		arrImages[i].onLoad = thumbLoaded();
		arrImages[i].src = 'photos/' + picsXML.firstChild.childNodes[i].firstChild.firstChild.nodeValue;
		
	}
	strThumbs += '</tr></table>';
	thumbscroller.innerHTML = strThumbs;
	thumbsWidthDiv.innerHTML = strThumbs;
	if(picCount == 0){
		clearScroll();
		thumbscroller.innerHTML = '<h1 style="text-align: center; margin-top: 20px; color: #666; font-style: italic; font-size: 24px;">No pictures were found in this category.</h1>';
	} else {
		loadFirstImage();
		scrollerWidthInterval = setInterval("checkSettings()", 500);
		setScroll();
	}
}

function thumbLoaded(){
	++loadedCount;
	if(loadedCount >= picCount + 2){
		allThumbsLoaded();
	}
}

function allThumbsLoaded(){
	var arrowHeight = elemHeight(scrollContainer.getAttribute("id"));
	currentMargin = Math.round(arrowHeight*(282/232));
	document.getElementById("thumbscroller").style.marginLeft = currentMargin + "px";
}

function setScroll(){
	var arrowHeight = elemHeight(scrollContainer.getAttribute("id")) + "px";
	
	if(!document.getElementById("leftArrowContainer")){
		leftArrowContainer = window.document.createElement("div");
		leftArrowContainer.setAttribute("id", "leftArrowContainer");
		document.body.appendChild(leftArrowContainer);
	}
	leftArrowContainer.innerHTML = "";
	
	leftArrowContainer.style.position = "absolute";
	leftArrowContainer.style.top = (findTop(scrollContainer) + arrowOffset) + "px";
	leftArrowContainer.style.left = (findLeft(scrollContainer) + 3) + "px";
	leftArrowContainer.style.height = arrowHeight;
	
	var ieStyle = "";
	if(isIE()){
		var ieStyle = "filter:alpha(opacity=50); opacity: .5; -moz-opacity: .5; ";
	}
	
	leftArrowHTML = '<a href="#" onMouseOver="scrollThumbs(0);" onMouseOut="stopScroll();" onClick="return false;" style="filter:alpha(opacity=50); opacity: .5; -moz-opacity: .5;">';
	leftArrowHTML += '<img id="leftArrowImg" style="' + ieStyle + 'border: none; height: ' + arrowHeight + ';" src="' + arrowPath + 'left.gif" alt="&laquo;" />';
	leftArrowHTML += '</a>';
	leftArrowContainer.innerHTML = leftArrowHTML;
	
	if(!document.getElementById("rightArrowContainer")){
		rightArrowContainer = window.document.createElement("div");
		rightArrowContainer.setAttribute("id", "rightArrowContainer");
		document.body.appendChild(rightArrowContainer);
	}
	rightArrowContainer.innerHTML = "";
	
	rightArrowContainer.style.position = "absolute";
	rightArrowContainer.style.top = (findTop(scrollContainer) + arrowOffset) + "px";
	var rightArrowX = findLeft(scrollContainer) - elemWidth("leftArrowImg") + elemWidth(scrollContainer.getAttribute("id")) + 6;
	rightArrowContainer.style.left = rightArrowX + "px";
	rightArrowContainer.style.height = arrowHeight;
	
	rightArrowHTML = '<a href="#" onMouseOver="scrollThumbs(1);" onMouseOut="stopScroll();" onClick="return false;" style="filter:alpha(opacity=50); opacity: .5; -moz-opacity: .5;">';
	rightArrowHTML += '<img style="' + ieStyle + 'border: none; height: ' + arrowHeight + ';" src="' + arrowPath + 'right.gif" alt="&raquo;" />';
	rightArrowHTML += '</a>';
	rightArrowContainer.innerHTML = rightArrowHTML;
	
	var left = document.createElement('img');
	var right = document.createElement('img');
	left.onLoad = thumbLoaded();
	right.onLoad = thumbLoaded();
	left.src = 'images/left.gif';
	right.src = 'images/right.gif';
}

function clearScroll(){
	clearInterval(scrollInterval);
	clearInterval(scrollerWidthInterval);
	if(!document.getElementById("leftArrowContainer")){
		leftArrowContainer = window.document.createElement("div");
		leftArrowContainer.setAttribute("id", "leftArrowContainer");
		document.body.appendChild(leftArrowContainer);
	}
	leftArrowContainer.innerHTML = "";
	
	if(!document.getElementById("rightArrowContainer")){
		rightArrowContainer = window.document.createElement("div");
		rightArrowContainer.setAttribute("id", "rightArrowContainer");
		document.body.appendChild(rightArrowContainer);
	}
	rightArrowContainer.innerHTML = "";
}

function scrollThumbs(dir){
	clearInterval(scrollInterval);
	if(elemWidth("thumbsWidthDiv") > (elemWidth(scrollContainer.getAttribute("id")) - elemWidth("leftArrowImg"))){
		scrollInterval = setInterval("scrollAction(" + dir + ")", 1);
	}
}
function scrollAction(dir){
	var end = 0;
	var arrowWidth = elemWidth("leftArrowImg");
	if(dir == "0"){
		currentMargin += scrollRate;
		if(currentMargin > arrowWidth){
			currentMargin = arrowWidth;
			end = 1;
		}
	} else {
		var scrollLimit = 0 - thumbsWidth + elemWidth(scrollContainer.getAttribute("id")) - elemWidth("leftArrowImg");
		currentMargin -= scrollRate;
		if(currentMargin < scrollLimit){
			currentMargin = scrollLimit;
			end = 1;
		}
	}
	document.getElementById("thumbscroller").style.marginLeft = currentMargin + "px";
	if(end == 1){
		clearInterval(scrollInterval);
	}
}
function stopScroll(){
		clearInterval(scrollInterval);
}

function checkSettings(){
	thumbsWidth = elemWidth("thumbsWidthDiv");
	leftArrowContainer.style.left = (findLeft(scrollContainer) + 3) + "px";
	var rightArrowX = findLeft(scrollContainer) - elemWidth("leftArrowImg") + elemWidth(scrollContainer.getAttribute("id")) + 6;
	rightArrowContainer.style.left = rightArrowX + "px";
	
	var top = (findTop(scrollContainer) + arrowOffset) + "px";
	document.getElementById("leftArrowContainer").style.top = top;
	document.getElementById("rightArrowContainer").style.top = top;
}

function loadImage(imgIndex){
	var img = picsXML.firstChild.childNodes[imgIndex].firstChild.firstChild.nodeValue;
	
	resizeImage("photos/" + img, stageDiv, "", 800, 600);
	
	//var imgDiv = document.getElementById(stageDiv);
	//imgDiv.innerHTML = '<img src="/photos/' + img + '" width="800" />';
	
	var top = (findTop(scrollContainer) + arrowOffset) + "px";
	document.getElementById("leftArrowContainer").style.top = top;
	document.getElementById("rightArrowContainer").style.top = top;
	loadDetails(imgIndex);
}

function finishLoadingImage(){
}

function loadFirstImage(){
	var img = picsXML.firstChild.childNodes[0].firstChild.firstChild.nodeValue;
	
	resizeImage("photos/" + img, stageDiv, "", 800, 600);
	
	//var imgDiv = document.getElementById(stageDiv);
	//imgDiv.innerHTML = '<img src="/photos/' + img + '" width="800" />';

	var mainImg = document.createElement('img');
	mainImg.onLoad = function(){
		var top = (findTop(scrollContainer) + arrowOffset) + "px";
		document.getElementById("leftArrowContainer").style.top = top;
		document.getElementById("rightArrowContainer").style.top = top;
	}
	mainImg.src = 'photos/' + img;
	loadDetails(0);
}

function loadDetails(imgIndex){
	var details = document.getElementById(detailsDiv);
	var detailsContent = "<h3>About this Photograph</h3>";
	detailsContent += "<br /><strong>Title:</strong><br />";
	detailsContent += picsXML.firstChild.childNodes[imgIndex].childNodes[1].firstChild.nodeValue;
	if((showGalleryDate == 1) && (picsXML.firstChild.childNodes[imgIndex].childNodes[3].firstChild.nodeValue != "none")){
		detailsContent += "<br /><br /><strong>Date:</strong><br />";
		detailsContent += picsXML.firstChild.childNodes[imgIndex].childNodes[3].firstChild.nodeValue;
	}
	if((showGalleryDescription == 1) && (picsXML.firstChild.childNodes[imgIndex].childNodes[2].firstChild.nodeValue != "<p></p>")){
		detailsContent += "<br /><br /><strong>Description:</strong><br />";
		detailsContent += picsXML.firstChild.childNodes[imgIndex].childNodes[2].firstChild.nodeValue;
	} else {
		detailsContent += "<br /><br />";
	}
	if((showGalleryDetails == 1) && (picsXML.firstChild.childNodes[imgIndex].childNodes[4].firstChild.nodeValue != "<p></p>")){
		detailsContent += "<strong>Details:</strong><br />";
		detailsContent += picsXML.firstChild.childNodes[imgIndex].childNodes[4].firstChild.nodeValue;
	}
	details.innerHTML = detailsContent;
}

function findLeft(obj) {
	var objX = 0;
	if (obj.offsetParent) {
		objX = obj.offsetLeft;
		while (obj = obj.offsetParent) {
			objX += obj.offsetLeft;
		}
	}
	return objX;
}
function findTop(obj) {
	var objY = 0;
	if (obj.offsetParent) {
		objY = obj.offsetTop;
		while (obj = obj.offsetParent) {
			objY += obj.offsetTop;
		}
	}
	return objY;
}
//functions to determine width and height of HTML elements
function elemHeight(elmID){
	var objElement = document.getElementById(elmID);
	if(objElement.clientHeight){
		return objElement.clientHeight;
	} else {
		if(objElement.offsetHeight){
			return objElement.offsetHeight;
		}
	}
}
function elemWidth(elmID){
	var objElement = document.getElementById(elmID);
	if(objElement.clientWidth){
		return objElement.clientWidth;
	} else {
		if(objElement.offsetWidth){
			return objElement.offsetWidth;
		}
	}
}
function isIE(){
	if (navigator.appName == "Microsoft Internet Explorer"){
		return true;
	} else {
		return false;
	}
}

/***********************************************\
*	resise functions below
\***********************************************/
//global vars
var workingImagePath;
var maxWidth;
var maxHeight;
var destinationDivID;
var alt;
var newWidth;
var newHeight;
var garbageVar;

//pass image path, target div, alt text, max width, and max height to function
function resizeImage(image, containerDivID, altText, width, height){
	workingImagePath = image;
	destinationDivID = containerDivID;
	alt = altText;
	maxWidth = width;
	maxHeight = height;
	setLoadingMsg();
}

//set loading message
function setLoadingMsg(){
	var objDestination = document.getElementById(destinationDivID);
	objDestination.style.width = maxWidth + "px";
	objDestination.style.height = maxHeight + "px";
	objDestination.style.textAlign = "center";
	objDestination.style.fontSize = "10px";
	objDestination.innerHTML = "Loading Image...";
	createTempDiv();
}

//create a hidden workspace
function createTempDiv(){
	var tempImageDiv = window.document.createElement("div");
	tempImageDiv.setAttribute("id", "tempImageDiv");
	window.document.body.appendChild(tempImageDiv);
	var objTempDiv = document.getElementById("tempImageDiv");
	objTempDiv.style.width = "1px";
	objTempDiv.style.height = "1px";
	objTempDiv.style.overflow = "hidden";
	objTempDiv.style.marginLeft = "-1000px";
	loadTempImage();
}

//load image into workspace
function loadTempImage(){
	//avoid cache problems with garbage variable
	garbageVar = new Date();
	document.getElementById("tempImageDiv").innerHTML = '<img src="' + workingImagePath + '?blah=' + garbageVar + '" id="tempImage" onLoad="setTempDimensions()" />';
}

//resize temp image to desired dimensions
function setTempDimensions(){
	var objTempImg = document.getElementById("tempImage");
	//get current dimensions
	var currentWidth = elemWidth("tempImage");
	var currentHeight = elemHeight("tempImage");
	//set width
	if(currentWidth > maxWidth){
		objTempImg.style.width = maxWidth + "px";
		//maintain aspect ratio
		objTempImg.style.height = (currentHeight*(maxWidth/currentWidth)) + "px";
	}
	//get current dimensions
	currentWidth = elemWidth("tempImage");
	currentHeight = elemHeight("tempImage");
	//set height
	if(currentHeight > maxHeight){
		objTempImg.style.height = maxHeight + "px";
		//maintain aspect ratio
		objTempImg.style.width = (currentWidth*(maxHeight/currentHeight)) + "px";
	}
	
	//get current dimensions
	currentWidth = elemWidth("tempImage");
	currentHeight = elemHeight("tempImage");
	if((currentWidth < maxWidth) && (currentHeight < maxHeight)){
		if((currentWidth - (maxWidth - maxHeight)) > (currentHeight)){
			objTempImg.style.width = "800px";
			objTempImg.style.height = (currentHeight*(maxWidth/currentWidth)) + "px";
		} else {
			objTempImg.style.height = "600px";
			objTempImg.style.width = (currentWidth*(maxHeight/currentHeight)) + "px";
		}
	}
	
	//record final dimensions
	newWidth = elemWidth("tempImage");
	newHeight = elemHeight("tempImage");
	loadFinalImage();
}

//load image into final position with adjusted dimensions
function loadFinalImage(){
	//use same garbage var so that cached version can be used
	var newImageSource = '<img src="' + workingImagePath + '?blah=' + garbageVar + '" style="width: ' + newWidth + 'px; height: ' + newHeight + 'px;" alt="' + alt + '" />'; 
	document.getElementById(destinationDivID).innerHTML = newImageSource;
	removeTempDiv();
}

//clean up
function removeTempDiv(){
	var elementToRemove = document.getElementById("tempImageDiv");
    elementToRemove.parentNode.removeChild(elementToRemove);
}