var SimpleLoopPages = new Class({
	Implements: Events,
	Extends: SimpleLoop,
	busy: false,
	changeImages: false,
	nextImages: [],
	toBye: false,
	change: function()
	{
		if(this.imgs.length > 1)
		{
			this.ini++;
			if(this.ini >= this.imgs.length)
				this.ini = 0;
			//si la imagen no esta cargada esperamos al proximo cambio
			if(this.imgs[this.ini].getState() == 'loaded' && this.imgs[this.ini] != this.current)
			{
				this.transition(this.imgs[this.ini]);
				this.busy = true;
			}else if(this.imgs[this.ini].getState() == 'bye') {
			    this.imgs[this.ini] = null;
			    this.imgs = this.imgs.clean();
			    this.ini--;
			    this.change();
			}else{
				this.ini--;
			}
		}else{
			$clear(this.interval);
		}
	},
	constructImg: function(path, indice)
	{
		if(indice == 0)
		{
	        return new SimpleLoopImage(path,
	        {
	            onFadeIn: function()
	            {
	                this.current.invisible();
	                this.current = this.next;
					this.busy = false;
					if(this.nextImages.length > 0)
						this.changeImages(this.nextImages);		    
	            }.bind(this),
				onLoad: function()
				{
					this.change();
					this.interval = this.change.periodical(this.time, this);
					this.toBye = false;
					this.fireEvent('changeok');
				}.bind(this)
	        });
		}else{
	        return new SimpleLoopImage(path,
	        {
	            onFadeIn: function()
	            {
	                this.current.invisible();
	                this.current = this.next;
					this.busy = false;
					if(this.nextImages.length > 0)
						this.changeImages(this.nextImages);		    
	            }.bind(this)
	        });
		}
	},
	changeImages: function(imgs, url)
	{
		this.fix();
		if(!this.toBye)
		{
			this.setBase(url);
			if(this.busy)
			{
				this.nextImages = imgs;
			}else{
				$clear(this.interval);
				this.imgs.each(function(el)
				{
					if(this.current != el)
					{
						el.destruct();
						el = null;
					}
				}.bind(this));
				this.toBye = true;
				this.imgs = [];
				this.current.bye();
				this.imgs.include(this.current);
				var firstImg;
				imgs.each(function(path, indice)
				{
					var img = this.constructImg(this.baseUrl + path, indice);
					this.imgs.include(img);
				}.bind(this));
				this.ini = 0;
				this.nextImages = [];
			}
		}
	},
	isOk: function()
	{
		return (this.toBye) ? false : true;
	},
	fix: function()
	{
		var els = $('bg').getChildren();
		els.each(function(el)
		{
			var sta = false;
			this.imgs.each(function(img)
			{
				if(img.img.get('src') == el.get('src'))
					sta = true;
			});
			if(!sta)
				el.destroy();
		}.bind(this));
	}
});
