var Loop = new Class({
	isStopped: true,
	isLooping: false,
	loopDelay: 5000,
	stopLoop: function() {
		this.isStopped = true;
		this.isLooping = false;
		$clear(this.periodical);
		return this;
	},
	startLoop: function(delay) {
		if(this.isStopped){
			var delay = (delay) ? delay : this.loopDelay;
			this.isStopped = false;
			this.isLooping = true;
			this.periodical = this.looper.periodical(delay,this);
		};
		return this;
	},
	looper: function(){
		return this;
	}
});

var ImgLoop = new Class({
	Implements: [Options, Loop],
	options: {
		autostart: true,
		delay: 4000,
		fade: 900,
	},
	images: [],
	initialize: function(container, options){
		this.setOptions(options);
		this.currentImage = -1;
		this.container = $(container);
		this.container.addClass('loop');
		this.container.getElements('img').each(function(e){
				e.set('tween', {duration: this.options.fade})
				e.fade('hide');
				this.images.push(e);
		}.bind(this));
		
		if(this.options.autostart == true) this.start();
	},
	start: function() {
		if(this.currentImage == -1) this.images[0].fade('show');
		this.startLoop(this.options.delay);
	},
	looper: function() {
		var key = this.currentImage + 1;
		if (key > this.images.length - 1) key = 0;
		this.show(key);
		return this;		
	},
	show: function(i) {
		this.currentImage = i;
		this.images.each(function(e, j) {
			if (i == j) {
				e.fade('in');
   			} else {
				e.fade('out');
			}
		}.bind(this));
	}
});
