function ImageSwitcher(objId)
{
	var id = objId;
	var length = 0;
	var names = [];
	var index = -1;

	var swap = function (obj, image, filename)
	{
		image = $(image);
		var overlay = image.cloneNode(true);
		overlay = $(overlay);

		overlay.src = filename;
		overlay.width = image.width;
		overlay.height = image.height;
		var pos = image.positionedOffset();
		overlay.setStyle(
		{
			position: 'absolute',
			left: pos[0] + 'px',
			top: pos[1] + 'px'
		});
		overlay.setOpacity(0);
		obj.appendChild(overlay);

		(new Effect.Opacity(overlay, {
			from: 0.0,
			to: 1.0,
			duration: 1.0,
			afterFinish: function ()
			{
				image.src = filename;
				obj.removeChild(overlay);
			}
		}));
	};

	var swapImage = function ()
	{
		var filename = '/splash/' + names[index];
		var obj = document.getElementById(id);
		var image = obj.getElementsByTagName('img')[0];

		var pre = new Image();
		pre.onload = function ()
		{
			swap(obj, image, filename);
		};
		pre.src = filename;
	};

	this.next = function ()
	{
		if (length > 0)
		{
			index = (index + 1) % length;
			swapImage();
		}
	};

	this.prev = function ()
	{
		if (length > 0)
		{
			index = index - 1;
			if (index < 0)
			{
				index = length - 1;
			}
			swapImage();
		}
	};

	var loadFiles = function (text)
	{
		var lines = text.split('\n');
		var i;
		for (i = 0; i < lines.length; i = i + 1)
		{
			if (lines[i].length > 3)
			{
				names.push(lines[i]);
			}
		}
		length = names.length;
	};

	var findCurr = function ()
	{
		var o = document.getElementById(id);
		var img = o.getElementsByTagName('img')[0];
		if (img)
		{
			var c = img.src;
			c = c.split('/').pop();
			var i;
			for (i = 0; i < length; i = i + 1)
			{
				if (c === names[i])
				{
					index = i;
				}
			}
		}
	};

	(new Ajax.Request('/splash/',
	{
		method: 'get',
		onSuccess: function (transport)
		{
			loadFiles(transport.responseText);
			findCurr();
		}
	}));

}


function Slideshow(id, autostart)
{
	var timer = null;
	var switcher = new ImageSwitcher(id);
	var duration = 8000;

	var startTimer = function ()
	{
		timer = setInterval(function ()
		{
			switcher.next();
		}, duration);

	};

	var stopTimer = function ()
	{
		clearInterval(timer);
		timer = null;
	};

	if (autostart)
	{
		startTimer();
	}

	this.start = function ()
	{
		if (timer === null)
		{
			switcher.next();
			startTimer();
		}
	};

	this.stop = function ()
	{
		if (timer !== null)
		{
			stopTimer();
		}
	};

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

	this.next = function ()
	{
		switcher.next();
		if (timer !== null)
		{
			stopTimer();
			startTimer();
		}
	};

	this.prev = function ()
	{
		switcher.prev();
		if (timer !== null)
		{
			stopTimer();
			startTimer();
		}
	};
}


var slideshow = new Slideshow('slide', 1);
