// JavaScript Document

Galeria = function(container, imagens, options){
	
	var imagens;
	var container;

	this.timerID = null;
	this.timerRunning = false;
	this.imagemActual = 0;
	this.replace = null;
	this.controller = null;
	this.startText = 'Start';
	this.stopText = 'Stop';
	this.delay = 2000;
	
	this.imagens = imagens;
	this.container = $(container);	
	
//	alert(this.container.id);
	
	this.mainImg = null;
	
	if(options){
		if(options.delay)
			this.delay = options.delay;
		if(options.replace)
			this.replace = options.replace;
		if(options.controller){
			if($(options.controller.elem) != null){
				this.controller = $(options.controller.elem);
				this.controller.addEvent('click', this.startStop.bindWithEvent(this));
			}
			this.startText = options.controller.stopped;
			this.stopText = options.controller.running;
		}
	}
	this.init();
	
}

Galeria.prototype.init = function(){
	
//	alert(this.container.id);
	
	if(this.mainImg == null){
		this.mainImg = new Element('img');
		this.mainImg.inject($(document.body));
		this.container.grab(this.mainImg);
		this.caption = new Element('div');
		this.caption.inject($(document.body));
		this.container.grab(this.caption);
	}
	this.imagemActual = 0;
	this.show(null, this.imagemActual);
	
	this.imagens.each(function(item, idx){
		new Asset.image(this.getLargeImage(idx));
		item.getParent('a').addEvent('click', this.show.bindWithEvent(this, idx));					
	}.bind(this));
}

Galeria.prototype.getLargeImage = function(idx){
	if(this.replace == null)
		return this.imagens[idx].get('src');
	else
		return this.imagens[idx].get('src').replace(this.replace[0], this.replace[1]);
}


Galeria.prototype.show = function(elem, idx){
//	alert(x2);
	
	this.imagens[this.imagemActual].removeClass('activo');
	this.imagemActual = idx;
	this.mainImg.set('src', this.getLargeImage(this.imagemActual));
	this.imagens[this.imagemActual].addClass('activo');
	this.caption.set('text', this.imagens[this.imagemActual].get('alt'));
	return false;
}

/**
* Avança e mostra o próximo
*/
Galeria.prototype.next = function(){
	//alert(this.imagemActual);
	
	this.imagens[this.imagemActual].removeClass('activo');
	this.imagemActual++;
	if(this.imagemActual >= this.imagens.length)
		this.imagemActual = 0;
		
	this.show(null, this.imagemActual);
}

/**
* Arranca ou para o slideshow
*/
Galeria.prototype.startStop = function(){
	if(!this.timerRunning)
		this.start();
	else
		this.stop();
	return false;
}

Galeria.prototype.start = function(){

	this.controller.set('text', this.stopText);
	this.timerRunning = true;
	this.timerID = this.next.periodical(this.delay, this);
}

Galeria.prototype.stop = function(){

	this.controller.set('text', this.startText);
	this.timerRunning = false;
	$clear(this.timerID);
	this.timerID = null;
}

