// Define some global variables.
var xhr;
var imageArray = new Array();
var thumbArray = new Array();
var totalImages;
var currentImage = 0;
var imagesPerPage = 5;
var totalPages;
var currentPage = 1;
var pagesHTML = "";
var thumbsHTML = "";
var imageScaled = new Array();
var firstThumb, lastThumb;
var preLoadImage = new Array();
var progressMarker = new Array("images/progress1.png","images/progress2.png","images/progress3.png","images/progress4.png","images/progress5.png","images/progress6.png");
var progressTimer;
var progressCurrent = "0";

// Preload the spining progress animation frames.
if (document.images) {
	for (i=0;i<progressMarker.length;i++) {
		preLoadImage[i] = new Image();
		preLoadImage[i].src = progressMarker[i];
	}
}

function initGallery(url) {
	// This function kicks things off when called from body.onload.
	
	// Set up our XMLHttpRequest object.
	xhr = getxhr();
	if (!xhr) {
		document.getElementById('photos').innerHTML = '<p>This feature is not compatible with your browser.</p><p><a href="http://en.www.mozilla.com/en/firefox/">Try Firefox</a></p>';
		return;
	}
	
	// Add some divs to hold the progress animation.
	var imagePlaceholder = document.createElement("div");
	imagePlaceholder.setAttribute("id","imagePlaceholder");
	document.getElementById('photoContainer').appendChild(imagePlaceholder);
	document.getElementById('imagePlaceholder').innerHTML = '<img src="images/progress1.png" id="imageProgressMarker" />';
	var thumbsPlaceholder = document.createElement("div");
	thumbsPlaceholder.setAttribute("id","thumbsPlaceholder");
	document.getElementById('thumbnailContainer').appendChild(thumbsPlaceholder);
	document.getElementById('thumbsPlaceholder').innerHTML = '<img src="images/progress1.png" id="thumbsProgressMarker" />';
	
	// Start the progress animation clock.
	progressTimer = window.setInterval("makeProgress()",100);
	
	// Hide the image and thumbnail boxes while we load our images & show the progress animation instead.
	removeImage();
	removeThumbs();
	
	// Do some AJAX magic
	xhr.onreadystatechange = stateChanged;
	xhr.open("GET",url,true);
	xhr.send(null);
}

function stateChanged() {
	// Finish initializing.
	
	if (xhr.readyState == 4 && xhr.status==200) {
		
		// Process our XML file containing the image URLs.
		var xmlDoc = xhr.responseXML.documentElement;
		for (i=0;i<xmlDoc.getElementsByTagName('image').length;i++) {
			imageArray[i] = xmlDoc.getElementsByTagName('image')[i].childNodes[0].nodeValue;
		}
		for (i=0;i<xmlDoc.getElementsByTagName('thumb').length;i++) {
			thumbArray[i] = xmlDoc.getElementsByTagName('thumb')[i].childNodes[0].nodeValue;
		}
		
		// Fill in some basic global variables.
		totalImages = imageArray.length
		totalPages = Math.ceil(totalImages / imagesPerPage);
		
		// Set up our gallery.
		drawPages();
		setThumbs();
		setImage();
	}
}

function makeProgress() {
	document.getElementById('imageProgressMarker').src = progressMarker[progressCurrent];
	document.getElementById('thumbsProgressMarker').src = progressMarker[progressCurrent];
	progressCurrent++;
	if (progressCurrent >= progressMarker.length) {
		progressCurrent = 0;
	}
}

function drawPages() {
	pagesHTML = "";
	for (i=1;i<=totalPages;i++) {
		if (i == currentPage) {
			pagesHTML += '<img src="images/pageCircle_solid.png" />';
		} else {
			pagesHTML += '<img src="images/pageCircle_open.png" />';
		}
	}
	document.getElementById('pages').innerHTML = pagesHTML;
}

function removeImage() {
	document.getElementById('photos').style.visibility = "hidden";
	document.getElementById('imagePlaceholder').style.visibility = "visible";
}

function setImage() {
	var imgId = "image" + currentImage;
	document.getElementById('photos').innerHTML = '<img src="' + imageArray[currentImage] + '" id="' + imgId + '" />';
	imageScaled[999] = false;
	scaleImage(imgId,500,400,999);
	showImage();
}

function showImage() {
	if (imageScaled[999]) {
		document.getElementById('photos').style.visibility = "visible";
		document.getElementById('imagePlaceholder').style.visibility = "hidden";
	} else {
		window.setTimeout("showImage()",500);
	}
}

function scaleImage(imgId, maxWidth, maxHeight, id) {
	if (imageComplete(imgId)) {
		var imgWidth = document.getElementById(imgId).width;
		var imgHeight = document.getElementById(imgId).height;
		if ((imgWidth / imgHeight) > (maxWidth / maxHeight)) {
			document.getElementById(imgId).style.width = maxWidth + 'px';
			var imgMargin = (maxHeight - document.getElementById(imgId).height) / 2;
			document.getElementById(imgId).style.marginTop = imgMargin + 'px';
		} else {
			document.getElementById(imgId).style.height = maxHeight + 'px';
		}
		imageScaled[id] = true;
	} else {
		var sendFunction = "scaleImage('" + imgId + "'," + maxWidth + "," + maxHeight + "," + id + ")";
		setTimeout(sendFunction,250);
	}
}

function imageComplete(imgId) {
	// This function checks to see if the image is finished loading... or at least that we know its dimensions.
	// Safari & W3C do not support ImageObject.complete. Instead we can check for a width property and see if it is greater than 0.
	// However, IE seems to report a defined, non-zero width before the image is finished loading, so we need to use ImageObject.complete at least for IE. 
	if (document.getElementById(imgId) && document.getElementById(imgId).complete) {
		return true;
	} else if (document.getElementById(imgId) && !(document.getElementById(imgId).complete == true) && !(document.getElementById(imgId).complete == false) && document.getElementById(imgId).width && document.getElementById(imgId).width > 0) {
		return true;
	} else {
		return false;
	}
}

function calculateThumbs(page) {
	// Determine the thumbnails that are on the specified page.
	firstThumb = (page - 1) * imagesPerPage;
	lastThumb = (page * imagesPerPage) - 1;
	if (lastThumb > (totalImages - 1)) {
		lastThumb = totalImages - 1;
	}
}

function removeThumbs() {
	document.getElementById('thumbnails').style.visibility = "hidden";
	document.getElementById('thumbsPlaceholder').style.visibility = "visible";	
}

function setThumbs() {
	thumbsHTML = "";
	calculateThumbs(currentPage);
	for (i=firstThumb;i<=lastThumb;i++) {
		var imgId = "thumb" + i;
		thumbsHTML += '<a href="#" class="thumb" onclick="return gotoImage(' + i + ');"><img src="' + thumbArray[i] + '" id="' + imgId + '" /></a>';
	}
	document.getElementById('thumbnails').innerHTML = thumbsHTML;
	for (i=firstThumb;i<=lastThumb;i++) {
		var imgId = "thumb" + i;
		imageScaled[i] = false;
		scaleImage(imgId,100,100,i);
	}
	showThumbs();
}

function showThumbs() {
	if (checkThumbs()) {
		document.getElementById('thumbnails').style.visibility = "visible";
		document.getElementById('thumbsPlaceholder').style.visibility = "hidden";
	} else {
		setTimeout("showThumbs()",250);
	}
}

function checkThumbs() {
	// Check to see if all the active thumbs are loaded.
	calculateThumbs(currentPage);
	for (i=firstThumb;i<=lastThumb;i++) {
		if (!imageScaled[i]) {
			return false;
		}
	}
	return true
}

function gotoImage (x) {
	if (isFinite(x)) {
		removeImage();
		currentImage = x;
		setImage();
	} 
	return false;
}

function changeImage(x) {
	if (isFinite(x)) {
		removeImage();
		currentImage += x;
		if (currentImage >= totalImages)
		{
			currentImage = 0;
		} else if (currentImage < 0) {
			currentImage = totalImages - 1;
		}
		setImage();
		checkPage();
	}
	return false;
}

function changePage(x) {
	if (isFinite(x)) {
		removeThumbs();
		currentPage += x;
		if (currentPage > totalPages) {
			currentPage = 1;
		} else if (currentPage < 1) {
			currentPage = totalPages;
		}
		drawPages();
		setThumbs();
	}
	return false;
}

function checkPage() {
	// If the current image is not on the current page of thumbs, load the appropriate page of thumbs.
	calculateThumbs(currentPage);
	if (currentImage < firstThumb || currentImage > lastThumb) {
		for (i=1;i<=totalPages;i++) {
			calculateThumbs(i);
			if (currentImage >= firstThumb && currentImage <= lastThumb) {
				currentPage = i;
				break;
			}
		}
		removeThumbs();
		drawPages();
		setThumbs();
	}
}
