/******************************************************************************
 * University of Wisconsin Platteville
 *
 * University Centers Network Support - ResNet
 *
 * randomimg.js
 *
 * This file contains a class called Image that takes links to images and changes
 * the displayed picture after a set interval of time occurs.
 *
 * @author Adam Nowicki
 * @copyright 2006 ResNet Development
 */

var me;

function RandomImg(myID, dir)
{
	/**
	 * Default extension for images
	 *
	 * @var string
	 * @access private
	 */
	RandomImg.DEFAULT_EXT = ".jpg";
	
	/**
	 * ID of the random picture
	 *
	 * @var integer
	 * @access private
	 */
	var id = myID;
	
	/**
	 * Delay in miliseconds
	 *
	 * @var integer
	 * @access private
	 */
	var delay = 4000;
	
	/**
	 * The directory the images are located
	 *
	 * @var string
	 * @access private
	 */
	var directory = "./";
	
	/**
	 * Image file extension
	 *
	 * @var string;
	 * @access private;
	 */
	var extension = RandomImg.DEFAULT_EXT;
	
	/**
	 * Vector containing image file names
	 *
	 * @var Vector
	 * @access private
	 */
	var images = new Vector();
	
	/**
	 * Vector containing image file names in the random order
	 *
	 * @var Vector
	 * @access private
	 */
	var order = new Vector();
	
	/* Constructor Stuff */
	
	if ( dir != null )
		directory = dir;
	
	if ( directory.substring(directory.length - 1, directory.length) != "/" )
		directory += "/";
	
	me = this;
	
	/* Methods */
	
	this.add = function(file)
	{
		images.push(directory + file);
		this.randomize();
	}
	
	this.addSequence = function(start, end, ext)
	{
		if ( !isInteger(start) || !isInteger(end) )
			throw Exception("Sequence start and end must be integers");
		
		if ( ext == null )
			ext = extension;
		
		if ( ext.substring(0,1) != "." )
			ext = "." + ext;
		
		for ( var i = start; i <= end; i++ )
		{
			this.add(i + ext);
		}
		
		this.randomize();
	}
	
	this.randomize = function()
	{
		order.clear();
		var oldImages = images.clone();
		
		while ( !oldImages.isEmpty() )
		{
			var rand = getRandom( 0, oldImages.getSize() - 1 );
			order.push( oldImages.get(rand) );
			oldImages.remove(rand);
		}
	}
	
	this.getImages = function()
	{
		return images;
	}
	
	this.getOrder = function()
	{
		return order;
	}
	
	this.start = function(myDelay)
	{
		if ( myDelay != null )
			delay = myDelay;

		order.reset();
		this.nextImage();
	}
	
	this.nextImage = function()
	{
		if ( order.next() == false )
		{
			order.first();
		}
		
		
		var img = document.getElementById(id);
		img.src = order.get();
		setTimeout("me.nextImage()", delay);
	}
	
	this.getId = function()
	{
		return id;
	}
	
	this.getDelay = function()
	{
		return delay;
	}
	
	function getRandom(low, high)
	{
		return Math.round( (Math.random() * high) + low );
	}
}