var ProtoDisplay=Class.create({
	initialize: function(elem1, elem2, opt) {
		opt = opt || {};
		this.options = {
			animSpeed: 0.5
		};
		
		Object.extend(this.options, opt);
		
		this.elem1 = $(elem1);
		this.elem2 = $(elem2);
		if ((!this.elem1) || (!this.elem2)) return;
		
		this.animating=false;
		
		//número total de items
		this.totalItems=this.elem2.lastChild.value;
		
		//items per pàgina
		this.itemsByPage=this.elem2.childNodes[7].value;
		
		//calculam el número de pàgines
		this.totalPages=parseInt(this.totalItems/this.itemsByPage);
		
		if (this.totalPages!=(this.totalItems/this.itemsByPage)) {
			this.totalPages++;
		}
		
		if (this.totalPages>0) {
			this.currentPage=1;
		}
		
		//element que es mou
		this.movible=$(this.elem1.firstChild);
		
		//mesures en px de quant s'ha de moure
		this.offset=this.elem1.getWidth();
		
		$(this.elem2.firstChild.firstChild).observe('click', (function() { 
												this.moveRight();
											 }).bind(this));
		
		$(this.elem2.childNodes[2].firstChild).observe('click', (function() { 
												this.moveLeft();
											 }).bind(this));
		
		this.updateCounter();
	},
	
	updateCounter: function() {
		this.firstCurrentItem=(this.currentPage*this.itemsByPage)-(this.itemsByPage-1);
		this.lastCurrentItem=this.currentPage*this.itemsByPage;

		if (this.lastCurrentItem>this.totalItems) {
			this.lastCurrentItem=this.totalItems;
		}
		
		$(this.elem2.childNodes[4]).update(this.firstCurrentItem+"-"+this.lastCurrentItem);
		$('nPag').update(this.currentPage);
	},
	
	moveRight: function() {
		if (this.currentPage>=this.totalPages) {
			return;
		}
		
		if (this.animating) {
			return;
		}
		
		
		this.currentPage++;
		this.animating=true;
		
		new Effect.Fade(this.movible, { duration: this.options.animSpeed, from: 1, to: 0.3, 
			afterFinish: function() {
				new Effect.Move(this.movible, { duration: this.options.animSpeed, mode: 'relative', x: (-1*this.offset),
					afterFinish: function() {
						new Effect.Appear(this.movible, { duration: this.options.animSpeed, from: 0.3, to: 1,
							afterFinish: function() {
								this.animating=false;
								this.updateCounter();
							}.bind(this)
						});
					}.bind(this)
				});
			}.bind(this)
		});
		
	},
	
	moveLeft: function() {
		if (this.currentPage<=1) {
			return;
		}
		
		if (this.animating) {
			return;
		}
		
		this.currentPage--;
		this.animating=true;
		
		new Effect.Fade(this.movible, { duration: this.options.animSpeed, from: 1, to: 0.3, 
			afterFinish: function() {
				new Effect.Move(this.movible, { duration: this.options.animSpeed, mode: 'relative', x: this.offset,
					afterFinish: function() {
						new Effect.Appear(this.movible, { duration: this.options.animSpeed, from: 0.3, to: 1,
							afterFinish: function() {
								this.animating=false;
								this.updateCounter();
							}.bind(this)
						});
					}.bind(this)
				});
			}.bind(this)
		});
	}
});
