function HomePageCycler()
{
	this.homePageRotationTimeout = 5000;
	this.currentIndex = 0;
	this.animationDuration = 1;
	this.timeout = null;
	this.isAnimating = false;
	this.elems = $$("div#home-page-rotations > div");

	this.toggle = function()
	{
		if (this.timeout === null)
		{
			this.start();
		}
		else
		{
			this.stop();
		}
	}

	this.stop = function()
	{
		window.clearTimeout(this.timeout);
		this.timeout = null;
	}

	this.switchHomePageThing = function(newIndex)
	{
		if (this.isAnimating)
		{
			return;
		}

		this.isAnimating = true;

		if (this.timeout !== null)
		{
			this.refreshTimeout();
		}

		if (newIndex >= this.elems.length || newIndex < 0)
		{
			throw newIndex + " is totally not within bounds";
		}

		var current = this.elems[this.currentIndex];
		
		var next = this.elems[newIndex];

		for (var i = 0; i < this.elems.length; i++)
		{
			$("select-home-page-rotation-" + i).down("a").setStyle({backgroundColor: (i == newIndex) ? "white" : "#5696d5"});
		}

		var outer = this;
		new Effect.Parallel(
			[
				new Effect.Fade(
					current,
					{
						from: 1,
						to: 0,
						duration: this.animationDuration,
						afterFinish: function()
						{
							current.setStyle(
								{
									display: "none"
								}
							);
							outer.isAnimating = false;
						}
					}
				),
				new Effect.Fade(
					next,
					{
						from: 0,
						to: 1,
						duration: this.animationDuration,
						afterUpdate: function()
						{
							next.setStyle(
								{
									display: ""
								}
							);
						}
					}
				)
			],
			{
				duration: this.animationDuration
			}
		);

		this.currentIndex = newIndex;

		if (this.timeout !== null)
		{
			this.refreshTimeout();
		}
	}

	this.rotateHomePageThings = function()
	{
		// get the current and next element
		var newIndex = this.currentIndex + 1;
		
		if (newIndex >= this.elems.length)
		{
			newIndex = 0;
		}

		this.switchHomePageThing(newIndex);
	};

	this.prepareHomePageThings = function()
	{
		for (var i = 1; i < this.elems.length; i++)
		{
			var elem = this.elems[i];
			elem.setStyle(
				{
					display: "none",
					opacity: 0
				}
			);
		}
	};

	this.refreshTimeout = function()
	{
		var outer = this;

		window.clearTimeout(this.timeout);
		this.timeout = window.setTimeout(
			function()
			{
				outer.rotateHomePageThings();
			},
			outer.homePageRotationTimeout
		);
	}

	this.start = function()
	{
		if (this.timeout === null)
		{
			this.refreshTimeout();
		}
	}
};

var cycler = null;

document.observe(
	"dom:loaded",
	function()
	{
		if ($("home-page-rotations"))
		{
			cycler = new HomePageCycler();
			cycler.prepareHomePageThings();
			cycler.start();
		}
	}
);

function toggleHomePageRotation()
{
	cycler.toggle();
}

function selectHomePageRotation(index)
{
	cycler.switchHomePageThing(index);
}
