var imageFader = {
	delay: 5000,
	transLength: 2000,
	imageUrls: new Array( ),
	nextId: -1,
	timer: null,
	fadeImages: null,
	topImageIndex: -1,
	started: false,
	
	init: function( ) {
		this.fadeImages = new Array( );

		this.fadeImages.push($('fadeImage0'));
		this.fadeImages.push($('fadeImage1'));
		
		this.clearImages( );
	},

	clearImages: function( ) {
		this.stop( );
		this.imageUrls = new Array( );
		// IT STARTS AT 0, LOSER
		this.currentId = -1;
		this.nextId = -1;
	
		this.topImageIndex = 0;
	},

	addImage: function(url) {
		this.imageUrls.push(url);
		if(this.nextId == -1) {
			this.fadeImages[0].src = url;
			this.inTrans(this.fadeImages[0]);
			this.outTrans(this.fadeImages[1]);
			this.nextId = 1;
		}

		if(this.imageUrls.length > 1) {
			this.start( );
		}
	},

	start: function( ) {
		if(!this.started) {
			this.timer = this.fadeImage.periodical(this.delay, this);
			this.started = true;
		}
	},

	stop: function( ) {
		if(this.timer) $clear(this.timer);
		this.started = false;
	},

	fadeImage: function( ) {
		if(this.started) {
			var currIndex = this.topImageIndex;
			var nextIndex = this.topImageIndex + 1;
			if(nextIndex > this.fadeImages.length - 1) {
				nextIndex = 0;
			}

			var currId = this.nextId;
			var nextUrl = this.imageUrls[this.nextId];
			if(!nextUrl) nextUrl = this.imageUrls[0];
			if(++this.nextId > this.imageUrls.length - 1) this.nextId = 0;
	
			var oldHolder = this.fadeImages[currIndex];
			var newHolder = this.fadeImages[nextIndex];
			oldHolder.removeEvents("load");
			newHolder.removeEvents("load");
			newHolder.addEvent("load", function( ) {
				this.outTrans(oldHolder);
				this.inTrans(newHolder);
				this.topImageIndex = nextIndex;
			}.bind(this));
			newHolder.src = nextUrl;

			if(this.imageUrls.length == 1) {
				this.stop( );
			}
		}
	},
	
	outTrans: function(el) {
		el.set('tween', {duration: this.transLength});
		el.tween('opacity', 0);
	},

	inTrans: function(el) {
		el.set('tween', {duration: this.transLength});
		el.tween('opacity', 1);
	}

};

