/**
 * @class CrossFader
 * @description Fades between elements (opacity).
 * @param {Element|String} container The element that wraps the frames.
 * @param {Object} options fadeDelay, number of intervals before swap.
 */
var CrossFader = new Class({
	Implements: Options,
	options: {
		fadeDelay:5000,
		duration :500
	},
	initialize: function(container, options){
		this.setOptions(options);
		this.container = $(container);
		this.frames = $defined(this.options.frames) ? $$(this.options.frames) : this.container.getChildren();
		this.currentframe = 0;
		
		this.setupContainer();
		
		this.frames.each(function(frame, index){
			this.addFrame(frame);
		}, this);
		
		this.container.addEvents({
			'mouseenter':this.pause.bindWithEvent(this),
			'mouseleave':this.start.bindWithEvent(this)
		});
		
		this.frames[0].setStyle('opacity', 1);
		this.start();
		
	},
	setupContainer: function(){
		this.containerHeight = 0;
		
		this.frames.each(function(frame, index){
			this.containerHeight = (frame.getSize().y >= this.containerHeight)? frame.getSize().y : this.containerHeight;
		}, this);
		
		this.container.setStyles({
			position:'relative',
			height:this.containerHeight
		});
		
	},
	addFrame: function(frame){
		frame = $(frame);
		
		frame.setStyles({
			position:'absolute',
			top:0,
			left:0,
			opacity:0
		});
		
		frame.set('morph', {duration: this.options.duration});
		
		this.frames.combine([frame]);
		
	},
	next: function(){
		var currentFrame = this.frames[this.currentframe];
		var nextFrameIndex = (this.currentframe + 1 >= this.frames.length)? 0 : this.currentframe + 1;
		var nextFrame = this.frames[nextFrameIndex];
		
		currentFrame.morph({opacity:0});
		nextFrame.morph({opacity:1});
		
		this.currentframe = (this.currentframe + 1 >= this.frames.length)? 0 : this.currentframe + 1;
	},
	start: function(){
		this.periodical = this.next.periodical(this.options.fadeDelay + this.options.duration, this);
	},
	pause: function(){
		$clear(this.periodical);
	}
});