/*****

Image Cross Fade Redux
Version 1.0
Last revision: 02.15.2006
steve@slayeroffice.com

Please leave this notice intact. 

Rewrite of old code found here: http://slayeroffice.com/code/imageCrossFade/index.html


*****/
/*****

Modified by Tom Molesworth
tom@audioboundary.com

*****/


window.addEventListener?window.addEventListener("load",so_init,false):window.attachEvent("onload",so_init);

var d=document;

function ImageFade() {
	var that = this;
	that.containerList = [ ];
	css = d.createElement("link");
	css.setAttribute("href","xfade3.css");
	css.setAttribute("rel","stylesheet");
	css.setAttribute("type","text/css");
	d.getElementsByTagName("head")[0].appendChild(css);
	return this;
}

ImageFade.prototype.addContainer = function(el) {
	var div = d.getElementById(el);
	var entry = {
		holder		: div,
		imageList	: div.getElementsByTagName('img'),
		current		: 0
	};
	for(i = 1; i < entry.imageList.length; ++i) {
		entry.imageList[i].xOpacity = 0;
	}
	entry.imageList[0].style.display = "block";
	entry.imageList[0].xOpacity = .99;
	div.style.visibility = 'visible';
	this.containerList.push(entry);
};

ImageFade.prototype.setOpacity = function(obj) {
	if(obj.xOpacity>.99) {
		obj.xOpacity = .99;
		return;
	}
	obj.style.opacity = obj.xOpacity;
	obj.style.MozOpacity = obj.xOpacity;
	obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
};

ImageFade.prototype.step = function() {
	var that = this;
	var longWait = false;
	for(var i = 0; i < this.containerList.length; ++i) {
		var holder = this.containerList[i];
		var cOpacity = holder.imageList[holder.current].xOpacity;
		var nIndex = holder.imageList[holder.current+1] ? (holder.current + 1) : 0;

		nOpacity = holder.imageList[nIndex].xOpacity;
		
		cOpacity -= 0.01; 
		nOpacity += 0.01;
		
		holder.imageList[nIndex].style.display = "block";
		holder.imageList[holder.current].xOpacity = cOpacity;
		holder.imageList[nIndex].xOpacity = nOpacity;
		
		that.setOpacity(holder.imageList[holder.current]); 
		that.setOpacity(holder.imageList[nIndex]);
		
		if(cOpacity<=0) {
			holder.imageList[holder.current].style.display = "none";
			holder.current = nIndex;
			longWait = true;
		}
	}
	if(longWait) {
		setTimeout(function() {
			that.step();
		}, 3000);
	} else {
		setTimeout(function() {
			that.step();
		}, 25);
	}
};

ImageFade.prototype.start = function() {
	if(!this.started) {
		var that = this;
		this.started = true;
		this.timeout = setTimeout(function() {
			return that.step();
		}, 3000);
	}
};

ImageFade.prototype.stop = function() {
	if(this.started) {
		clearTimeout(this.timeout);
		this.started = false;
	}
};

function so_init() {
	var fader = new ImageFade();
	fader.addContainer('imageContainer');
	fader.start();
}
