var SimpleLoopImage = new Class({
    Implements: [Events, Options],
    img: null,
    fx: null,
	initialize: function(path, options)
	{
		this.setOptions(options);
		this.img = new Asset.image(path,
		{
			onload: function()
			{
				this.img.store('state', 'loaded');
				this.fireEvent('load');
			}.bind(this)
		});
		this.img.setStyle('position', 'absolute');

		this.fx = new Fx.Morph(this.img, 
		{
			duration: 2000, 
			transition: Fx.Transitions.Sine.easeOut,
			onComplete: function()
			{
				this.fireEvent('fadeIn');
			}.bind(this)
		});
		this.invisible();
	},
	inject: function(container)
	{
		this.img.inject(container);	
	},
	visible: function()
	{
    	this.img.setStyle('opacity', '1');
	},
	invisible: function()
	{
    	this.img.setStyle('opacity', '0');
	},
	fadeIn: function()
	{
		this.fx.start({opacity: 1});
	},
	getState: function()
	{
	    return this.img.retrieve('state');
	},
	bye: function()
	{
        this.img.store('state', 'bye');
	},
	destruct: function()
	{
        this.img.dispose();
        this.fx = null;
		this.removeEvents('fadeIn');
	}
});

var SimpleLoop = new Class({
	container: null,
	imgsPath: [],
	imgs: [],
	baseUrl: '', // hier begint  de basis map voor de afbeeldingen. 
	
	
	ini: 0,
	current: null,
	next: null,
	interval: false,
	time: 5000,
	initialize: function(container, imgs, url) 
	{
		this.container = $(container);
		this.imgsPath = imgs;
		if(url != undefined)
			this.baseUrl = url;
	},
	setBase: function(url)
	{
		if(url != undefined)
			this.baseUrl = url;
	},
	start: function()
	{
		this.container.empty();
		this.container.setStyles({'position':'relative'});
		this.imgsPath.each(function(path, c)
		{
			var img = this.constructImg(this.baseUrl + path);
			if(c > 0)
			{
    			img.invisible();
			}else{
				this.current = img;
				this.current.visible();
			}
				
			img.inject(this.container);
			this.imgs.include(img);
		}.bind(this));
		this.interval = this.change.periodical(this.time, this);
	},
	change: function()
	{
		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.transition(this.imgs[this.ini]);
		}else{
			this.ini--;
		}
	},
	transition: function(next)
	{
		this.next = next;
		this.next.inject(this.container);
		this.next.fadeIn();
	},
	constructImg: function(path)
	{
        return new SimpleLoopImage(path,
        {
            onFadeIn: function()
            {
                this.current.invisible();
                this.current = this.next;		    
            }.bind(this)
        });
	}
});

