var XFader = function (elements, animationtime, waittime, callback) {
	this.elements = elements;
	this.animationtime = animationtime;
	this.waittime = waittime;
	this.current = 1;
	this.callback = callback;
	this.timer = null;
	
	this.init = function() {
		this.elements.eq(0).css('display', 'block');
	}
	
	this.start = function() {
		var thisXF = this;
		this.timer = setTimeout(function() { thisXF.slide.apply(thisXF, []); }, thisXF.waittime);
	}

	this.stop = function() {
		clearTimeout(this.timer);
		this.timer = null;
	}
	
	this.slide = function() {
		var next = (this.current % this.elements.size()) + 1;
		if (next <= this.current && this.callback != null) {
			this.callback.call();
			return;
		}
		var elem = this.elements.eq(this.current - 1);
		if (elem.children('img').size() > 0) elem = elem.children('img').eq(0);
		elem.fadeOut(this.animationtime, 0, function() { if (document.all) { this.style.removeAttribute('filter'); }});
		var thisXF = this;
		var elem = this.elements.eq(next - 1);
		if (elem.children('img').size() > 0) elem = elem.children('img').eq(0);
		elem.show();
		if (document.all) { elem.get(0).style.removeAttribute('filter'); }
		this.timer = setTimeout(function() { thisXF.slide.apply(thisXF, []); }, thisXF.waittime);
		this.current = next;
	}
}

jQuery.fn.extend({
	XFade: function(animationtime, waittime, callback) {
		if (typeof(animationtime) == "number") {
			$(this).data('xfader', new XFader($(this).children(), animationtime, waittime, callback));
			$(this).data('xfader').init.apply($(this).data('xfader'), []);
		} else if (animationtime == "start") {
			$(this).data('xfader').start.apply($(this).data('xfader'), []);
		} else if (animationtime == "stop") {
			$(this).data('xfader').stop.apply($(this).data('xfader'), []);
		}
	}
});

