var tv_chainedAnimation = {};

var Tv_animation = function(config, chain){
	/// action,stopAction,delay,nextAnimation are mandatory - nextAnimation could be null
	for(var i in config){ this[i]=config[i]; }
	this._abort = false;
	this._chain = chain ? chain : null;
}

Tv_animation.prototype.animate = function(){
	this.action();
	var self = this;
	(new Ext.util.DelayedTask(function(){
		self.stopAction();
		if(self.nextAnimation){
			self.nextAnimation.animate();
		}
	})).delay(this.delay)
}

Tv_animation.prototype.animate1 = function(){
	if(this._chain && this._chain._abort){return}
    this.timeout = null;
	if(this._chain){ this._chain._currentAnimation = this };
	this.action();
	if(this._chain && this._chain._abort){
		self.stopAction();
        return
    }
	this.timeout = 	window.setTimeout(function(self){
		self.stopAction();
		if(self.nextAnimation){ self.nextAnimation.animate1(); }
	}, this.delay, this);
}



// window.clearTimeout

var Tv_chainedAnimation = function(list){
			//{action:function(){ console.log('start '+this.nb); },
			//stopAction:function(){ console.log('stop '+this.nb)},
			//delay:1000.0 }
	this._abort = false;
	this._currentAnimation = null;
	var self = this;
	this.abort = function(){ 
		self._abort = true;
		if(self._currentAnimation && self._currentAnimation.timeout){
			window.clearTimeout(this._currentAnimation.timeout);
    		self._currentAnimation.stopAction();
		}
	}
	var current=null; var nextAnimation = null;
	for (var i=list.length-1;i>=0; i--){
		list[i].nextAnimation = nextAnimation;
		var current = new Tv_animation(list[i],this);		
		nextAnimation = current;
	}
    this.start = function(){ if(current){current.animate1();}  }
}

var zzz;
var zz= function(){  // test the lib
	var aa=['a','b','c','d','e','f','g','h','i','j','k','l','m'];
    var list = [];
    console.log('xx');
	for (var i=0;i<aa.length; i+=1){
        console.log('xx00-'+aa[i]+i);
		list.push({
			nb:aa[i]+i,
			action:function(){ console.log('start '+this.nb); },
			stopAction:function(){ console.log('stop '+this.nb)},
			delay:3000.0
		});
	}
    console.log('xx10');
    var chain = new Tv_chainedAnimation(list);
    chain.start();
	zzz = function(){
		chain.abort();	
	}
	
}



