// Based on http://www.webmonkey.com/tutorial/Make_a_JavaScript_Slideshow

$.debug(true)

function SlideShow(album) {

    this.album = album;
	this.imageObjects = album.imageObjects;
	this.interval = 5000;
	this.randomDisplay = album.randomDisplay;
	this.imageIndex = 0;
	this.imageCount = 0;
    for(obj in album.imageObjects) this.imageCount++;

	this.start = function() {
		this.interval = parseInt(document.getElementById(this.album.intervalId).value);
		slideShow.nextImage(this.album.galleryImageId);
		slideShow.updateCaption();
		slideShow.randomPictures(album.randomDisplay);
	}

	this.randomPictures = function(random) {
		this.randomDisplay = random;
		if (random == "no") {
			document.getElementById(this.album.previousId).style.display = "table-cell";
		} else {
			document.getElementById(this.album.previousId).style.display = "none";
		}
	}

	this.updateCaption = function () {
		var image = this.imageObjects[this.imageIndex];
		var captionText = image.caption;
		var captionElement = document.getElementById(this.album.captionId);
		captionElement.innerHTML = image.caption;
		var counterText = "(" + (this.imageIndex + 1) + " of " + this.imageCount + ")";
		var counterElement = document.getElementById(this.album.counterId);
		counterElement.innerHTML = counterText;
//		$.log("captionDiv: " + captionDiv.nodeName + ", captionText: " + captionText.nodeName);
	}

	this.getImageItemLocation = function (imageObj) {
		return album.imageRoot + imageObj.path + imageObj.fileName;
	}

	this.randomNumber = function (x, y) {
		var range = y - x + 1;
		return Math.floor(Math.random() * range) + x;
	}

	this.getNextImage = function () {
		if (this.randomDisplay == "yes") {
			this.imageIndex = this.randomNumber(0, this.imageCount-1);
		}
		else {
			this.imageIndex = (this.imageIndex+1) % this.imageCount;
		}
		var new_image = this.getImageItemLocation(this.imageObjects[this.imageIndex]);
		return(new_image);
	}

	this.getPreviousImage = function () {
		if (this.randomDisplay == "yes") {
			this.imageIndex = this.randomNumber(0, this.imageCount-1);
		}
		else {
			this.imageIndex = this.imageIndex - 1;
			if (this.imageIndex < 0) {
			    this.imageIndex = this.imageCount - 1;
			}
		}
		var new_image = this.getImageItemLocation(this.imageObjects[this.imageIndex]);
		return(new_image);
	}

	this.previousImage = function () {
		document.getElementById(album.galleryImageId).src = this.getPreviousImage();
		this.updateCaption();
	}

	this.nextImage = function () {
		document.getElementById(album.galleryImageId).src = this.getNextImage();
		var nextCall = "slideShow.nextImage()";
		this.updateCaption();
		this.timerID = setTimeout(nextCall, this.interval);
	}

}
