//Classe para fading de imagens	
//POliveira 2011
var FadeSlideshow = new Class({
    options: {
		images: new Array(), //array com os nomes das imagens
		links : new Array(), //links para cada imagem
		duracao: 2000, //duração da transição
		espera: 5000, //espera entre transições
		auto: true, //manual ou automático
		transition : Fx.Transitions.Sine.easeOut //Linear, //Sine.easeOut,
    },
    
    initialize: function(contentor, options){
        this.setOptions(options);
        this.vDiv = 1; //controle de posição do slide visivel 0 - esquerda, 1 - dta
		this.dir = 1; //controle de direção 0 - vai para a direita, 1 - vai para a esquerda
		this.moving = false; //controlar se podemos avançar para a próxima
		this.waitControl = -1; //controlcar o avanço manual
		this.manualGoto = -999; //é para ir para este slide, se clickar
        this.imgs = new Array(); //as nossas imagens
		this.indicator = new Array(); //o indicador e comando de slide

		//contentor do slide da esquerda
        this.lSlide = new Element('div', {
            'id': 'lSlide',
            'class': 'divSld'
        });
		//contentor do slide da direita
        this.rSlide = new Element('div', {
            'id': 'rSlide',
            'class': 'divSld'
        });
		//"meter" no DOM
        this.lSlide.injectAfter(contentor);
        this.rSlide.injectAfter(contentor);
		//adicionar e configurar efeitos
		this.lSlide.effect  = new Fx.Morph(this.lSlide,{
			duration: this.options.duracao,
			transition: this.options.transition	
		});
		this.rSlide.effect  = new Fx.Morph(this.rSlide,{
			duration: this.options.duracao,
			transition: this.options.transition	
		});
		//guardar as imgs
        for (i = 0; i < this.options.images.length; i++) {
			//há dois métodos de obter as imagens, base de dados ou disco
			//daí esta diferenciação 
			//TODO: rever isto, parace-me desnecessário
			if (this.options.images[i].name)
			{
				this.imgs[i] = new Element('img', {
					'src': this.options.images[i].name,
					'class': 'sldItem'
				});
			}
			else
			{
				this.imgs[i] = new Element('img', {
					'src': this.options.images[i].src,
					'class': 'sldItem'
				});
			}
			this.imgs[i].selfId = i; //id interno da imagem, para ir buscar a imagem do link em cache (ver os métodos forceCache e imgClicked)
			this.imgs[i].link = this.options.images[i].link; //o link qd se clica na no banner
			this.imgs[i].mode = this.options.images[i].mode; //se 'p' é em shadowbox (popup) se 'd' é download
			this.imgs[i].addEvent('click', function(e)
			{
				this.imgClicked(e.target); //passa o click(neste caso o target, i.e. a própria imagem) na imagem para a func
			}.bind(this));
			if (this.imgs[i].link) this.imgs[i].set('styles',{'cursor':'pointer'}); //se for de clickar, mete o cursor certo
        };
		this.forceCache(); //carrega os links
		this.totalWidth = contentor.getSize().x; //a largura da janela do slide
		this.lSlide.setStyle('left',0); //posição inicial
		this.rSlide.setStyle('left',this.totalWidth);//posição inicial
        this.actual = -1;//Math.floor(Math.random() * i); <- para arrancar random
        this.prox = 0;
		//se + que 1 imagem, mostra e constrói o indicador
		if (this.imgs.length > 1)
		{
			this.indicator = this.setupIndicator();
			//ajuste da posição
			this.indicator.set('styles',{
				'top': 3,
				'right':3
			});
		this.indicator.inject(contentor.getParent());
		}
		//calcula e executa o arranque, se for o caso
		if (this.imgs.length > 1)
		{
        	this.setImg(this.dir);
		}
		else //mete só a imagem
		{
            this.imgs[0].inject(this.lSlide);
		}
        if (this.options.auto) this.start();
    },
	forceCache : function()
	{
		for (i=0; i < this.imgs.length;i++)
		{
			if (this.imgs[i].link && this.imgs[i].mode == 'p')
			{
				var im = new Element('img',{'id':'img_link'+i}); //<-i = id interno
				im.src = this.imgs[i].link;
				im.set('styles',{
					'display':'block',
					'position':'absolute',
					'left':-10000
				});
				im.inject(document.body);
			}
		}
	},
	imgClicked : function(img)
	{
		if (img.link)
		{
			if (img.mode == 'p')  //popup em shadowbox
			{
				var cont = new Element('div');
				cont.setStyles({
					'overflow':'hidden',
					'margin':'30px auto'
				});
				var imagem = new Element('img');
				imagem.src = img.link;
				imagem.set('styles',{'display':'block'});
				imagem.selfId = img.selfId; //<-- id enterno
				cont.adopt(imagem);
				cont.img = imagem;
				var c = this.shadowbox(cont);
				c(true);
			}
			else
			{//download
				var w = window.open(img.link);
			}
		}
		
	},
	//construir o indicador
	setupIndicator : function()
	{
		var indicatorContainer = new Element('div',{'class':'indicatorContainer'});
		var indicatorBed = new Element('div',{'class':'indicatorLightContainer'});
		indicatorBed.items = new Array();
		for (i = 0;i < this.imgs.length;i++)
		{
			var indImg = new Element('span',{'class':'indicator off'});
			indImg.indx = i;
			indImg.addEvent('click', function(e)
			{
				if (!e.target.hasClass('on')) this.gotoSlide(e.target.indx);
			}.bind(this));
			indicatorBed.items[i] = indImg;
			indImg.inject(indicatorBed);
		}
		indicatorBed.inject(indicatorContainer);
		var indArrow = new Element('span',{'class':'indArrow prev'});
		indArrow.addEvent('click', function(){
			this.dir = 0;
			this.gotoSlide(this.actual - 1);
		}.bind(this));
		indArrow.inject(indicatorContainer);
		var indArrow = new Element('span',{'class':'indArrow next'});
		indArrow.addEvent('click', function(){
			this.dir = 1;
			this.gotoSlide(this.actual + 1);
		}.bind(this));
		indArrow.inject(indicatorContainer);
		indicatorContainer.lights = indicatorBed;
		return indicatorContainer;
	},    
	displayIndicator : function()
	{
		if (!this.options.auto) return true;//<--não sei para que serve isto
		for (i = 0;i < this.indicator.lights.items.length;i++)
		{
			if (i == this.indicator.lights.items[this.prox].indx)
			{
				this.indicator.lights.items[this.prox].removeClass('off').addClass('on');
			}
			else
			{
				this.indicator.lights.items[i].removeClass('on').addClass('off');
			}
		}
		
	},
	gotoSlide : function (slide)
	{
		if (this.moving) return true;
		this.manualGoto = slide;
		$clear(this.waitControl);
		this.waitControl = -1;
		if (!this.moving) this.reStart();
	},
    setImg: function()
	{	
		if (this.manualGoto == -999)
		{	
			if (this.actual > this.imgs.length - 1) this.actual = 0;
			this.prox = this.actual + 1;
			if (this.prox > this.imgs.length - 1) this.prox = 0;
		}
		else
		{
			this.prox = this.manualGoto;
			if (this.prox > this.imgs.length - 1) this.prox = 0;
			if (this.prox < 0) this.prox = this.imgs.length - 1;
			this.actual = this.prox - 1;
			this.manualGoto = -999;
		}
		//actualizar o indicador
		this.displayIndicator();
		
        if (this.vDiv == 0) // esquerda visivel
		{
			this.rSlide.empty();
			if (this.dir) //vai para a esquerda
			{
				this.rSlide.effect.set({'left':this.totalWidth});
			}
			else //vai para a direita
			{
				this.rSlide.effect.set({'left':-this.totalWidth});
			}
            this.imgs[this.prox].inject(this.rSlide);
		}
		if (this.vDiv == 1) //dta visivel
		{
			this.lSlide.empty();
			if (this.dir) //vai para esquerda
			{
				this.lSlide.effect.set({'left':this.totalWidth});
			}
			else //vai para a direita
			{
				this.lSlide.effect.set({'left':-this.totalWidth});
			}
            this.imgs[this.prox].inject(this.lSlide);
        }
		
        this.toggle();
        this.actual++;
    },
    start: function(){
        this.waitControl = this.setImg.periodical(this.options.espera, this,this.dir);
    },
    toggle: function(){				
        if (this.vDiv == 0) //esq visivel
		{
	        this.moving = true;
			if (this.dir) //vai para esq
			{
				this.lSlide.fx = this.lSlide.effect.start({'left':-this.totalWidth}); 
				this.rSlide.effect.start({'left':0});
				this.lSlide.fx.chain(function()
				{
					this.reStart();
				}.bind(this));
			}
			else //vai para dta
			{
				this.lSlide.fx = this.lSlide.effect.start({'left':this.totalWidth});
				this.rSlide.effect.start({'left':0});
				this.lSlide.fx.chain(function()
				{
					this.reStart();
				}.bind(this));
			}
            this.vDiv = 1;
			return true;
        }
        if (this.vDiv == 1) //dta visivel
		{
	        this.moving = true;
			if (this.dir) //vai para esq
			{
				this.rSlide.fx = this.rSlide.effect.start({'left':-this.totalWidth});
				this.lSlide.effect.start({'left':0});
				this.rSlide.fx.chain(function()
				{
					this.reStart();
				}.bind(this));
			}
			else //vai p/ dta
			{
				this.rSlide.fx = this.rSlide.effect.start({'left':this.totalWidth}); //1
				this.lSlide.effect.start({'left':0});//0
				this.rSlide.fx.chain(function()
				{
					this.reStart();
				}.bind(this));
			}
            this.vDiv = 0;
			return true;
        }
    },
	reStart : function()
	{
        this.moving = false;		
		if (this.waitControl != -1) return true;
		this.setImg(this.dir);
		this.waitControl = this.setImg.periodical(this.options.espera,this,this.dir);
	},
	shadowbox : function(content)
	{
		var wShadow = new Element('div',{'class':'wShadow'});
		var sizeDoc = $(document.body).getScrollSize();
		wShadow.setStyles({
				'position':'absolute',
				'width':sizeDoc.x,
				'height':sizeDoc.y,
				'opacity':0,
				'left':0,
				'z-index':1100
		});
		wShadow.injectTop($(document.body));
		wShadow.ef = new Fx.Morph(wShadow,
		{
			duration:500
		});
		wShadow.addEvent('click',function(){
			content.show(false);
		});
		content.inject(wShadow);
		
		var size = content.img.measure(function()
		{
			var a = this.getSize();
			return a;
		});
		size = $('img_link'+content.img.selfId).getSize();
		content.setStyles({
			'width':size.x,						
			'height':size.y,
			'opacity':1,
			'background':'#fff',
			'z-index':1101
		});

		var closeBut = new Element('div',{'class':'wsCloseBtn'});
		closeBut.set('styles',{
			'left':(size.x /2 )+(sizeDoc.x/2) -27,
			'top':32
		});
		closeBut.inject(content);
		
		content.show = function(how)
		{
			if (how)
			{
				wShadow.ef.start({'opacity':1});		
			} 
			else
			{
				wShadow.ef.start({'opacity':0});
				wShadow.ef.chain(function(){
					this.element.empty();
					this.element.dispose();
					
				});
				
			}
		}
	return content.show;	
	}
});

FadeSlideshow.implement(new Options);
