/**
*   Copyright (c) 2008, All rights reserved.
*   António Rodrigues, www.alfarod.net
*   
*   The author does not authorize the copy of this code, fully or partially,
*   without expressed permission according to the law and international conventions.
*/

// object collection
ImageRotator.instances = [];

/*
 * Constructor. Initializes the variables.
 * arguments: image ID, caption ID, rotation speed in ms.
 */
function ImageRotator(imgId, captionId, speed) {
	// identifies this object for further use
	this.index = ImageRotator.instances.length;
	ImageRotator.instances[this.index] = this;
	this.refreshMethodString = "ImageRotator.instances[" + this.index + "].refreshImage();";
	// initializes variables
	this.imgId = imgId || '';
	this.captionId = captionId || '';
	this.speed = speed || 5000; // default speed
	this.imageArray = new Array(); 
	this.captionArray = new Array(); 
	


	/**
	 * Populates the array of images. 
	 * Receives a comma-separated list of images.
	 */
	this.addImages = function() { 
		for (var i=0; arguments[i]; i++) {
			this.imageArray[i] = arguments[i];
		}
	}
	
	
	/**
	 * Populates the array of captions
	 * Receives a comma-separated list of captions.
	 */
	this.addCaptions = function() { 
		for (var i=0; arguments[i]; i++) {
			this.captionArray[i] = arguments[i];
		}
	}


	/**
	 * Refreshes the image and caption specified by imgId and captionId
	 */
	this.refreshImage = function() { 
		var imgObj = document.getElementById(this.imgId); 
		var capObj = document.getElementById(this.captionId);
		if (imgObj) {
			var randomIndex = Math.round(Math.random()*(this.imageArray.length-1));   
			imgObj.src = this.imageArray[randomIndex];
			if (capObj) {
				capObj.innerHTML = this.captionArray[randomIndex] || '';
			}
			setTimeout(this.refreshMethodString,  this.speed);
		}
	}


	/**
	 * Starts the rotation. 
	 * Initialiyes the image ID, caption ID and time out.
	 */
	this.startRotation = function() { 
		setTimeout(this.refreshMethodString,  this.speed);
	}


} //end of class

