var ProtoGal = Class.create({ 
	//inicialitzam la clases i les seves opcions
	initialize: function(elem, opt) {
		opt = opt || {};
		
		this.options = {
			width: null,
			height: 1024,
			interval: 10,
			transition: 2
		};
		
		Object.extend(this.options, opt);
		
		this.elem=$(elem);
		
		if (!this.elem) {
			return;
		}
		
		this.elem.hide();
		this.elem.setStyle({'width': this.options.width+"px" });
		this.elem.setStyle({'height': this.options.height+"px" });
		
		//recullim totes les imatges;
		this.imageStack=this.elem.select('img');
		
		var n=this.imageStack.length-1;
		
		//seguim una vegada s'ha carregat la darrera imatge;
		if (n>-1) {
			var img=new Image();
		
			img.onload=function() {
				this.continua();
			}.bind(this);
		
			img.src=this.imageStack[n].getAttribute("src");
		}
	},
	
	continua: function() {
		this.imageStack.each(function(elem) {
			var d=new Element('div', {'style':'position: absolute; display: none;' });
			elem.width=this.options.width;
			d.appendChild(elem);
			this.elem.appendChild(d);
		}.bind(this));
		
		this.divStack=this.elem.select('div');
		this.div=0;
		this.elem.show();
		
		if (this.imageStack.length>1) {
			new Effect.Appear(this.divStack[this.div], { 
				from: 0, 
				to: 1, 
				duration: this.options.transition,
				afterFinish: function (){
					new PeriodicalExecuter(function(pe) {
					    pe.stop();
					    this.anima();
					}.bind(this), this.options.interval);
				}.bind(this)
			});
		} else {
			this.divStack[0].show();
		}
	},
	
	anima: function() {
		new Effect.Fade(this.divStack[this.div], {
			from: 1,
			to: 0,
			duration: this.options.transition
		});
		
		this.div++;
		
		if (this.div>=this.divStack.length) {
			this.div=0;
		}
		
		new Effect.Appear(this.divStack[this.div], { 
			from: 0, 
			to: 1, 
			duration: this.options.transition,
			afterFinish: function (){
				new PeriodicalExecuter(function(pe) {
				    pe.stop();
				    this.anima();
				}.bind(this), this.options.interval);
			}.bind(this)
		});
	}
});
