//
// Subpage Image Rotator Component
//

function SubpageImageRotator(instanceName)
{
	/////////////////////////
	// Properties
	/////////////////////////
	this.instanceName 	= instanceName;
	this.images 		= new Array();
	this.btmImage		= null;
	this.topImage		= null;
	this.timer			= null;
	this.interval		= 5000;
	this.fadeInterval	= 50;
	this.fadeStep 		= 5;
	this.currentAlpha	= 100;
	this.currentImage	= 0;


	/////////////////////////
	// Methods
	/////////////////////////

	// Add image to rotation
	this.add = function(imageId)
	{
		this.images.push({'id' : imageId});
	}

	// Get Element By Id
	this.getElement = function(elementId)
	{
		if (document.getElementById(elementId))
		{
			return document.getElementById(elementId);
		}
		alert('Could not locate element with id "'+elementId+'"');
		return false;
	}

	// Initialize Object
	this.init = function()
	{
		this.btmImage = this.getElement('btmImage');
		this.topImage = this.getElement('topImage');
		this.play();
	}

	// Begin/resume rotation
	this.play = function()
	{
		var instance = this;
		this.timer = setInterval
		(
			function()
			{
				instance.nextImage();
			},
			this.interval
		);
		delete(instance);
	}

	// Pause rotation
	this.pause = function()
	{
		clearInterval(this.timer);
		this.timer = null;
	}

	// Advance to next image
	this.nextImage = function()
	{
		this.currentImage++;
		if (this.currentImage == this.images.length)
		{
			this.currentImage = 0;
		}

		var image = this.images[this.currentImage];
		var imageUrl = this.baseHref+'http://www.visitathensga.com/images/display.php?id='+image.id+'&width=776&height='+height;

		var instance = this;
		this.btmImage.onload = function()
		{
			instance.fade();
		}
		delete(instance);
		this.btmImage.src = imageUrl;
		return true;
	}

	// Fade top image out
	this.fade = function()
	{
		this.currentAlpha = this.currentAlpha - this.fadeStep;
		if (this.currentAlpha < 0)
		{
			this.fadeComplete();
		}
		else
		{
			this.setAlpha(this.topImage, this.currentAlpha);
			var instance = this;
			setTimeout(function()
			{
				instance.fade();
			},
			this.fadeInterval);
			delete(instance);
		}
	}

	// Done fading
	this.fadeComplete = function()
	{
		this.currentAlpha = 100;
		this.topImage.src = this.btmImage.src;

		var instance = this;
		this.topImage.onload = function()
		{
			instance.setAlpha(instance.topImage, 100);
		}
		delete(instance);
	}

	// Set element alpha
	this.setAlpha = function(object, value)
	{
		object.style.opacity = value/100;
		object.style.MozOpacity= value + '%';
		object.style.filter = 'alpha(opacity=' + value + ')';
	}


}


