function Fader(jq){
	this.current = 0;
	this.jq = jq;
	this.title = jq.attr("title");
	if (!this.title) this.title = "";
	this.parseValues();
	this.images = jq.children("img");
	this.titles = [];
	this.len = this.images.length;
	for (var i=0; i<this.len; i++){
		this.titles[i] = this.images[i].title;
	}
	
	this.jq.css({
		"position" : "relative",
		"height" : this.images.attr("height")+"px",
		"width": this.images.attr("width")+"px",
		"display" : "block"
	});
	
	this.images.css({
		"position":"absolute",
		"top":"0px",
		"left":"0px",
		"border":"none"
	});
	// this hide call must take place after the css meddling above
	// otherwise safari <= 2.0 tends to crash
	this.images.next().hide();
	
	Fader.list.push(this);
	Fader.named[this.title] = this;
}

Fader.list = [];
Fader.named = {};

Fader.prototype.updateTitles = function (snap){

		if (!(this.caption || this.counter)) return;

		if (this.caption){
			var cap = this.titles[this.current];
			this.caption.html(cap ? cap : "");
			if (!snap){
				this.caption.hide();
				this.caption.fadeIn(this.speed);
			}
		}

		if (this.counter){
			var cs = "Image #current/#max";
			var text = cs.replace(/#current/,this.current + 1).replace(/#max/,this.len);
			this.counter.html(text);
			if (!snap){
				this.counter.hide();
				this.counter.fadeIn(this.speed);
			}
		}
}

Fader.prototype.parseValues = function(){
	if (this.title.match(/^\s*\d+\s*,\s*\d+\s*$/)){
		var temp = this.title.split(",");
		this.delay = parseInt(temp[0]);
		this.speed = parseInt(temp[1]);
	} else if (this.title.match(/^\s*\d+\s*$/)){
		this.delay = parseInt(this.title);
		this.speed = 1000;
	} else {
		this.delay = 3000;
		this.speed = 1000;
	}
	//if (console) console.debug("speed "+this.speed+ " delay "+this.delay);
}

Fader.prototype.fade = function(delta){
	if (!delta) delta = 1;
	else delta = -1;

	var show = this.current + delta;
	if (show < 0) show = this.len - 1;
	else show = show % this.len;
		
	//if (console) console.debug("current " + this.current + " show " + show);
	
	$(this.images[this.current]).fadeOut(this.speed);
	$(this.images[show]).fadeIn(this.speed);

	this.current = show;
	this.updateTitles();
}

Fader.prototype.start = function(){
	var callback = function(obj){ return function (){obj.fade();} };
	this.timer = setInterval(callback(this),this.delay);
}

Fader.prototype.stop = function(){
	clearTimeout(this.timer);
}
	
Fader.prototype.next = function(){
	this.stop();
	this.fade();
}

Fader.prototype.previous = function(){
	this.stop();
	this.fade(-1);
}

Fader.prototype.addCaption = function(name){
	this.caption = $("#"+name);
}

Fader.prototype.addCounter = function(name){
	this.counter = $("#"+name);
}

Fader.stop = function(){
	for (each in Fader.list){
		Fader.list[each].stop();
	}
}

Fader.start = function(){
	for (each in Fader.list){
		Fader.list[each].start();
	}
}

$(function(){	
	$(".fader").each(function(){new Fader($(this));});
});

