
var APT = {};

APT.Slideshow = function(ul)
{
	this.ul = ul;
	this.elems = ul.getElementsByTagName("li");
	
	// Defaults (can change with class)
	this.tickLength = 20;
	this.fadeTime = 500;
	this.waitTime = 1000;
	this.randomize = false;
	
	var props = ul.className.split(" ");
	for (var p = 0; p < props.length; p++)
	{
		var prop = props[p];

		var m = prop.match(/tick(\d+)/);
		if (m) this.tickLength = m[1];
		
		var m = prop.match(/wait(\d+)/);
		if (m) this.waitTime = m[1];
		
		var m = prop.match(/fade(\d+)/);
		if (m) this.fadeTime = m[1];
		
		if (prop == "randomize") this.randomize = true;		
	}
	
	this.curSlideIndex = this.randomize ? Math.floor(Math.random() * this.elems.length) : 0;
	this.nextSlideIndex = (this.curSlideIndex + 1) % this.elems.length;
	
	for (var n = 0; n < this.elems.length; n++) 
	{
		this.setOpacity(this.elems[n], (n == this.curSlideIndex) ? 1 : 0);
		this.elems[n].style.zIndex = (n == this.nextSlideIndex) ? "1000" : "0";
	}
	
	this.startWait();
	
	var self = this;
	window.setInterval(function() { self.onTimer(); }, this.tickLength);
}

APT.Slideshow.State = {};
APT.Slideshow.State.waiting = "waiting";
APT.Slideshow.State.fading = "fading";

APT.Slideshow.prototype.setOpacity = function(elem, op)
{
	elem.style.opacity = "" + op;
	elem.style.filter = "alpha(opacity=" + (op * 100) + ")";
}

APT.Slideshow.prototype.onTimer = function()
{
	switch(this.state)
	{
		case APT.Slideshow.State.waiting:
			this.stateIndex++;
			if (this.stateIndex >= this.stateCount) this.startFade();
			break;
		case APT.Slideshow.State.fading:
			this.stateIndex++;
			this.setOpacity(this.elems[this.nextSlideIndex], 1. * this.stateIndex / this.stateCount);
			if (this.stateIndex >= this.stateCount) 
			{
				this.startWait();
				this.setOpacity(this.elems[this.curSlideIndex], 0);
				this.curSlideIndex = this.nextSlideIndex;
			}
			break;
	}
}

APT.Slideshow.prototype.startFade = function()
{
	this.nextSlideIndex = (this.curSlideIndex + 1) % this.elems.length;
	this.state = APT.Slideshow.State.fading;
	this.stateCount = this.fadeTime / this.tickLength;
	this.stateIndex = 0;
	for(var n = 0; n < this.elems.length; n++) 
		this.elems[n].style.zIndex = (n == this.nextSlideIndex) ? "1000" : "0";
}

APT.Slideshow.prototype.startWait = function()
{
	this.state = APT.Slideshow.State.waiting;
	this.stateCount = this.waitTime / this.tickLength;
	this.stateIndex = 0;
}

APT.slideshows = [];

APT.Slideshow.StartAll = function()
{
	var uls = document.getElementsByTagName("ul");
	for(var u = 0; u < uls.length; u++)
	{
		var ul = uls[u];
		if (ul.className.indexOf("slideshow") < 0) continue;

		APT.slideshows.push(new APT.Slideshow(ul));
	}
}


