function bot_image_timerFunction(self)
{
	return function() { self.advance() };
}

function bot_image(id, delay, transition)
{

	this.delay		= delay ? delay : 5000;
	this.transition = transition ? transition : 1000;
	
	var container = document.getElementById(id);
	
	// Get the images we'll cycle through.
	this.images = container.getElementsByTagName("img");

	for (i = 0; i < this.images.length; ++i)
	{
		$(this.images[i]).setOpacity(0);
	}
	
	// Show one of the images.
	this.current = 0;
	this.images[this.current].style.display = "block";
	this.images[this.current].style.zIndex  = 1;
	$(this.images[this.current]).setOpacity(1);

	var pos = $(container).getCoordinates();
	var top = pos.top;

	var shutterRate = 3000 / 1000; // Pixels per millisecond
	
	// Set the first time so we get a staggered appearance if there are multiple cyclers on the same page.
	this.timer = setTimeout(bot_image_timerFunction(this), top * shutterRate, this);

	var self = this;
	
	// This function is called when a transition is completed. It sets the display for
	// all images other than the current one to hidden
	this.complete = function()
	{
		for (i = 0; i < self.images.length; ++i)
		{
			if (i != self.current) {

				self.images[i].style.display = 'none'
				$(self.images[i]).setOpacity(0);
			}
		}
	}

}

bot_image.prototype.setTimer = function()
{
	this.timer = setTimeout(bot_image_timerFunction(this), this.delay);
}

// Fades in the next image in the sequence.
bot_image.prototype.advance = function()
{
	var next = (this.current + 1) % this.images.length;
	this.showImage(next);
}

bot_image.prototype.showImage = function(next)
{

	// Show the next image.
	this.images[next].style.display = "block";
	this.images[next].style.zIndex  = 1;	
	
	// Decrease the z-index of all of the images currently being shown so that the image we're
	// fading into will be on top.
	for (var i = 0; i < this.images.length; ++i)
	{
		if (i != next) {
			this.images[i].style.zIndex = this.images[i].style.zIndex - 1;
		}
	}

	// If we're already fading, another image, stop it.
	if (this.effect) {
		this.effect.cancel();
	}

	this.current = next;

	// Create the fade in effect.
	this.effect = new Fx.Morph(this.images[next], {duration: this.transition, onComplete: this.complete});
	this.effect.start({ 'opacity': [this.images[next].style.opacity, 1] });

	this.setTimer();

}

function bot_image_initialize(id, delay, transition)
{
	bot = new bot_image(id, delay, transition);
}
