var FUTLib = window.FUTLib || {}

FUTLib.rotativoDeChamadas = {
	
	objects : {},
  navMSIE : !!navigator.userAgent.match(/MSIE/g),
  
  botoesTxts : {
    next : 'proximo',
    prev : 'anterior',
    stop : 'parar',
    play : 'executar'
  },
  botoesRefClickUOL : '',
  timer : 10,
  
  init : function(args){
		this.show(args);
  },
	
	show : function(args){
    if(typeof mostrabanner == 'undefined')
      mostrabanner = 0;
		
		this.objects[args.id] = this.newRotativoDeChamadas(args);
	},
	
	newRotativoDeChamadas : function(args){
		
		var obj = FUTLib.rotativoDeChamadas;
		var objId = args['id'];
		var getObjPainel = function(){return obj.objects[objId]}
		var painel = document.getElementById(objId);
		var rotativo = {
		ativado : 0,
		anterior : 0,
		proximo : 0,
		timeOut : null,
		painel : null,
		itens : null,
		botoes : null,
		animando : false,
		banner : document.createElement('div'),
		contaTrocas : 0,
		listar : args['lista'] || false,
		listaEle : null,

	    timer : args['timer'] || obj.timer,
	    botoesRefClickUOL : args['botoesRefClickUOL'] || obj.botoesRefClickUOL,
	    botoesTxts : args['botoesTxts'] || obj.botoesTxts,
	    
	    showBanner : (function(){
				if(typeof args['showBanner'] != "undefined")
					return args['showBanner']
				else
					return showBanner = (document.cookie.indexOf('rotativoDeChamadasNoBanner' + objId + '=1')==-1) ? true : false
			})(),
	
	    itens : painel.getElementsByTagName('li'),
			
			criarRotativo : function(){
		    this.setNavegacao(this.ativado);
		
		    this.aplicarSombras();
		    
		    if (this.itens.length == 1)
		      args['startOff'] = true;
		    else
					this.montarBotoes();
		      
		    if(document.cookie.indexOf("rotativoDeChamadasStop" + objId + "=1")!=-1)
		      args['startOff'] = true;
		
		    if(!args['startOff'])
		      this.stopPlay();
		    else
		      this.setBtStopPlay('play');

				this.montarLista();

			},
			
			setNavegacao : function(i,direto){
		    if(!direto)
					this.ativado = (parseInt(i)+(this.ativado || this.itens.length))%this.itens.length;
		    this.anterior = ((this.ativado || this.itens.length)-1)%this.itens.length;
		    this.proximo = ((this.ativado || this.itens.length)+1)%this.itens.length;
			},
			
		  stopPlay : function(replace){
		    if ((!replace && this.timeOut == null) || (replace && this.timeOut != null)) {
		      clearInterval(this.timeOut);
		      this.timeOut = setInterval(function(){
		        getObjPainel().navegar(1);
		      }, this.timer * 1000);
		      document.cookie="rotativoDeChamadasStop" + objId + "=0; path=/"; 
		      this.setBtStopPlay('stop');
		    } else {
		      document.cookie="rotativoDeChamadasStop" + objId + "=1; path=/"; 
		      clearInterval(this.timeOut);
		      this.timeOut = null;
		      this.setBtStopPlay('play');
		    }
		  },
		  
		  setBtStopPlay : function(status){
		    if (this.botoes != null) {
		      var bt = this.botoes.getElementsByTagName('a')[1];
		      bt.className = 'bt' + status;
		      bt.innerHTML = this.botoesTxts[status];
		    }
		  },

		  montarBotoes : function(){
		    this.botoes = document.createElement('div');
		    this.botoes.className="botoesNavegacao";
		    this.writeBotoesHTML();
		    painel.appendChild(this.botoes);
		  },
			
			montarLista : function(){
				if(this.listar && this.itens.length > 1){
					if(this.listaEle == null){
						this.listaEle = document.createElement('div');
						this.listaEle.className = 'lista';
						obj.events.add(this.listaEle,'click',
			        function(e){
						    obj.events.preventDefault(e);
								if(e.srcElement && !e.target)
						      e.target=e.srcElement;
								if(e.target.href && getObjPainel().animando==false && getObjPainel().ativado != parseInt(e.target.innerHTML,10)-1)

									getObjPainel().navegar(null,e.target.innerHTML);
							}
			      );
						painel.appendChild(this.listaEle);
					}
					var html = '';
					for(var i=1; i<=this.itens.length; i++)
						html += '<a href="'+this.itens[(i-1)].getElementsByTagName('a')[0].href.replace(/(^.*?click\.fut.*?rf\=).*?(&u\=.*?)$/g,'$1'+this.botoesRefClickUOL+'$2')+'" ' + (this.ativado == (i-1) ? ' class="sel"' : '') + ' metricOff="true">' + i + '</a>';
					this.listaEle.innerHTML = html;
				}
			},
			
		  aplicarSombras : function(){
		    var sombra = document.createElement('div');
		    sombra.className='sombra';
		    
		    for(var i=0;i<this.itens.length;i++){
		      if(i>0)
		        this.itens[i].className+=' desativado';
		      this.itens[i].appendChild(sombra.cloneNode(true));
		    }
		  },
		  
		  writeBotoesHTML : function(){
		    this.botoes.innerHTML ="<a metricOff='true' rel='-1' href='"+this.itens[this.anterior].getElementsByTagName('a')[0].href.replace(/(^.*?click\.fut.*?rf\=).*?(&u\=.*?)$/g,'$1'+this.botoesRefClickUOL+'$2')+"' class='anterior' name='"+this.botoesRefClickUOL+"'>"+this.botoesTxts.prev+"</a>\
		      <a metricOff='true' rel='0' href='"+this.itens[this.ativado].getElementsByTagName('a')[0].href.replace(/(^.*?click\.fut.*?rf\=).*?(&u\=.*?)$/g,'$1'+this.botoesRefClickUOL+'$2')+"' class='' name='"+this.botoesRefClickUOL+"'></a>\
		      <a metricOff='true' rel='+1' href='"+this.itens[this.proximo].getElementsByTagName('a')[0].href.replace(/(^.*?click\.fut.*?rf\=).*?(&u\=.*?)$/g,'$1'+this.botoesRefClickUOL+'$2')+"' class='proximo' name='"+this.botoesRefClickUOL+"'>"+this.botoesTxts.next+"</a>";
				
		    var aHrefs = this.botoes.getElementsByTagName('a');
			 
			 //alert(this.botoes.innerHTML);
		
				for(var i=0;i<aHrefs.length;i++){
		      obj.events.add(aHrefs[i],'click',
		        function(e){getObjPainel().btNavegacaoClick(e)}
		      );
		    }
		
		  },
		
		  btNavegacaoClick : function(e){
		    obj.events.preventDefault(e);
				if(e.srcElement && !e.target)
		      e.target = e.srcElement;
		    var target = e.target;
				while(target.parentNode != this.botoes)
					target = target.parentNode;
				if (target.rel == 0)
		      this.stopPlay();
		    else if(this.animando==false) {
					setTimeout(function(){      
					      getObjPainel().navegar(target.rel);
					      getObjPainel().stopPlay(true);
					},30);
		    }
		  },
			
		  fadeIO : function(item, io, callback){
		    if (io) {
		      item.style.opacity = 0;
		      item.style.filter = "Alpha(Opacity=0)";
		    }else{
		      item.style.opacity = 1;
		      item.style.filter = "Alpha(Opacity=100)";
		    }
		    this.animando = true;
		    for (var i = 1; i <= 5; i++) {
		      setTimeout(function(y){
		        return function(){
		          if (obj.navMSIE)
								item.style.filter = "Alpha(Opacity=" + (io?20*y:100-20*y) + ")";
		          else 
		            item.style.opacity = (io?.2*y:1-.2*y);
		          if (y == 5){
								getObjPainel().animando = false;
		            if(typeof callback == "function")
		              callback();
		          }
		        }
		      }(i), 50 * i)
		    }
		  },
		  
		  fecharBanner : function(){
		    document.cookie="rotativoDeChamadasNoBanner" + objId + "=1; path=/"; 
		    this.showBanner = false;
		    clearTimeout(this.bannerFadeOutTimer);
		    this.bannerFadeOut();
		  },
		  
		  bannerFadeOut : function(){
		    this.fadeIO(this.banner,false,function(){
		      getObjPainel().banner.style.display='none';
		      getObjPainel().botoes.style.display='block';
		    });
		    this.fadeIO(this.botoes,true,null);
		  },
		  
		  navegar : function(to,direto){
				var desativar = this.ativado;
				if(!to)
					this.ativado = parseInt(direto,10)-1;
		    this.removerBanner = false;
		    this.contaTrocas++;
		
		    if (mostrabanner == 1 && this.showBanner && this.contaTrocas > 0 && this.contaTrocas % this.itens.length == 0) {
					this.banner.style.display='block';
		      this.banner.className='bannerRotativo';
		      //antigo -> this.banner.innerHTML = '<a href="'+mostrabannerLINK+'" target="_blank"><img src="'+mostrabannerIMG+'" border="0" /></a><div class="rodape"><img src="http://home.img.uol.com.br/h3/pub_h_120_b.gif" class="txtPublicidade" border="0" /><a href="javascript:void(0)" onclick="FUTLib.rotativoDeChamadas.objects.' + objId + '.fecharBanner()"><img src="http://home.img.uol.com.br/h3/banner-fechar.gif" border="0" /></div>';
					//this.banner.innerHTML = '<a href="'+mostrabannerLINK+'" target="_blank"><img src="'+mostrabannerIMG+'" border="0" /></a><div class="rotativoBannerRodape"><span>Publicidade</span><a href="javascript:void(0)" onclick="FUTLib.rotativoDeChamadas.objects.' + objId + '.fecharBanner()"></a></div>';
		      
				painel.appendChild(this.banner);
		      this.fadeIO(this.banner,true,function(){
		        getObjPainel().botoes.style.display='none';
		      });
		      this.fadeIO(this.botoes,false,null);
		      if(this.timeOut != null)
		        getObjPainel().bannerFadeOutTimer = setTimeout(function(){getObjPainel().bannerFadeOut()},getObjPainel().timer*1000);
		
		    } else {

					this.setNavegacao(to,direto);
		

		      this.itens[this.ativado].className = this.itens[this.ativado].className.replace(/desativado/g, '');
		      this.itens[this.ativado].style.zIndex = 3;
		      this.itens[desativar].style.zIndex = 4;
		      this.itens[this.ativado].style.opacity = 1;
		      this.itens[this.ativado].style.filter = "none";
		
		      this.fadeIO(this.itens[desativar],false,function(){
			        if (obj.navMSIE) 
			          getObjPainel().itens[desativar].style.filter = getObjPainel().itens[desativar].style.filter = 'none';
			        getObjPainel().itens[desativar].className = 'desativado';
			        getObjPainel().itens[desativar].style.zIndex = 2;
						});
		
		      this.writeBotoesHTML();
		      if (this.timeOut == null) 
		        this.setBtStopPlay('play');
		      else 
		        this.setBtStopPlay('stop');
		
		    }
				this.montarLista();
		  }

		};

		rotativo.criarRotativo();
		return rotativo;
		
	},
  
  events : {

    /**
     * Retorna false para os eventos padroes
     * @param {Object} e Evento
     */
    preventDefault : function(e){
      if(e.preventDefault) e.preventDefault();
      else e.returnValue = false; 
    }, 
    
    /**
     * Adicionar eventos
     * @param {Object} elem Elemento HTML
     * @param {String} event Evento (click, mouseover, mouseout, ...)
     * @param {Function} fun Função adicionada ao evento
     */
    add : function(elem,event,fun){
      if(document.attachEvent)
        elem.attachEvent('on'+event,fun);
      else if(document.addEventListener)
        elem.addEventListener(event,fun,false);
    }
  
  }
  
}

