/** 
 * @projectDescription Script para montar o HTML da galeria de jogos. Montando página de thumbs e página de visualição de fotos
 *
 * @author   Roberto Robson (Bode) rnogueira@uolinc.com
 * @update   Marcelo Favoratti <mmendonca@uolinc.com> (2008-12-19)
 * @version  2.4
 * @since	 2.0
 */

/**
 * Objeto principal da galeria de jogos.
 * O efeito no scroll de thumbs depende do objeto setAndAnimate
 * @type {Object}
 */
galeriasTPL=function(){

  /** Verifca exibicao do Banner */
  this.viewPub = false;
  
  /** HTML da publicidade */
  this.HTML_publicidade = document.createElement("div");

  /** Valor inicial do numero randomico */
  this.randomNum = 0;

  /** Inverte a ordem das fotos ASC||DESC */
  if(galeriaInfo[0]['ordem']=='ASC') {
      galeriaInfo.reverse();
  }

  /** Indica a página de thumbs atual */
  this.sortPage=((typeof(sortPage)=="undefined")?0:parseInt(sortPage));

  /** Na página de thumbs, quantidade a ser exibido */
  this.qtThumbs=20;

  /** Modelo da página a ser formatado "thumbs|foto" */
  this.modelo="foto";

  /** Quantidade de thumbs possiveis na regua de navegação. Calculado automaticamente */
  this.qtThumbsRegua=0;

  /** Inicio da listagem de thumbs na regua de navegação */
  this.thumbsReguaStart=((typeof(thumbsReguaStart)=="undefined")?0:parseInt(thumbsReguaStart));

  /** Fim da listagem de thumbs na regua de navegação */
  this.thumbsReguaEnd=((typeof(thumbsReguaEnd)=="undefined")?0:parseInt(thumbsReguaEnd));
  
  /** Resolução atual da galeria "800|1024" */
  this.screenSize=1024;

  /** Slideshow 1 = ativado | 0 = desativado */
  this.slideshow=((typeof(slideshow)=="undefined")?0:parseInt(slideshow));
  
  /** Tempo de intervalo em milesegundos do slideshow */
  this.slideshowTimer=4000;

  /** Função setTimeout do slideshow */
  this.slideshowWatch;
  
  /** Travar o metodo proAnt que faz a naveção de imagens uma-a-uma quando a regua de thumbs não estiver exibindo a imagem atual. 0 = destravado | 1 = travado */
  this.proAntTravado=0;
  
  /** informa quando o script setAndAnimate estiver carregado */
  this.setandanimateLoaded=0;
  
  /** Verifica orientacao da Foto (vertical ou horizontal) */
  this.verticalImage = false;

  
  /** 
   * Inicialização, obrigatorio antes da chamada de qualquer outro metodo
   * @type {Method}
   */
    this.init=function(){
        /** Foto atual em visualização */
        if(typeof(abrefoto)=="undefined" || !/\d/.test(abrefoto) || parseInt(abrefoto)<1 || parseInt(abrefoto)>parseInt(galeriaInfo[0]['totalImagens'])) {
            if(galeriaInfo[0]['fotoInicial']!='0') {
                if (galeriaInfo[0]['ordem'] == 'ASC') {
                    this.gFoto = parseInt(galeriaInfo[0]['totalImagens']) + 1 - parseInt(galeriaInfo[0]['fotoInicial']);
                }
                else {
                    this.gFoto = parseInt(galeriaInfo[0]['fotoInicial']);
                }
            }
            else {
                this.makeRandomNum();
                this.gFoto = this.randomNum;
            }
        }
        else {
            if (galeriaInfo[0]['ordem'] == 'ASC') {
                this.gFoto = parseInt(galeriaInfo[0]['totalImagens']) + 1 - (abrefoto * 1);
            }
            else {
                this.gFoto = abrefoto * 1;
            }
        }

        /** Mostra banner **/
        try {
            if(mostrabanner==1) {
                this.makeRandomNum();
            }
        } catch(e) {}

        /** Resolucao **/
       this.resolution();
    };


  /** 
   * Detecta resolucao do monitor
   * @type {Method}
   */
    this.resolution = function(){
        if (document.getElementsByTagName('body')[0].className.indexOf("sx1024") == -1) 
			document.getElementsByTagName('body')[0].className += " sx" + this.screenSize;
    };

  /** 
   * Executa os metodos necessários para montar o HTML da galeria baseado no modelo
   * @type {Method}
   */
  this.show=function(){
    if(galeriaInfo[0]['menuTab'].length>0) {
        this.galMenu();
    }
    
    if(this.modelo=="thumbs"){
      this.showThumbs().showPages();
    }else{
      if(this.setandanimateLoaded==0){

        /** 
         * Carrega script setAndAnimate
         */
        var HTML_JS=document.createElement('script');
        HTML_JS.src="http://lib.uol.com.br/setandanimate/setandanimate.js?timestamp="+new Date().getTime();

        if(navigator.userAgent.indexOf("Safari")==-1 && navigator.userAgent.indexOf("Opera")==-1){
          try{
            HTML_JS.addEventListener('load',function(){
              galeriasTPL.setandanimateLoaded=1;
              galeriasTPL.show();
            },true);

          }catch(e){
            try{
              HTML_JS.onreadystatechange = function () {
                if (HTML_JS.readyState == 'loaded'){
                  galeriasTPL.setandanimateLoaded=1;
                  galeriasTPL.show();
                }
              }
            }catch(e){}

          }
        }else{
          jsSetAndAnimateTimer=setInterval(function(){
            if(document.readyState=="complete" || document.readyState=="loaded"){
              clearTimeout(jsSetAndAnimateTimer);
              galeriasTPL.setandanimateLoaded=1;
              galeriasTPL.show();
            }
          },10);
        }
	      document.getElementsByTagName('head')[0].appendChild(HTML_JS);
        
      }else{
        this.showMenuFloat().showThumbsRegua().showImage();
      }
    }
  };

  /** 
   * Ativa e desativa Slideshow
   * @type {Method}
   */
  this.changeSlideShow=function(){
    if(this.slideshow==0){
      this.slideshow=1;
      document.getElementById('inputSlideshow').checked=true;
    }else{
      this.slideshow=0;
      document.getElementById('inputSlideshow').checked=false;
    }
      
    this.checkSlideShow();
  };

  
  /** 
   * Verifica o status do slide show, se ativado executa slideshowWatch
   * @type {Method}
   */
  this.checkSlideShow=function(){
    clearTimeout(this.slideshowWatch);
    if(this.slideshow==1)
      this.slideshowWatch=setTimeout(function(){galeriasTPL.proAnt(-1)},this.slideshowTimer);
  };
  
  /** 
   * Executado deopois da imagem ter carregado
   * @type {Method}
   */
  this.imageLoaded=function(t){
    this.checkSlideShow();

    document.getElementById('fullImageSrc').style.display="block";
    document.getElementById("fotoLegenda").className="carregado";
	var fixLeg = Math.round(document.getElementById("fotoLegenda").offsetHeight/2); //calcula a metade do tamanho da legenda

    if(!this.verticalImage) {
        document.getElementById('fullImage').style.height = this.getHeight(document.getElementById('fullImageSrc')) + this.getHeight(document.getElementById('fotoLegenda')) + "px";
        if(galeriaInfo[0]["mp3File"]!="") {
            document.getElementById('galeriaPlayer').style.top =  ((navigator.userAgent.indexOf("MSIE 6")>=0) ? -50 : -24) - this.getHeight(document.getElementById('fotoLegenda')) + "px";
        }
    }
    else {
        document.getElementById('fullImage').style.height = this.getHeight(document.getElementById('fullImageSrc')) + "px";
        document.getElementById('fotoLegenda').style.top = parseInt(parseInt(galeriaInfo[this.gFoto]['height']) / 2) - fixLeg + "px"; //corrije a altura da leganda, levando em consideração a metade da sua altura
		if(galeriaInfo[0]["mp3File"]!="") {
            document.getElementById('galeriaPlayer').style.top =  (navigator.userAgent.indexOf("MSIE 6")>=0) ? "-51px" : "-44px";
        }
    }
    document.getElementById("corpo").style.height =  "auto";
    
    /** 
     * No IE6 é necessário definir o tamanho 'height' das setas anterior e proxima utilizado o tamanho da imagem atual
     */
    if(navigator.userAgent.indexOf("MSIE 6")>=0) {
      document.getElementById('setaEsq').style.height=document.getElementById('setaDir').style.height=document.getElementById('fullImageSrc').offsetHeight+"px";
      setTimeout(function() {
                        document.getElementById('barraFoto').style.top=galeriasTPL.getHeight(document.getElementById('boxFullImage')) - 25 + "px";
                    },100);
    }
    
    document.getElementById('fullImage').className="carregado";
  };
  
  /** 
   * Muda a resolução da página - não é mais utilizada
   * @type {Method}
   */
  this.switchScreenSize=function(){return this};
  
  /**
   * Seleciona imagens clicando no thumb
   * @type {Method}
   */
  this.selectImage=function(){
    this.gFoto=arguments[0];
    this.showImage();
    this.selecionaThumbAtivo();
  };
  
  /**
   * Monta HTML do menu float
   * @type {Method}
   */
  this.showMenuFloat=function(){
    HTML_fechado=document.createElement('div');
    HTML_fechado.id="menu-fechado";
    HTML_fechado.className="menu-float";
    HTML_fechado.innerHTML="<a href=\"javascript:galeriasTPL.switchMenu()\" class=\"menu-top\">Abrir o menu</a><div class=\"menu-bottom-bg\"></div>";
    document.getElementById('corpo').appendChild(HTML_fechado);
    HTML_aberto=document.createElement('div');
    HTML_aberto.id="menu-aberto";
    HTML_aberto.className="menu-float";
    HTML_aberto.innerHTML="<a href=\"javascript:galeriasTPL.switchMenu()\" class=\"menu-top\">Fechar o menu</a>";
        	
	/* não clona mais o menu, apenas move diretamente pro local desejado */
	/*HTML_menu=document.getElementById('menu').cloneNode(true);
    document.getElementById('menu').parentNode.removeChild(document.getElementById('menu'));
    HTML_aberto.appendChild(HTML_menu);*/
	HTML_aberto.appendChild(document.getElementById('menu'));
	
	/* cria a div dinamicamente */
	/*HTML_aberto.innerHTML+="<div class=\"menu-bottom-bg\"/>";*/
	HTML_bgBottom=document.createElement('div');
	HTML_bgBottom.className='menu-bottom-bg';
	HTML_aberto.appendChild(HTML_bgBottom);

    document.getElementById('corpo').appendChild(HTML_aberto);
    document.getElementById('menu').style.display = "block";
    return this;
  };
  
  /**
   * HTML dos thumbs
   * obs. página somente dos thumbs
   * @type {Method}
   */
  this.showThumbs=function(){
    var HTML="<dl>";
    startLoop=galeriaInfo[0]['totalImagens']-(this.sortPage*this.qtThumbs);
    endLoop=galeriaInfo[0]['totalImagens']-(this.sortPage*this.qtThumbs)-this.qtThumbs;
    dataThumbAnterior="";
    for(var i=startLoop;i>endLoop;i--){
      if(galeriaInfo[i]['date']!=dataThumbAnterior) 
        HTML+="<dt><div>"+galeriaInfo[i]['date']+"</div></dt>";
        HTML+="<dd><a href=\"?gFoto="+i+"\"><img src=\"http://j.i.uol.com.br/galerias/"+galeriaInfo[0]['plataformaDir']+"/"+galeriaInfo[i]['image'].replace("_f_","_t_")+"\" border=0 /></a></dd>";
      dataThumbAnterior=galeriaInfo[i]['date'];
      if(i==1)
        break;
    }
    HTML+="</dl><div class=\"endLine\"></div>";
    try { // Album não utiliza esse elemento
      document.getElementById('materia').innerHTML+=HTML;
    } catch(e) {}
    return this;
  };

  /**
   * HTML da paginacao dos thumbs
   * obs. página somente dos thumbs
   * @type {Method}
   */
  this.showPages=function(){
    totalPages=Math.floor(galeriaInfo[0]['totalImagens']/this.qtThumbs)+((galeriaInfo[0]['totalImagens']%this.qtThumbs>0)?1:0)-1;
    var HTML="<div id=\"paginacao\"><div class=\"paginas\">Páginas:";
    startPages=0;
    endPages=totalPages;
    if(totalPages>12){
      startPages=(this.sortPage<6)?0:this.sortPage-5;
      endPages=(this.sortPage<6)?12:this.sortPage+6;
      if(endPages>totalPages){
        startPages=totalPages-11;
        endPages=totalPages;
      }
    }
    for(i=startPages;i<=endPages;i++)
      HTML+="<a class=\""+((i==this.sortPage)?"ativa":"inativa")+"\" href=\"?sortPage="+i+"\">"+(i+1)+"</a>";
    HTML+="</div><div class=\"prx-ant\">";
    if(this.sortPage>0)
      HTML+="<a href=\"?sortPage="+(this.sortPage-1)+"\"><img src=\"http://img.uol.com.br/upsi_left_arrow.gif\" border=0> anterior</a>";
    if(this.sortPage>0 && this.sortPage<totalPages && totalPages>1)
      HTML+="&nbsp;|&nbsp;";
    if(this.sortPage<totalPages)
      HTML+="<a href=\"?sortPage="+(this.sortPage+1)+"\">próxima <img src=\"http://img.uol.com.br/upsi_right_arrow.gif\" border=0></a>";
    HTML+="</div></div>";
    try {
      document.getElementById('materia').innerHTML+=HTML;
    } catch(e) {}
    return this;
  };


  /**
   * HTML regua dos thumbs. Página de visualização
   * @type {Method}
   */
  this.showThumbsRegua=function(){
    if(!document.getElementById('thumbsRegua'))
      document.getElementById('boxGaleria').innerHTML+='<div id=\"thumbsRegua\"></div><div id="thumbsPreview"></div>';
    
    var HTML="<a href=\"javascript:void(0)\" id=\"thumbsReguaAnt\" onclick=\"galeriasTPL.scrollThumbs(1)\" class=\"ant\"></a>"+
          "<div id=\"thumbsReguaLista\">"+
          "<ul>";
    try{
	var useImage = (galeriaInfo[i]['thumb']!='') ? galeriaInfo[i]['thumb'] : galeriaInfo[i]['preview'];
	} catch(e) { var useImage = "" }
    HTML+="<li><a href=\"?gFoto="+this.gFoto+"\"><img src=\""+galeriaInfo[0]["imagePath"]+useImage+"\" /></a></li>";
    
    HTML+="</ul></div><a href=\"javascript:void(0)\" id=\"thumbsReguaPro\" onclick=\"galeriasTPL.scrollThumbs(-1)\" class=\"pro\"></a>";
    document.getElementById('thumbsRegua').innerHTML=HTML;

    /**
     * Define a quantidade de thumbs possiveis na regua a ser exibido
     */
    this.qtThumbsRegua=Math.floor(document.getElementById('thumbsReguaLista').offsetWidth/document.getElementById('thumbsReguaLista').getElementsByTagName('li')[0].offsetWidth);
    document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[0].parentNode.removeChild(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[0]);
    this.montarThumbsLista(0);
    this.centerThumbs();
    return this;
  };
  
  /**
   * Monta lista da regua de thumbs utilizando 'qtThumbsRegua' para saber quantos são possiveis.
   * @type {Method}
   * @param {Int} args.0 0 = sem movimento, >0 = cria thumbs na esquerda, <0 cria thumbs na direita
   */
  this.montarThumbsLista=function(){

    if(this.thumbsReguaStart==0)
      this.thumbsReguaStart=this.gFoto+Math.floor(this.qtThumbsRegua/2);
    if(this.thumbsReguaEnd==0)
      this.thumbsReguaEnd=this.gFoto-Math.floor(this.qtThumbsRegua/2);

    if(arguments[0]>0 && arguments[0]<this.qtThumbsRegua){
      this.thumbsReguaStart+=arguments[0];
      this.thumbsReguaEnd=this.thumbsReguaStart-arguments[0]+1;
      this.thumbsReguaRecalcular=1;
    }else if(arguments[0]<0 && arguments[0]*-1<this.qtThumbsRegua){
      this.thumbsReguaEnd+=arguments[0];
      this.thumbsReguaStart=this.thumbsReguaEnd+arguments[0]*-1-1;
      this.thumbsReguaRecalcular=1;
    }else{
      this.thumbsReguaRecalcular=0;
      this.thumbsReguaStart=parseInt(this.thumbsReguaStart)+arguments[0];
      this.thumbsReguaEnd=parseInt(this.thumbsReguaEnd)+arguments[0];
    }

    if(this.thumbsReguaStart>galeriaInfo[0]['totalImagens']){
      this.thumbsReguaStart=galeriaInfo[0]['totalImagens'];
      this.thumbsReguaEnd=this.thumbsReguaStart-this.qtThumbsRegua;
      if(this.thumbsReguaEnd<1)
        this.thumbsReguaEnd=1;
    }else if(this.thumbsReguaEnd<1){
      this.thumbsReguaStart=this.qtThumbsRegua;
      if(this.thumbsReguaStart>parseInt(galeriaInfo[0]['totalImagens']))
        this.thumbsReguaStart=parseInt(galeriaInfo[0]['totalImagens']);
      this.thumbsReguaEnd=1;
    }

    if(this.thumbsReguaStart-this.thumbsReguaEnd>=this.qtThumbsRegua)
      this.thumbsReguaEnd=this.thumbsReguaStart-(this.qtThumbsRegua-1);
      
    if(this.thumbsReguaStart==galeriaInfo[0]['totalImagens'])
      document.getElementById('thumbsReguaAnt').style.display="none";
    else
      document.getElementById('thumbsReguaAnt').style.display="block";

    if(this.thumbsReguaEnd==1)
      document.getElementById('thumbsReguaPro').style.display="none";
    else
      document.getElementById('thumbsReguaPro').style.display="block";

    HTML_ul=document.createElement('div');
    for (var i = this.thumbsReguaStart; i >= this.thumbsReguaEnd; i--) {
        var useImage = (galeriaInfo[i]['thumb'] != '') ? galeriaInfo[i]['thumb'] : galeriaInfo[i]['preview'];
        HTML_ul.innerHTML += "<li id=\"thumbId" + i + "\"><a onclick=\"galeriasTPL.selectImage(" + i + ")\" onmouseover=\"galeriasTPL.thumbsPreview(" + i + ",'visible')\" onmouseout=\"galeriasTPL.thumbsPreview(0,'hidden')\"><img src=\"" + galeriaInfo[0]["imagePath"] + useImage + "\" /></a></li>";
    }
    if(arguments[0]<0){
      document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].innerHTML+=HTML_ul.innerHTML;
    }else{
      document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].innerHTML=HTML_ul.innerHTML+document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].innerHTML;
      if(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li').length>this.qtThumbsRegua)
        document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.marginLeft=(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[this.thumbsReguaStart-this.thumbsReguaEnd+1].offsetLeft)*-1+"px";
    }
    
    this.selecionaThumbAtivo();
    
    if(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li').length>this.qtThumbsRegua){
      reguaMovimentoInicio=parseInt(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.marginLeft);
      reguaMovimentoFim=((arguments[0]<0)?(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li').length-this.qtThumbsRegua].offsetLeft)*-1:0);
      setAndAnimate.change({'objName':'thumbsScroller','propriedade':[document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style,'marginLeft','px'],'inicio':reguaMovimentoInicio,'fim':reguaMovimentoFim,'velocidade':0.90,'callback':function(){galeriasTPL.deleteThumbs();galeriasTPL.thumbsReguaRewrite()}});
    }
    
    if(this.thumbsReguaRecalcular==1){
      if(arguments[0]>0){
        this.thumbsReguaEnd=this.thumbsReguaStart-this.qtThumbsRegua+1;
      }else{
        this.thumbsReguaStart=this.thumbsReguaEnd+this.qtThumbsRegua-1;
      }
    }
    
  };
  
  /**
   * Evita imagens quebradas na regua de thumbs no IE 6
   * @type {Method}
   */
  this.thumbsReguaRewrite=function(){
    if(navigator.userAgent.indexOf("MSIE 6")>=0)
      document.getElementById('thumbsRegua').innerHTML=document.getElementById('thumbsRegua').innerHTML;
  };

  /**
   * Seleciona o thumb sendo a mesma imagem que esta sendo visualizada
   * @type {Method}
   */
  this.selecionaThumbAtivo = function(){
    for(var i=0;i<document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li').length;i++)
      document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[i].className="";

    if(document.getElementById('thumbId'+this.gFoto))
      document.getElementById('thumbId'+this.gFoto).className="ativo";
  };
  
  /**
   * deleta Thumbs na regua que estão escondidos e define a margem da regua para 0
   * @type {Method}
   */
  this.deleteThumbs=function(){

    delImgs=document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li').length-this.qtThumbsRegua;
    marginUl=parseInt(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.marginLeft);
    for(var i=0;i<delImgs;i++)
      document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[((marginUl==0)?this.qtThumbsRegua:0)].parentNode.removeChild(document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].getElementsByTagName('li')[((marginUl==0)?this.qtThumbsRegua:0)]);
   
    document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.marginLeft=0;
    this.proAntTravado=0;
  };

  /**
   * Define o parametro correto para a criação de thumbs
   * @type {Method}
   * @param {Int} args.0 
   */
  this.scrollThumbs=function(to){
    if (to > 0) {
        thumbsRestantes = galeriaInfo[0]['totalImagens'] - galeriasTPL.thumbsReguaStart;
    }
    else {
        thumbsRestantes = galeriasTPL.thumbsReguaEnd - 1
    }
    this.montarThumbsLista(((thumbsRestantes<this.qtThumbsRegua)?thumbsRestantes:this.qtThumbsRegua)*to);
  };
  
  /**
   * Monta HTML da imagem com barra superior
   * @type {Method}
   */
  this.showImage=function(){
    if(!document.getElementById('boxFullImage'))
	  document.getElementById('boxGaleria').innerHTML+="<iframe id=\"galeriaHit\" src=\""+galeriaInfo[0]['link'].replace(/(\/album)(.*?)$/g,'$1/')+"galerias-hit.jhtm?editoria="+galeriaInfo[0]['editoria']+"&galeria="+galeriaInfo[0]['galeria']+"&foto="+this.gFoto+"\"></iframe><div id=\"boxFullImage\"></div>";   //o regExp do src do iframe serve para pegar o caminho do álbum (sem o nome do arquivo)
      //document.getElementById('boxGaleria').innerHTML+="<iframe id=\"galeriaHit\" src=\"/galerias/galerias-hit.jhtm?editoria="+galeriaInfo[0]['editoria']+"&galeria="+galeriaInfo[0]['galeria']+"&foto="+this.gFoto+"\"></iframe><div id=\"boxFullImage\"></div>";
    
    fullImageOldSize="";
    if(document.getElementById('fullImage'))
      fullImageOldSize=document.getElementById('fullImage').offsetHeight;
      
    var HTML= '<div id="contador">Imagem '+this.counter(this.gFoto)+" de "+galeriaInfo[0]["totalImagens"]+'</div>'+
                    '<div id="fullImage" '+((fullImageOldSize!="")?' style="height:'+fullImageOldSize+'px" ':"")+' class="carregando">'+
                        '<a '+((navigator.userAgent.indexOf("MSIE 6")>=0)?'href="javascript:void(0)"':"")+' onclick="galeriasTPL.proAnt(1)" class="ant" id="setaEsq"></a>'+
                        '<a '+((navigator.userAgent.indexOf("MSIE 6")>=0)?'href="javascript:void(0)"':"")+' onclick="galeriasTPL.proAnt(-1)" class="pro" id="setaDir"></a>'+
                        '<div align="center">'+
                            '<img src="'+galeriaInfo[0]["imagePath"]+'/'+galeriaInfo[this.gFoto]["image"]+'" id="fullImageSrc" style="max-width:'+galeriaInfo[this.gFoto]["width"]+"px;max-height:"+galeriaInfo[this.gFoto]["height"]+'px" onload="galeriasTPL.imageLoaded()" border=0 />'+
                            '<p id="fotoLegenda" class="carregando">'+galeriaInfo[this.gFoto]["legenda"]+(typeof(galeriaInfo[this.gFoto]["url-foto"]) != "undefined" && galeriaInfo[this.gFoto]["url-foto"] != ""? '<a href="'+galeriaInfo[this.gFoto]["url-foto"].replace(" target=_blank","\" target=\"_blank")+'" class="mais">Mais</a>':'') +'<em>'+galeriaInfo[this.gFoto]["credito"]+'</em>'+(typeof(enquete)!="undefined" && enquete?'<a id="butvotar" href="javascript:vota('+this.counter(this.gFoto)+');">VOTAR NESTA FOTO</a><span id="verresult"><a href="javascript:resultado();">VER RESULTADO</a></span>':'')+'</p>'+ //adição do link da foto "MAIS" e dos botões de enquete (se houver)
                        '</div>'+
                    '</div>'+
                    '<div id="barraFoto">'+
                        '<div class="slideshow">'+
                            '<input type="checkbox" value=1 '+((this.slideshow==1)?'checked="checked"':"")+' onclick="galeriasTPL.changeSlideShow()" id="inputSlideshow">'+
                            '<a href="javascript:galeriasTPL.changeSlideShow()">SLIDESHOW</a>'+
                        '</div>'+
                        '<div class="divisao d1"></div>'+
                        '<div class="enviarEmail"><a href="javascript:document.email.submit()">ENVIAR POR E-MAIL</a></div>'+
                    '</div>';
    document.getElementById('boxFullImage').innerHTML=this.HTML_publicidade.innerHTML+HTML;
    this.HTML_publicidade.innerHTML="";
    document.getElementById('galeriaHit').src=galeriaInfo[0]['link'].replace(/(\/album)(.*?)$/g,'$1/')+"galerias-hit.jhtm?editoria="+galeriaInfo[0]['editoria']+"&galeria="+galeriaInfo[0]['galeria']+"&foto="+this.gFoto;

    // Largura Maxima das fotos de acordo com a resolucao (800 ou 1024)
    var imageBoxSize = (this.screenSize==1024) ? 956 : 736;
    // Corrige o tamanho das fotos no IE6 em resolucao 800
    if(navigator.userAgent.indexOf("MSIE 6")>=0) {
        document.getElementById('fullImageSrc').style.width = ((galeriaInfo[this.gFoto]["width"] <= imageBoxSize) ? galeriaInfo[this.gFoto]["width"] : imageBoxSize) + "px";
    }
    // Posiciona Legenda a direita nas fotos verticais
    if(galeriaInfo[0]['legendaPos']!='') {
        this.verticalImage = (galeriaInfo[this.gFoto]["height"] > galeriaInfo[this.gFoto]["width"]) ? true : false;
    }
    if(this.verticalImage) {
        document.getElementById('corpo').className = "rightLeg";
        document.getElementById('fotoLegenda').style.top = parseInt(parseInt(galeriaInfo[this.gFoto]['height']) / 2) - 20 + "px";
		//document.getElementById('fotoLegenda').style.paddingTop = parseInt(parseInt(galeriaInfo[this.gFoto]['height']) / 2) - 20 + "px"; //ajuste para legenda da foto sobre os botões anterior ou próximo
    }
    else {
        document.getElementById('corpo').className = "";
		document.getElementById('fotoLegenda').style.paddingTop = 0;
    }

    if(navigator.userAgent.indexOf("Opera")>=0) {
        document.getElementById('fullImageSrc').style.display="block";
    }
    else if(navigator.userAgent.indexOf("MSIE 6")>=0) {
        setTimeout(function() {
                        document.getElementById('fullImage').innerHTML=document.getElementById('fullImage').innerHTML;
                        document.getElementById('barraFoto').style.top=galeriasTPL.getHeight(document.getElementById('boxFullImage')) - 25 + "px";
                    },100);
    }
	if( typeof uol_sc != "undefined" && (typeof uol_sc.t).toLowerCase() == 'function' ){
		uol_sc.prop5='fotoId ' + this.gFoto;
		uol_sc.t();
	}
    return this;
  };

  /**
   * Exibi apartir da imagem atual proxima ou anterior
   * @type {Method}
   * @param {Int} to +1 para proxima | -1 para anterior
   */
  this.proAnt=function(to){
    document.getElementsByTagName('body')[0].focus();
    this.gFoto=this.gFoto+to;

    try {
        this.HTML_publicidade.innerHTML = "";
        if (typeof DEalbum == "function" && this.viewPub == false && this.randomNum == this.gFoto && document.getElementById('banner-588x414-area')) {
            if(document.getElementById("pubGalBox"))
              document.getElementById("pubGalBox").parentNode.removeChild(document.getElementById("pubGalBox"));
            document.getElementById("banner-588x414-area").getElementsByTagName("script")[0].parentNode.removeChild(document.getElementById("banner-588x414-area").getElementsByTagName("script")[0]);
            var HTML_temp=document.getElementById("banner-588x414-area").innerHTML;
            document.getElementById("banner-588x414-area").innerHTML="";
            this.HTML_publicidade.innerHTML='<div id="pubGalBox" onclick="$(\'pubGalBox\').style.display=\'none\'" style="display:block;width:'+document.getElementById("boxFullImage").offsetWidth+'px;height:'+document.getElementById("boxFullImage").offsetHeight+'px;"><div class="pubGalBoxImage"><div class="pubGalBoxBottom"><img src="http://img.uol.com.br/pub_h_120_b.gif" border="0" class="txtPub" /><a class="close" href="javascript:void(0)" onclick="$(\'pubGalBox\').style.display=\'none\'"><img src="http://es.i.uol.com.br/moda/album/banner-fechar.gif" border="0" /></a></div>'+HTML_temp+'</div></div>';
            this.viewPub = true;
            if(typeof DEalbum == "function")
              DEalbum();
        }
        else {
            document.getElementById('pubGalBox').style.display = "none";
        }
    } catch(e) {}
    
    if(this.gFoto==0)
      this.gFoto=parseInt(galeriaInfo[0]['totalImagens']);
    else if(this.gFoto>parseInt(galeriaInfo[0]['totalImagens']))
      this.gFoto=1;

    if(this.gFoto<=this.thumbsReguaStart && this.gFoto>=this.thumbsReguaEnd){
      this.selecionaThumbAtivo();
      this.showImage();
    }
    else {
      if(this.gFoto-to==this.thumbsReguaStart || this.gFoto-to==this.thumbsReguaEnd){
        if(this.proAntTravado==0) {
          this.montarThumbsLista(to);
          this.showImage();
        }
        else {
          this.gFoto-=to;
        }
      }
      else {
        this.thumbsReguaStart=0;
        this.thumbsReguaEnd=0;
        this.montarThumbsLista(0);
        this.showImage();
        this.proAntTravado=1;
      }
      this.selecionaThumbAtivo();
    }
  };

  /**
   * Gera Numero Randomico para exibir Publicidade
   * @type {Method}
   * @autor Elav
   */
    this.makeRandomNum = function() {
        this.randomNum = Math.round(100*Math.random());
        while ( this.randomNum > galeriaInfo[0]['totalImagens'] || this.randomNum == 0) {
            this.makeRandomNum();
        }
    };
    
  /**
   * Escreve data da ultima exportacao do album
   * @type {Method}
   * @autor Elav
   */
    this.formatDate = function(timestamp,estacao) {
        var formatedDate = timestamp.replace(/(\d{4})(\d{2})(\d{2})\d+/,'$3/$2/$1');
        if(!estacao) {
            document.write(formatedDate);
        }
        else {
            try {
                document.getElementsByTagName('form')['reportar'].getElementsByTagName('input')['chmateria'].value = formatedDate + " - " + estacao;
                document.getElementsByTagName('form')['email'].getElementsByTagName('input')['data'].value = formatedDate;
            } catch(e){}
        }
    };

  /**
   * Monta MenuTab acima da regua do Album
   * @type {Method}
   * @autor Elav
   */
    this.galMenu = function() {
        if (galeriaInfo[0]['menuTab'][0]!="" && galeriaInfo[0]['menuTab'][1]!=""){ /* alteração: se não houver abas, não escrever na página */
			var menu = '<ul id="menu-tab"><li class="ativo"><a href="'+galeriaInfo[0]['link']+'">Galeria</a></li>';
			for(i=0; i<galeriaInfo[0]['menuTab'].length;i++) {
				if(i%2==0) {
					menu += '<li><a href="'+galeriaInfo[0]['menuTab'][i+1]+'">'+galeriaInfo[0]['menuTab'][i]+'</a></li>';
				}
			}
			document.getElementById('boxGaleria').innerHTML = menu + "</ul>";
			document.getElementById('boxGaleria').className = "menuTab";
		}
    };


  /**
   * Exibe/Esconde menu da estacao
   * @type {Method}
   * @autor Elav
   */
    this.switchMenu = function() {
        document.getElementById("menu-fechado").style.display = (this.getStyle(document.getElementById("menu-fechado"),'display')=='block') ? 'none' : 'block';
        document.getElementById("menu-aberto").style.display = (this.getStyle(document.getElementById("menu-aberto"),'display')=='block') ? 'none' : 'block';
        document.getElementById('sombra1').style.display = (this.getStyle(document.getElementById("sombra1"),'display')=='block') ? 'none' : 'block';
        document.getElementById('sombra2').style.display = (this.getStyle(document.getElementById("sombra2"),'display')=='block') ? 'none' : 'block';
        document.getElementById('sombra3').style.display = (this.getStyle(document.getElementById("sombra3"),'display')=='block') ? 'none' : 'block';
        if(this.getStyle(document.getElementById('menu-aberto'), 'display')=='block') {
             this.setSombraMenu();
        }
    };
	
  /**
   * Seta a altura da sombra
   * @type {Method}
   * @autor Roberto Robson
   */
	this.setSombraMenu = function(){
	document.getElementById('sombra1').style.height=document.getElementById('sombra2').style.height=document.getElementById('sombra3').style.height=(this.getHeight(document.getElementById('menu-aberto'))-13)+"px";
	};

  /**
   * Ajusta o contador de fotos para trabalhar na ordem ascendente e descendente
   * @type {Method}
   * @param {Int}
   * @autor Elav
   */
    this.counter = function(foto){
        if(galeriaInfo[0]['ordem']=='ASC') {
            return (parseInt(galeriaInfo[0]['totalImagens'])+1)-foto;
        }
        else {
            return foto;
        }
    };


  /**
   * Centraliza regua de thumbs
   * @type {Method}
   * @autor Elav
   */
    this.centerThumbs = function() {
        var pixelAjuste = (this.screenSize==1024) ? 4 : 2;
        if(galeriaInfo[0]['totalImagens'] < this.qtThumbsRegua) {
            // 18 = metade da largura de um thumb
            document.getElementById('thumbsReguaLista').firstChild.style.marginLeft = ((this.qtThumbsRegua - galeriaInfo[0]['totalImagens'] ) * 18 + pixelAjuste) + "px"; 
        }
    };
    
  /**
   * Mostra Preview da foto com mouseOver
   * @type {Method}
   * @param {Int} id, {String} view = block | none
   * @autor Elav
   */
    this.thumbsPreview = function(id,view) {
        if(id!=0) {

			/* alterado para não exibir legendas no thumb, caso não esteja preenchido*/
			//var thumbLeg = (galeriaInfo[id]["legenda-thumb"]!='') ? galeriaInfo[id]["legenda-thumb"] : galeriaInfo[id]["legenda"];
			var thumbLeg = (galeriaInfo[id]["legenda-thumb"]!='') ? galeriaInfo[id]["legenda-thumb"] : "";

            document.getElementById("thumbsPreview").innerHTML = '<table cellpadding="0" cellspacing="0" class="foto"><tr><th id="previewSeta"></th></tr><tr><td><img src="'+galeriaInfo[0]["imagePath"]+galeriaInfo[id]["preview"]+'"/><p>'+thumbLeg+'</p></td></tr></table>';
            var previewClass = "in";
            var previewPosition = this.pageX(document.getElementById("thumbId"+id))-8;
            if(this.screenSize ==1024) {
                if(previewPosition > 820) {
                    previewPosition = previewPosition - this.getWidth(document.getElementById("thumbsPreview")) + 34;
                    previewClass = "out";
                }
            }
            else {
                if(previewPosition > 610) {
                    previewPosition = previewPosition - this.getWidth(document.getElementById("thumbsPreview")) +34;
                    previewClass = "out";
                }
            }
            document.getElementById("previewSeta").className = previewClass;
            document.getElementById("thumbsPreview").style.left = previewPosition+ "px";
        }
        if(navigator.userAgent.indexOf("Opera")>=0 && view=="visible") {
          setTimeout(function() {
                    document.getElementById("thumbsPreview").style.visibility = view;
                },120);
        }
        else {
            document.getElementById("thumbsPreview").style.visibility = view;
        }
    };

  /**
   * Retorna o valor de uma propriedade (name) de um elemento (elem)
   * @type {Method}
   * @param {Object}  elem, {String} name
   * @autor Elav
   */
  this.getStyle = function( elem, name ) {
    if (elem.style[name]) {
        return elem.style[name];
    }
    else if (elem.currentStyle) { // IE
        return elem.currentStyle[name];
    }
    else if (document.defaultView && document.defaultView.getComputedStyle) { // W3C
        name = name.replace(/([A-Z])/g,"-$1");
        name = name.toLowerCase();
        var s = document.defaultView.getComputedStyle(elem,"");
        return s && s.getPropertyValue(name);
    }
    else { // Outros browser
        return null;
    }
  };
  
  /**
   * Retorna a posicao horizontal (x) de um elemento
   * @type {Method}
   * @param {Object}  elem
   * @autor Elav
   */
    this.pageX = function(elem) {
        var p = 0;
        while ( elem.offsetParent ) {
            
			/**
			 * inclusão de if para corrigir centralização do álbum
			 * se existir o elemento com id "centraliza", retira-se o valor do offsetLeft que será incrementado na variável
			 * o número 8 será retirado pela função do Preview, portanto, adiciono aqui para equalizar
			 */
			if (elem.offsetParent.id == "centraliza"){
				p = p - document.getElementById("centraliza").offsetLeft + 8;
		    } 
			else p += elem.offsetLeft;

			/* antes da implementação acima só havia a linha abaixo */
			// p += elem.offsetLeft;
            elem = elem.offsetParent;
        }
        return p;
    };
    
  /**
   * Retorna a largura de um elemento
   * @type {Method}
   * @param {Object}  elem
   * @autor Elav
   */
    this.getWidth = function( elem ) {
        return elem.offsetWidth || parseInt( this.getStyle( elem, 'width' ) );
    };

  /**
   * Retorna a altura de um elemento
   * @type {Method}
   * @param {Object}  elem
   * @autor Elav
   */
    this.getHeight = function( elem ) {
        return elem.offsetHeight || parseInt( this.getStyle( elem, 'height' ) );
    };

};

/*adição de script para captura de variáveis passadas na URI*/
// GetMethodParserJS ::: fermads @ uol
var L=location.href;
var d=L.substring(L.indexOf("?")+1);
var c=v=new Array(); c=d.split("&");
for(i=0;i<c.length&&c.length>0;i++) {
v=c[i].split("="); if(v.length>1)
eval(v[0]+"=unescape('"+v[1].replace(/\+/g," ")+"')");}

galeriasTPL = new galeriasTPL();