var GaleriaActions = Class.create ({

	ul: 'galeria-lista',
	image: 'galeria-image',
	current: 'galeria-current',
	className: 'ativo',
	baseWidth: 0,
	thumbWidth: 92 + 13,
	list: null,
	
	images: [],
	
	i: 0,
	total: 0,
	totalPages: 1,
	currentPage: 0,
	itensPerPage: 0,
	isPlaying: false,
	timeout: true,
	seconds: 0,
	
	pic: function (index)
	{
		this._update ( index );
	},
	next: function (e)
	{
		this._update ( this.i + 1 );
	},
	prev: function (e)
	{
		this._update ( this.i - 1 );
	},
	page: function (index)
	{
		this._updatePage ( index );
	},
	nextPage: function ()
	{
		this._updatePage ( this.currentPage + 1 );
	},
	prevPage: function ()
	{
		this._updatePage ( this.currentPage - 1 );
	},
	slideshow: function ( seconds )
	{
		clearTimeout ( this.timeout );
		
		if (seconds === undefined)
			return;
		this.seconds = seconds;
		
		this.isPlaying = this.isPlaying ? false : true;
		
		if (this.isPlaying)
			this.next ();
	},
	initialize: function ()
	{
		Event.observe (document, 'dom:loaded', this._onDomReady.bindAsEventListener (this) );
	},
	_onDomReady: function (evt)
	{
		//this.current = $(this.current);
		this.image = $(this.image);
		this.image.observe ('load',  this._onLoad.bindAsEventListener (this) );
		this.image.observe ('error', this._onError.bindAsEventListener (this) );
		
		this.ul = $(this.ul);
		this.ul.makePositioned ();
		this.ul.cleanWhitespace ();
		this.ul.setStyle ({width: (this.ul.childElements().length * this.thumbWidth)+'px'});
		this.list = this.ul.childElements();
		for (var i = 0; i < this.list.length; i++)
		{
			var a = this.list[i].firstDescendant ();
			if (a.tagName != 'A')
				continue;
			a.href = 'javascript:Galeria.pic ('+ i +');';
			var img = a.firstDescendant ();
			this.images.push ( img.src.replace (/thumbs\//gi, '') );
		}
		this.total = this.images.length;
		// Paginação
		$(this.ul.parentNode).setStyle ({overflow: 'hidden'});
		this.baseWidth = parseInt( $(this.ul.parentNode).getWidth () );
		this.itensPerPage = Math.floor(this.baseWidth / this.thumbWidth);
		this.totalPages = Math.ceil ( this.total / this.itensPerPage );
		// Binda as ações das flechinhas do teclado
		Event.observe (document, "keydown", this._onKeyDown.bindAsEventListener (this));
		
		// Pega a ancora e acha a foto
		var ancora = new String (window.location);
		ancora = ancora.replace (/(.*)?#/gi, '')
		ancora = parseInt (ancora);
		if ( !isNaN (ancora) )
			this._update (ancora);
	},
	_update: function ( index )
	{
		// Não deixa o index ser menor que zero ou maior que o total
		index = parseInt (index);
		if (index < 0)
			index = this.total - 1;
		if (index > this.total - 1)
			index = 0;
		this.i = index;
		// Atualiza a foto atual no layout
		//this.current.update (this.i + 1);
		// Deixa selecionado o li correto
		for (var i = 0; i < this.list.length; i++)
		{
			if (i == index)
				this.list[i].addClassName (this.className);
			else
				this.list[i].removeClassName (this.className);
		}
		// Gera o permalink para esta página
		window.location.replace ('#'+index);
		// Mostra a imagem na tag correta
		this.image.src = this.images[index];
		// Calcula a pagina que o index está e atualiza a paginação
		index = Math.floor (index / this.itensPerPage );
		this._updatePage ( index );
	},
	_updatePage: function ( index )
	{
		index = parseInt (index);
		if (index < 0)
			index = this.totalPages - 1;
		if (index > this.totalPages - 1)
			index = 0;
		this.currentPage = index;
		
		index = this.thumbWidth * this.itensPerPage * this.currentPage * -1;
		
		this.ul.morph ('left:'+index+'px');
	},
	_onKeyDown: function (evt)
	{
		switch (evt.keyCode)
		{
			case 37 : // Flecha da esquerda
				this.pic ( --this.i );
				break;
			case 39 : // Flecha da direita
				this.pic ( ++this.i );
				break;
		}
	},
	_setTimeout: function ()
	{
		if (this.seconds === undefined)
			return;	
	
		clearTimeout ( this.timeout );
		this.timeout = setTimeout (this.next.bindAsEventListener (this), this.seconds * 1000);
	},
	_onLoad: function (evt)
	{	
		evt.target.removeAttribute ('height')
		
		if (this.isPlaying)
			this._setTimeout ();
	},
	_countErr: 0,
	_onError: function (evt)
	{
		if (this.isPlaying && ++this._countErr > 2)
			this.next ();
	}
});

var Galeria = new GaleriaActions ();