/** 
 * @projectDescription Album de fotos
 *
 * @author 	Roberto Robson (Bode) rnogueira@uolinc.com, responsavel pela primeira versão desenvolvida para UOL Jogos que originou todas as demais
 * @version	4.0
 * @since	2.0
 */

/**
 * FirebugX
 */
(function(){
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}
})();

window.albumFotos = window.albumFotos || {};
albumFotos.ParseUrl = function(src,v){
	src = src.replace(/#fotoNav\=/,(src.indexOf("?")>=0?"&":"?")+"fotoNav=")
  eval("_REQUEST"+v+"=[];\n"+(unescape(src).indexOf("?")>=0?unescape(src).replace(/.*?\?/,"?").replace(/((\&|\?)\&?[^\=]*?(\&|$))/g,"").replace(/(\&|\?)*(([^\&]*?)\=(.*?))(\&|$)/g,"_REQUEST"+v+"['$3']=\"$4\";\n"):""));
}
albumFotos.ParseUrl(location.href,"_HREF");


/**
 * Inicia a galeria fazendo as suas principais configuracoes
 * @type {Method}
 * @param {Object} args {
 *                   idAlbum : String (default : null),
 *                   thumbs : Boolean (default : false),
 *                   applyIn : String (default : "albumHTML"),
 *                   jsHtmlThumbs : String (default : "http://lib.uol.com.br/album/album-html-thumbs.js"),
 *                   jsHtmlFoto : String (default : "http://lib.uol.com.br/album/album-html-foto.js"),
 *                   modeThumbsQtImgs : Int (default : 20),
 *                   slideshowTimer : Int (default : 4),
 *                   hitURL : String (default : "album-hit.jhtm"),
 *                   ultimosAlgunsApplyIn : String (default : "ultimosAlbunsHTML"),
 *                   jsUltimosAlbuns : String (degault : false),
 *                   jsHtmlUltimosAlbuns : String (default : "http://lib.uol.com.br/album/album-html-ultimos.js"),
 *                   idEnquete : int (default : null),
 *                   urlEnquete : String (default : "album-enquete.jhtm"),
 *                   playerBgColor1 : String (default : 486d92),
 *                   playerBgColor2 : String (default : 003366),
 *                   playerLegendColor : String (default : ffffff)
 *               }
 */
albumFotos.init = function(args){
	if(!args)
		args = {};
	this.dependencias();
	this.getAlbumData();	
	this.idAlbum = args['idAlbum'] || null;
	this.pgThumbs = args['thumbs'] || false; // define se o album tem pagina com thumbs
	this.fotoAtual = this.fotoAtualView = null;
	  this.setFotoAtual(parseInt(_REQUEST_HREF['fotoNav']) || parseInt(_REQUEST_HREF['gFoto']) || parseInt(_REQUEST_HREF['abrefoto']) || parseInt(galeriaInfo[0]['fotoInicial']) || null,true);
	this.applyIn = args['applyIn'] || "albumHTML"; // id do elemento que receberá os elementos do Album
	this.jsHtmlThumbs = args['jsHtmlThumbs'] || "http://lib.uol."+(location.href.match('lib.uol.intranet')?'intranet':'com.br')+"/album/album-html-thumbs.js"; // js para gerar o html da pagina de thumbs
	this.jsHtmlFoto = args['jsHtmlFoto'] || "http://lib.uol."+(location.href.match('lib.uol.intranet')?'intranet':'com.br')+"/album/album-html-foto.js"; // js para gerar o html da pagina de foto ampliada
	
	this.hitURL = args['hitURL'] || "album-hit.jhtm";
	this.sortPage = parseInt(_REQUEST_HREF['sortPage']) || 0; // pagina atual no modo visualizacao de thumbs
	this.modeThumbsQtImgs = args['modeThumbsQtImgs'] || 20;
	this.ultimosAlbuns = {
	  applyIn : args['ultimosAlgunsApplyIn'] || "ultimosAlbunsHTML",
	  paginaAtual : 0,
	  paginas : []
	}; // Lista dos ultimos albuns, utilizado para fazer um cache de todas os arquivos carregados pelo usuario
	this.jsUltimosAlbuns = args['jsUltimosAlbuns'] || false; // url do js com a lista dos ultimos albuns publicados
	this.jsHtmlUltimosAlbuns = typeof args['jsHtmlUltimosAlbuns'] !="undefined" ? args['jsHtmlUltimosAlbuns'] || false : "http://lib.uol."+(location.href.match('lib.uol.intranet')?'intranet':'com.br')+"/album/album-html-ultimos.js"; // js para gerar o html da lista dos ultimos albuns publicados
	this.idEnquete = args['idEnquete'] || null;
	this.urlEnquete = args['urlEnquete'] || "album-enquete.jhtm";
	this.playerBgColor1 = args['playerBgColor1'] || '486d92';
	this.playerBgColor2 = args['playerBgColor2'] || '003366';
	this.playerLegendColor = args['playerLegendColor'] || 'ffffff';
	this.modeFotoStandBy = []; // Armazena funcoes que devem ser executadas apos a imagem principal ter carregado
	this.modeFotoRunScriptsOK = false; // Scripts em standby, informa se foram executados apos a imagem principal ter carregado
	this.qtThumbsRegua = 0; // Quantidade de thumbs possiveis na regua de navegação. Calculado automaticamente
	this.thumbsReguaStart = 0; //Inicio da listagem de thumbs na regua de navegação
	this.thumbsReguaEnd = 0; //Fim da listagem de thumbs na regua de navegação
	this.proAntTravado = 0; //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.slideshow = 0; //Slideshow 1 = ativado | 0 = desativado
	this.slideshowWatch; //Função setTimeout do slideshow
	this.slideshowTimer=parseInt(args['modeThumbsQtImgs'])*1000 || 4000; //Intervalo em miliesegundos do slideshow
	this.HTML_publicidade = null //HTML da publicidade
	this.clicksExibirPublicidade = Math.round((galeriaInfo[0]['totalImagens']-1)*Math.random());
	this.setModeView();
	this.cliksNav = 0; //Quantidade de cliques na navegação de fotos
	
	if(this.modeView=="foto" && this.fotoAtual==null)
		this.setFotoAtual(Math.round((galeriaInfo[0]['totalImagens']-1)*Math.random()+1),false);
		
	// Define classe no elemento BODY como tipo de visualizacao do album (Lista de thumbs ou apenas foto)
	var HTML_BODY = document.getElementsByTagName("body")[0];
	if (this.modeView == "foto" && HTML_BODY.className.indexOf("albumFotosNavFoto") == -1) 
			HTML_BODY.className += " albumFotosNavFoto";
	else if (this.modeView == "thumbs" && HTML_BODY.className.indexOf("albumFotosNavThumbs") == -1) 
			HTML_BODY.className += " albumFotosNavThumbs";
	    
	// Adiciona na lista de funcoes que devem ser executadas apos a imagem principal ter carregado
	// a chamada para o arquivo js que monta o HTML da lista dos ultimos albuns
	if (this.jsHtmlUltimosAlbuns != false && this.jsUltimosAlbuns != false) {
	  this.modeFotoStandBy.push(function(){
	    albumFotos.loadScript(albumFotos.jsHtmlUltimosAlbuns);
	  })
	}
	
	// funcao para montar o HTML do player
	if(galeriaInfo[0]["mp3File"] && galeriaInfo[0]["mp3File"]!="")
	  this.modeFotoStandBy.push(function(){
	    albumFotos.loadScript('http://lib.uol.com.br/album/versoes/AC_RunActiveContent.js');
	  })
	
	// no Safari, é criado uma thread que verifica o hash na URL
	if (navigator.userAgent.indexOf('Safari') >= 0) {
		this.intervalSafari = setInterval(function(){
			albumFotos.checkSafari();
		},100)
	}
		
	// ativar navegação pelas setas do teclado
	if(this.modeView == 'foto')
		albumFotos.modeFotoStandBy.push(function(){
			albumFotos.setNavKeyBoard();
		})
}

/**
 * Converte lista em HTML das fotos em Json
 */
albumFotos.getAlbumData = function(){
	var albumDataDL = document.getElementById('albumData');
	if (albumDataDL) {
  	window.galeriaInfo = [];
  	window.galeriaInfo[0] = {};
  	(function(){
  		var li = albumDataDL.getElementsByTagName('li');
  		for (var i = 0; i < li.length; i++) {
  			galeriaInfo[0][li[i].title] = li[i].innerHTML.replace(/^.*?\:(\s|$)/g, "").replace(/\s$/g, "");
  		}
  	})();
  	var fotosDT = albumDataDL.getElementsByTagName('dl')[0].getElementsByTagName('dt');
  	var fotosDD = albumDataDL.getElementsByTagName('dl')[0].getElementsByTagName('dd');
  	for (var i = 0; i < fotosDT.length; i++) {
  		var foto = fotosDT[i].getElementsByTagName('a')[0].getAttribute('rel');
  		galeriaInfo.push({
  			'image': foto + "?ts=" + galeriaInfo[0]['timestamp'],
  			'thumb': foto.replace(/_f_/, "_t_") + "?ts=" + galeriaInfo[0]['timestamp'],
  			'preview': foto.replace(/_f_/, "_p_") + "?ts=" + galeriaInfo[0]['timestamp'],
  			'legenda': fotosDD[i].getElementsByTagName('a')[0].innerHTML,
  			'legenda-thumb': fotosDT[i].getElementsByTagName('a')[0].innerHTML,
  			'credito': fotosDD[i].getElementsByTagName('span')[0].innerHTML,
  			'width': fotosDD[i].getAttribute('rel').split("x")[0],
  			'height': fotosDD[i].getAttribute('rel').split("x")[1],
  			'url-foto': fotosDD[i].getElementsByTagName('cite')[0].getElementsByTagName('a')[0].getAttribute('href',2)
  		})
  	}
  	galeriaInfo[galeriaInfo.length] = galeriaInfo[0];
  } 
}

/**
 * Define os atributos fotoAtual e fotoAtualView e inverte a ordem das fotos para crescente caso seja informado
 * @param {int} f numero correspondente da foto em visualizacao
 * @param {boolean} o reverte a ordem das fotos caso galeriaInfo[0]['ordem'] seja igual a 'ASC'
 */
albumFotos.setFotoAtual = function(f,o){
  // Inverte a ordem das fotos ASC||DESC
  if (o == true && galeriaInfo[0]['ordem'] == 'ASC'){
    this.fotoAtual = this.fotoAtualView = f;
  	galeriaInfo.reverse();
    if(this.fotoAtual!=null && galeriaInfo[0]['ordem'] == 'ASC')
	  	this.fotoAtual=parseInt(galeriaInfo[0]['totalImagens'])+1-this.fotoAtual;
  }else if(galeriaInfo[0]['ordem'] == 'ASC'){
      this.fotoAtual=f;
      this.fotoAtualView=parseInt(galeriaInfo[0]['totalImagens'])+1-this.fotoAtual;
  }else
    this.fotoAtual=this.fotoAtualView=f;
  return this;
}

/**
 * Define o modo de visualizacao (foto ou thumbs)
 */
albumFotos.setModeView = function(){
	if (this.pgThumbs == false || (this.pgThumbs == true && this.fotoAtual != null))
		this.modeView = "foto";
  else if (this.pgThumbs == true && this.fotoAtual == null)
		this.modeView = "thumbs";
}

/**
 * Método para carregar scripts dinamicamente
 * @type {Method}
 * @param {String} url url do javascript para ser carregado
 */
albumFotos.loadScript = function(url){
	var HTML_SCRIPT = document.createElement("script");
	HTML_SCRIPT.src=(url);
	document.getElementsByTagName("head")[0].appendChild(HTML_SCRIPT);
}

/**
 * Lista de dependencias para o Album funcionar
 * @type {Method}
 */
albumFotos.dependencias = function(){
		this.loadScript("http://lib.uol.com.br/setandanimate/setandanimate.js?timestamp="+(new Date()).getTime());
}

/** 
 * Ativa e desativa Slideshow
 * @type {Method}
 */
albumFotos.changeSlideShow=function(){
  if(this.slideshow==0){
    this.slideshow=1;
    document.getElementById('inputSlideshow').checked=true;
  }else{
    this.slideshow=0;
    document.getElementById('inputSlideshow').checked=false;
  }
  document.getElementById('inputSlideshow').blur();
  this.checkSlideShow();
}

/** 
 * Verifica o status do slide show, se ativado executa slideshowWatch
 * @type {Method}
 */
albumFotos.checkSlideShow=function(){
  clearTimeout(this.slideshowWatch);
  if(this.slideshow==1)
    this.slideshowWatch=setTimeout(function(){albumFotos.proAnt(-1)},this.slideshowTimer);
}

/** 
 * Executa os metodos necessários para montar o HTML do album baseado no modelo de visualizacao
 * @type {Method}
 */
albumFotos.show = function(){
	if(parent.albumFotos == self.albumFotos){
		if(this.modeView == "thumbs")
			this.loadScript(this.jsHtmlThumbs);
		else if(this.modeView == "foto")
			this.showMenuFloat().loadScript(this.jsHtmlFoto);
	}
}



/**
 * Monta HTML do menu float
 * @type {Method}
 */
albumFotos.showMenuFloat=function(){
  if (document.getElementById("corpo") && document.getElementById("menu")) {
    var HTML_bgBottom = document.createElement('div');
    HTML_bgBottom.className = 'menu-bottom-bg';
    
    var HTML_fechado = document.createElement('div');
    HTML_fechado.id = "menuAlbumFotosFechado";
    HTML_fechado.className = "menuAlbumContent menuAlbumFechado";
    HTML_fechado.innerHTML = "<a href=\"javascript:albumFotos.switchMenu()\" class=\"switch\">Abrir o menu</a>";
    HTML_fechado.appendChild(HTML_bgBottom.cloneNode(true));
    document.getElementById('corpo').appendChild(HTML_fechado);
    
    var HTML_aberto = document.createElement('div');
    HTML_aberto.id = "menuAlbumFotosAberto";
    HTML_aberto.className = "menuAlbumContent menuAlbumAberto";
    HTML_aberto.innerHTML = "<a href=\"javascript:albumFotos.switchMenu()\" class=\"switch\">Fechar o menu</a>";
    HTML_aberto.appendChild(document.getElementById('menu'));
    HTML_aberto.appendChild(HTML_bgBottom);
    document.getElementById('corpo').appendChild(HTML_aberto);
    
    document.getElementById('menu').style.display = "block";
  }
  return this;
};

/**
 * Exibe/Esconde menu da estacao
 * @type {Method}
 */
albumFotos.switchMenu = function() {
	if(document.getElementById("menuAlbumFotosAberto").offsetHeight==0){
  	document.getElementById("menuAlbumFotosFechado").style.display = "none";
  	document.getElementById("menuAlbumFotosAberto").style.display = "block";
	}else{
  	document.getElementById("menuAlbumFotosFechado").style.display = "block";
  	document.getElementById("menuAlbumFotosAberto").style.display = "none";
	}
};

/**
 * Define a quantidade de thumbs que cabe na regua
 * @type {Method}
 */
albumFotos.setQtThumbsRegua = function(){
  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);
  document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.width = (document.getElementById('thumbsReguaLista').getElementsByTagName('li')[0].offsetWidth * parseInt(galeriaInfo[0]['totalImagens'])) + 'px';
  if (parseInt(galeriaInfo[0]['totalImagens']) <= this.qtThumbsRegua)
    document.getElementById('thumbsReguaLista').className+=" center";
  else
    document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].style.width = document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].offsetWidth * 2 + 'px';
  return this;
}

/**
 * Monta lista da regua de thumbs utilizando 'qtThumbsRegua' para saber quantos são possiveis.
 * @type {Method}
 * @param {Int} to 0 = sem movimento, >0 = cria thumbs na esquerda, <0 cria thumbs na direita
 */
albumFotos.montarThumbsLista=function(to){
  if(this.thumbsReguaStart==0)
    this.thumbsReguaStart=this.fotoAtual+Math.floor(this.qtThumbsRegua/2);
  if(this.thumbsReguaEnd==0)
    this.thumbsReguaEnd=this.fotoAtual-Math.floor(this.qtThumbsRegua/2);
		
  if(to>0 && to<this.qtThumbsRegua){
    this.thumbsReguaStart+=to;
    this.thumbsReguaEnd=this.thumbsReguaStart-to+1;
    this.thumbsReguaRecalcular=1;
  }else if(to<0 && to*-1<this.qtThumbsRegua){
    this.thumbsReguaEnd+=to;
    this.thumbsReguaStart=this.thumbsReguaEnd+to*-1-1;
    this.thumbsReguaRecalcular=1;
  }else{
    this.thumbsReguaRecalcular=0;
    this.thumbsReguaStart=parseInt(this.thumbsReguaStart)+to;
    this.thumbsReguaEnd=parseInt(this.thumbsReguaEnd)+to;
  }

  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";

  this.HTML_ul=document.createElement('div');
	this.montarThumbsListaHtml();

  if(to<0){
    document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].innerHTML+=this.HTML_ul.innerHTML;
  }else{
    document.getElementById('thumbsReguaLista').getElementsByTagName('ul')[0].innerHTML=this.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=((to<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(){
	  		albumFotos.deleteThumbs();
	  		albumFotos.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}
 */
albumFotos.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}
 */
albumFotos.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.fotoAtual))
    document.getElementById('thumbId'+this.fotoAtual).className="ativo";
}

/**
 * deleta Thumbs na regua que estão escondidos e define a margem da regua para 0
 * @type {Method}
 */
albumFotos.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 
 */
albumFotos.scrollThumbs=function(to){
  if(to>0) 
    thumbsRestantes=galeriaInfo[0]['totalImagens']-albumFotos.thumbsReguaStart;
  else
    thumbsRestantes=albumFotos.thumbsReguaEnd-1
  this.montarThumbsLista(((thumbsRestantes<this.qtThumbsRegua)?thumbsRestantes:this.qtThumbsRegua)*to);
}

/** 
 * Executado deopois da imagem ter carregado
 * @type {Method}
 */
albumFotos.imageLoaded=function(){
  this.checkSlideShow();

  //document.getElementById('fullImageSrc').style.display="block";
  document.getElementById('fullImage').style.height="auto";

  if(document.getElementById("corpo"))
		document.getElementById("corpo").style.height="auto";
	if(document.getElementById("col-esquerda"))
		document.getElementById("col-esquerda").style.height="auto";
	if(document.getElementById("col-centro"))
		document.getElementById("col-centro").style.height="auto";
	if(document.getElementById("col-direita"))
		document.getElementById("col-direita").style.height="auto";
    
  //if(typeof(setHeight)!="undefined")
  //  setHeight('col-centro');
  

  /** 
   * 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) {
    if(document.getElementById("fullImageSrc").offsetWidth>984)
      document.getElementById("fullImageSrc").style.width="984px";
    document.getElementById('setaEsq').style.height = document.getElementById('setaDir').style.height = "auto";
    document.getElementById('setaEsq').style.height = document.getElementById('setaDir').style.height = "350px";
    //document.getElementById('setaEsq').style.height = document.getElementById('setaDir').style.height = document.getElementById('fullImageSrc').clientHeight + "px";
  }
  document.getElementById('fullImage').className=document.getElementById('fullImage').className.replace(/carregando/,"carregado");

  //Scripts em standby, devem rodar apenas uma vez depois que a imagem principal carregar
  if(this.modeFotoRunScriptsOK==false){
    for(var i=0; i<this.modeFotoStandBy.length; i++){
      if(typeof this.modeFotoStandBy[i] == "function")
        this.modeFotoStandBy[i].call(this);
    }
    this.modeFotoRunScriptsOK=true;
  }
  
  if (document.getElementById("albumPlayer"))
    document.getElementById("albumPlayer").style.top = (document.getElementById("fullImage").offsetTop + document.getElementById("fullImageSrc").offsetHeight)+"px"

	this.metricas('fotoId ' + this.fotoAtual);

}

/**
 * Seleciona pelos thumbs
 * @type {Method}
 */
albumFotos.selectImage=function(f){
  this.setFotoAtual(f,false);
  this.showImage();
  this.selecionaThumbAtivo();
}

/**
 * Exibi a partir da imagem atual proxima ou anterior
 * @type {Method}
 * @param {Int} to +1 para proxima | -1 para anterior
 */
albumFotos.proAnt=function(to){
  this.setFotoAtual(this.fotoAtual+to);

  if(this.fotoAtual==0)
    this.setFotoAtual(parseInt(galeriaInfo[0]['totalImagens']),false);
  else if(this.fotoAtual>parseInt(galeriaInfo[0]['totalImagens']))
    this.setFotoAtual(1,false);

  if(this.fotoAtual<=this.thumbsReguaStart && this.fotoAtual>=this.thumbsReguaEnd){
    this.showImage();
    this.selecionaThumbAtivo();
  }else{
    if(this.fotoAtual-to==this.thumbsReguaStart || this.fotoAtual-to==this.thumbsReguaEnd){
      if(this.proAntTravado==0){
        this.montarThumbsLista(to);
        this.showImage();
      }else{
        this.fotoAtual-=to;
      }
    }else{
      this.thumbsReguaStart=0;
      this.thumbsReguaEnd=0;
      this.montarThumbsLista(0);
      this.showImage();
      this.proAntTravado=1;
    }
    this.selecionaThumbAtivo();
  }

  this.publicidade();

}

albumFotos.ultimosAlbunsLoad = function(p){
  document.getElementById(albumFotos.ultimosAlbuns.applyIn).className=document.getElementById(albumFotos.ultimosAlbuns.applyIn).className.replace("carregado","");
  albumFotos.ultimosAlbuns.paginaAtual = p;
  setTimeout(function(){
    p = albumFotos.ultimosAlbuns.paginaAtual;
    if(p>=albumFotos.ultimosAlbuns.paginas.length || albumFotos.ultimosAlbuns.paginas[p]==null)
      albumFotos.loadScript(albumFotos.jsUltimosAlbuns.replace(/(\.js)/g,(p>0?p:"")+"$1"));
    else
      albumFotos.ultimosAlbunsShow();
		if(albumFotos.ultimosAlbuns.paginaAtual + albumFotos.ultimosAlbuns.paginas.length > 0)
    	albumFotos.albumHitRequest('ultimos');
    },300);
	this.metricas('pagina ' + p);
}

albumFotos.ultimosAlbunsCallback = function(data){
  console.log("JS com lista de ultimos albuns publicados carregado");
  albumFotos.ultimosAlbuns.paginas[albumFotos.ultimosAlbuns.paginaAtual] = data;
  albumFotos.ultimosAlbunsShow();
}

albumFotos.fotoNav = function(){
	if(this.cliksNav > 0)
		location.replace("#fotoNav="+this.fotoAtualView);
	this.cliksNav++;
}

albumFotos.albumHitRequest = function(URL){
	// Cria AlbumHit

	if(this.cliksNav > 1 || URL == 'ultimos'){
		if (!document.getElementById("galeriaHit")) {
	  	var AlbumHitDiv = document.createElement("div");
	  	AlbumHitDiv.innerHTML = "<iframe style=\"position:absolute;top:-1000px;left:-1000px\" name=\"albumHit\" id=\"galeriaHit\" src=\"" + this.hitURL + "?id=" + galeriaInfo[0]['galeria'] + "&fotoAtual=" + this.fotoAtual + "\"></iframe>";
	  	document.getElementById(this.applyIn).appendChild(AlbumHitDiv);
	  }else	if(window.frames['albumHit'])
			window.frames['albumHit'].location.replace(this.hitURL + "?id=" + galeriaInfo[0]['galeria'] + "&fotoAtual=" + this.fotoAtual);
	}

}

/**
 * Exibe publicidade
 * @type {Method}
 */
albumFotos.publicidade = function(){
  if (this.clicksExibirPublicidade == 0 && typeof DEalbum == "function" && document.getElementById('banner-588x414-area')) {
    if(this.slideshow==1)
      this.changeSlideShow();
    document.getElementById("banner-588x414-area").getElementsByTagName("script")[0].parentNode.removeChild(document.getElementById("banner-588x414-area").getElementsByTagName("script")[0]);
    this.HTML_publicidade = document.createElement("div");
    this.HTML_publicidade.id = "albumFotosPublicidade";
    this.HTML_publicidade.innerHTML='<div class="imagemPublicidade"><div class="barraPublicidade"><img src="http://img.uol.com.br/pub_h_120_b.gif" border="0" class="txtPub" /><a class="btFechar" href="javascript:void(0)" onclick="albumFotos.fecharPublicidade()"><img src="http://img.uol.com.br/album/banner-fechar.gif" border="0" /></a></div></div>';
    this.HTML_publicidade.getElementsByTagName('div')[0].appendChild(document.getElementById("banner-588x414-area"));
    document.getElementById('boxFullImage').appendChild(this.HTML_publicidade);
  }else
    this.clicksExibirPublicidade--;
}

/**
 * Fechar publicidade
 */
albumFotos.fecharPublicidade = function(){
  document.getElementById("albumFotosPublicidade").parentNode.removeChild(document.getElementById("albumFotosPublicidade"));
}

/**
 * Caso o navegador seja Safari, é criado uma thread que verifica o hash na URL
 * Se a foto no hash for diferente da que o usuário esta vendo, é executado a função selectImage para exibir a imagem/foto correta.
 */
albumFotos.checkSafari = function(){
	albumFotos.ParseUrl(location.href,"_HREF");
	if(_REQUEST_HREF['fotoNav'] && parseInt(_REQUEST_HREF['fotoNav']) != this.fotoAtualView){
		this.setFotoAtual(parseInt(_REQUEST_HREF['fotoNav']),true).selectImage(this.fotoAtual);
	}
}

/**
 * Script de metricas acionado a cada troca de imagem/foto
 */
albumFotos.metricas = function(s){
	if( typeof uol_sc != "undefined" && (typeof uol_sc.t).toLowerCase() == 'function' ){
	    uol_sc.prop5=s;
	    uol_sc.t();
	}
}

albumFotos.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,true);
  }

}

albumFotos.setNavKeyBoard = function(){
	this.navKeyboardTimerEnable = null;
	this.events.add(document,'keyup',function(e){albumFotos.navKeyBoard(e)});
}


albumFotos.navKeyBoardTracking = function(){
	var navKeyboardTracking = new Image();
	navKeyboardTracking.src = "http://click.uol.com.br/?rf=albumFotosKeyNavTrack&ts="+ ((new Date()).getTime()) +"&u=http://home.img.uol.com.br/h3/x.gif?album="+escape(location.host+location.pathname);
}

albumFotos.navKeyBoard = function(e){
	if (this.navKeyboardTimerEnable == null) {
		this.navKeyboardTimerEnable = setTimeout(function(){albumFotos.navKeyboardTimerEnable = null},500);
  	if (e.srcElement && !e.target) 
  		e.target = e.srcElement;
  	if (!e.target.nodeName.toLowerCase().match(/(input|text)/g) && e.keyCode.toString().match(/^(39|37)$/)) {
			this.navKeyBoardTracking();
  		if (e.keyCode == 39)
  			this.proAnt(-1);
  		else if (e.keyCode == 37) 
  			this.proAnt(1);
  	}
	}
}

