JAME.Package('JAME.Components.CrossFader');

JAME.Components.CrossFader= function(options) {	

		this.delay      = options.delay      || 7000;
		this.transition = options.transition || 2000;
		this.current    = 0;
		this.imgs       = options.imgs      || parse('.JCrossFader img');
		this.imgs       = this.imgs && this.imgs.constructor===Array ? this.imgs : this.imgs ? [this.imgs] : undefined;
		this.imgsToLoad = options.imgsToLoad ||[];
		this.container  = options.container;

		if(!this.imgs) throw('no images to cross-fade');

		if(this.imgs.length==1 && this.imgsToLoad.length==0) return;

		this.max = this.imgs.length-1;

		this.setImgsStyle();
		if(this.imgsToLoad.length==0)
			this.start();

		
};

JAME.Components.CrossFader.prototype = {

	start:function(){
		var me =this;
		this.running=true;
		new JAME.FX.Tween(this.imgs[0],{opacity:[0,1]},{duration:10}).addListener('onComplete',function() {me.round()});
	},
	setImgsStyle : function() {
		var me=this;
		JAME.each(this.imgs,function(elm) {
			me.setImgStyle(elm);
		});
	},
	setImgStyle:function(elm){

		if(elm.nodeName.toLowerCase()!=='img') return;

		JAME.CSS.setStyles(elm,{
			opacity:0,
			position:'absolute',
			top:0,
			left:0,
			zIndex:1
		});
	},
	stop : function() {
		this.running=false;
	},
	restart : function() {
		if(this.running===false) {
			this.running=true;
			this.round();
		}
	},
	fadein : function(current) {
		var effect        = {};
		effect['opacity'] = [0,1];

		var transition=this.transition;
		effect['left'] = [this.current%2 ? -5:5,0];
		return new JAME.FX.Tween(this.imgs[current],effect,{duration:transition,easing:JAME.FX.Transition.Sine.Out});
	},
	fadeout : function(current) {
		var effect        = {};
		effect['opacity'] = [1,0];
		var transition    = this.transition;
		return new JAME.FX.Tween(this.imgs[current],effect,{duration:transition});
	},
	round : function() {

		var me=this;
		if(!this.running) {
			clearTimeout(this.timeout);
			return;
		}
		this.current++;

		if(this.current>this.max && this.imgsToLoad.length>0) {
			clearTimeout(this.timeout);
			var newImg = this.imgsToLoad.shift();
			var img    = JAME.DOM.createNode('img');
			img.onload = function(e){
				me.imgs.push(img);
				me.max=me.imgs.length-1;
				me.current=me.max;
				me.setImgStyle(img);
				me.container.appendChild(img);
				me.goRound();
			}
			img.onabort=img.onerror=function(e){
				me.round();
			}
			img.src=newImg;
			return;
		}
		
		if(this.current>this.max) {
			this.current=0;
		}
		this.goRound();
	},
	goRound:function(){
		var me = this;
		this.timeout = setTimeout(function() {

			me.fadein(me.current).addListener('onComplete',function() { me.round() });
			me.fadeout(me.current===0 ? me.max : me.current-1);

		},this.delay);
	}
};
