// coloca os parametros passado por get, em um array por nomes
var URL = location.href;
var PARAMS = URL.substring(URL.indexOf("?")+1);
var PARAM = new Array();
PARAM = PARAMS.split("&");
var par = new Array();

for(var x=0; x < PARAM.length; x++)
{
	var VALOR = new Array();
	VALOR = PARAM[x].split("=");
	par[VALOR[0]] = VALOR[1];
}

var re = /^\//;
var Path = (document.location.pathname).replace(re,"");
var Paths = new Array;
Paths = Path.split('/');
for(var x=0;x <= 1;x++)
{
	if(Paths[x])
	{
		Path = Paths[x];
	}
}

var re = /result/
if(re.test(Path))
{
	Path = par["cl"]
	var re = /(%2F)/g;
	Path = Path.replace(re,"\/");
	var re = /.*\/(.*)/g;
	Path = Path.replace(re,"$1");
}


function Paginacao(Page)
{
	pagDiv = new DynLayer("paginacao");

	var linkPag = '';

	quantPageDiv = new DynLayer("quantpage");
	var quantPage = quantPageDiv.read();
	
	var Proximo = '';
	var Anterior = '';

	for(var x=1; x <= quantPage;x++)
	{
		if(x == Page)
		{
			//linkPag += '<span class="padrao1-14px"><b>'+x+'</b>&nbsp;|&nbsp;</span>';
			linkPag += '<img src="/imagem/ico_pg'+x+'b.gif" border=0>';
		}
		else
		{
			//linkPag += '<a href="#top" onclick="javascript:showPage('+x+');" class="texto7">'+x+'&nbsp;|</a>&nbsp;';
			linkPag += '<a href="#top" onclick="javascript:showPage('+x+');"><img src="/imagem/ico_pg'+x+'.gif" border=0></a>';
		}
		
		
		if(x == quantPage)
			linkPag += '&nbsp;';
		else
			linkPag += '&nbsp;';

	}

	if(Page == 1)
	{
		Proximo = '<a href="#top" onclick="javascript:showPage('+(Page+1)+');"><img src="/imagem/ico_seta_segue.gif" border=0></a>&nbsp;';
		Anterior = '&nbsp;';
	}
	else if(Page == quantPage)
	{
		Proximo = '&nbsp;';
		Anterior = '&nbsp;<a href="#top" onclick="javascript:showPage('+(Page-1)+');"><img src="/imagem/ico_seta_volta.gif" border=0></a>';;
	}
	else
	{
		Proximo = '<a href="#top" onclick="javascript:showPage('+(Page+1)+');"><img src="/imagem/ico_seta_segue.gif" border=0></a>&nbsp;';
		Anterior = '&nbsp;<a href="#top" onclick="javascript:showPage('+(Page-1)+');"><img src="/imagem/ico_seta_volta.gif" border=0></a>';;
	}


	linkPag = '<table border="0" cellspacing="0" cellpadding="0" align="center"><tr><td align="left">'+Anterior+'</td><td align="center">'+linkPag+'</td><td align="right">'+Proximo+'</td></tr></table><br>';
	pagDiv.write(linkPag);
}

function showPage(Page)
{
	// Adicionado para PSeguro
	if(typeof(imagem[Page-1])=="object" && imagem[Page-1]["src"] != "##" && imagem[Page-1]["src"] != "####")
	{
		img = imagem[Page-1];
		imgDiv = new DynLayer("imagem");
		
		right = /(_ver)/;
		if(right.test(img["src"]))
			imgDiv.write('<div align=right><table border=0 cellpadding=0 cellspacing=0 align=right><tr><td><img src="/'+img["src"]+'" border=0><br><span class=legenda>'+img["legenda"]+'</span></td></tr></table></div>');
		else
			imgDiv.write('<img src="/'+img["src"]+'" border=0><br><span class=legenda>'+img["legenda"]+'</span>');
	}
	// Fim PSeguro

	tipo= typeof(pag1);
	if (tipo == "object"){
		if(PageVisible != 0){hidePage(PageVisible);}
		PageVisible = Page;
		pagDiv = new DynLayer("pag"+Page);
		eval("pag"+Page).style.top = 16;
		pagDiv.show();
		pagDiv.Relative();
		Paginacao(Page);
		
	}
	if(Page == "1" && typeof(topo)=="object"){
		topoDiv = new DynLayer("topo");
		topoDiv.show();
		topoDiv.Relative();
	}
	else
	{
		topoDiv = new DynLayer("topo");
		topoDiv.hide();
		topoDiv.Absolute();
	}
}

function hidePage(Page)
{
	pagDiv = new DynLayer("pag"+Page);
	pagDiv.hide();
	pagDiv.Absolute();
}

function navegacao(Titulo)
{
	var Canais = new Array;

	Canais['infonews'] = 'plantão info';
	Canais['edicoes'] = 'revista';
	Canais['download'] = 'download info';



	var PathVoceEsta = '/';
	var re = /^\//;
	var VoceEsta = (document.location.pathname).replace(re,"");
	var Paths = new Array;
	VoceEsta = VoceEsta.replace(/app\//gi, "");
	Paths = VoceEsta.split('/');
	VoceEsta =  '> <a href="/" class=navegacao>home</a> > ';
	for(var x=0;x < Paths.length;x++)
	{
		if(Paths[x])
		{
			var re = /([.][sS][hH][tT][mM][lL])|([.][hH][tT][mM][lL])|([.][jJ][sS][pP])|([.][dD][oO])|([.][jJ][hH][tT][mM][lL])|([.][sS][eE][rR][vV][lL][eE][tT])|([.][sS][hH][lL])/;

			if((!re.test(Paths[x])))
			{
				var nomeCanal
				if(!Canais[Paths[x]])
				{
					Canais[Paths[x]] = Paths[x];
				}
				
				if( (Titulo == 'Home') && (x == ((Paths.length) - 2)) )
				{
					VoceEsta += ' > <b>'+Canais[Paths[x]]+'</b>';
				}
				else
				{
					PathVoceEsta += Paths[x]+'/';
					
					//regex que verifica se o canal esta dentro de uma edição e coloca o,link corretamente
					rePathVoceEsta1 = /.*edicoes\/$/;
					rePathVoceEsta2 = /.*edicoes\/[0-9]+\/arquivos\/$/;
					rePathVoceEsta3 = /.*aberto\/$/;
					rePathVoceEsta4 = /.*aberto\/infonews\/[0-9]+\/$/;
					
					
					if(rePathVoceEsta1.test(PathVoceEsta))
					{
						VoceEsta += '<a href="/arquivo/" class="navegacao">'+Canais[Paths[x]]+"</a> > ";
					}
					else if(rePathVoceEsta2.test(PathVoceEsta))
					{
						VoceEsta += "";
					}
					else if(rePathVoceEsta3.test(PathVoceEsta))
					{
						VoceEsta += "";
					}
					else if(rePathVoceEsta4.test(PathVoceEsta))
					{
						mes = Paths[x].substr(0,2);
						ano = Paths[x].substr(2,4);
						VoceEsta += "<a href="+PathVoceEsta+" class=navegacao>"+mes+"/"+ano+"</a> >";
					}
					else
					{
						VoceEsta += '<a href="'+PathVoceEsta+'" class="navegacao">'+Canais[Paths[x]]+"</a> > ";
					}
				}
			}
		}
	}
	if(Titulo != 'Home')
	{	
		VoceEsta += ' '+Titulo.toLowerCase()+'';
	}
	return VoceEsta;
}


// Função para a busca do site Capricho
function BuscaCapricho(BuscaLetra)
{
	reTest = /artista/;
	if(reTest.test(Path))
	{
		document.BuscaSubHome.action = "http://busca.abril.com.br/capricho/resultartista.jhtml"
	}

	reTest = /galeria/;
	if(reTest.test(Path))
	{
		document.BuscaSubHome.action = "http://busca.abril.com.br/capricho/resultgaleria.jhtml"
	}

	if(par["cl"])
	{
		var re = /%2F/g;
		secao = (par["cl"]).replace(re,"\/");
	}
	
	document.BuscaSubHome.cl.value = secao;
	document.BuscaSubHome.fi.value = BuscaLetra;
	document.BuscaSubHome.submit()

}


// Pega o nome do canal - primeira ocorrência dentro do split para usar no box de Busca das Sub Homes
function PegaNomeCanal()
{
	var Path;
	if(par["cl"])
	{
		var re = /%2F/g;
		Path = (par["cl"]).replace(re,"\/");
		var re = /.*\/(.*)/;
		Path = Path.replace(re,"$1");
	}
	else if(secao)
	{
		var re = /.*\/(.*)/;
		Path = (secao).replace(re,"$1");
	}
	else
	{		
		var re = /.*\/(.*)\/.*/;
		Path = (document.location.pathname).replace(re,"$1");
	}
	document.write(Path.toUpperCase());
}

// Retorna o nome do canal - primeira ocorrência dentro do split para usar no box de Busca das Sub Homes
function ReturnNomeCanal()
{
	var Path;
	if(par["cl"])
	{
		var re = /%2F/g;
		Path = (par["cl"]).replace(re,"\/");
		var re = /.*\/(.*)/;
		Path = Path.replace(re,"$1");
	}
	else
	{		
		var re = /.*\/(.*)\/.*/;
		Path = (document.location.pathname).replace(re,"$1");
	}
	return Path.toUpperCase();
}

function getCookieVal (offset) 
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	   endstr = document.cookie.length;
	   return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name)
{
	 var arg = name + "=";
	 var alen = arg.length;
	 var clen = document.cookie.length;
	 var i = 0;

	 while (i < clen) 
	 {           
	  var j = i + alen;									   
	  if (document.cookie.substring(i, j) == arg)
		  return getCookieVal (j);
		  i = document.cookie.indexOf(" ", i) + 1;
	  if (i == 0) 
		  break; 
	 }
	 return null;
}


function LogOut() // Deleta os cookies ticket e usuario
{
	pathname = location.pathname;
	myDomain = pathname.substring(0,pathname.lastIndexOf('/')) +'/';
	var largeExpDate = new Date();
	largeExpDate.setTime(largeExpDate.getTime() + (60 * 24 * 3600 * -1000));
	SetCookie('usuario',"unknown",largeExpDate,myDomain);
	SetCookie('Ticket',"unknown",largeExpDate,myDomain);
	location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=logout&URL_RETORNO=http://info.abril.com.br');
}

function MostraNomeUsuario(Tipo) // Mostra nome do usuário na barra do site
{
	username = GetCookie('usuario');
	if (username != null)
	{
		var Paths = new Array;
		Paths = username.split(';');
		for(var x=0;x < Paths.length;x++)
		{
			Paths[x] = Paths[x].replace(/\+/gi, " ")
		}


		// Pego só o primeiro nome do usuário para mostrar na barra do site
		PrimeiroNome = Paths[1].split(' ');
		//for(var x=0;x<=1;x++)
		//{			
		//	alert(PrimeiroNome[x])
		//}

		
		if(Tipo!=""){
			document.write(PrimeiroNome[0])
		}
		else{
			document.write("Olá, " + PrimeiroNome[0] + " [<a href='javascript:LogOut()' class='padrao3-9px'>logout</a>] ")		
		}
	}
	else {
			document.write("Olá visitante [<a href='javascript:PassAbril()' class='padrao3-9px'>login</a>] ");
	}
}

function PegaNomeUsuario() // Retorna o nome do usuário logado
{
	username = GetCookie('usuario');
	if (username != null)
	{
		var Paths = new Array;
		Paths = username.split(';');
		for(var x=0;x < Paths.length;x++)
		{
			Paths[x] = Paths[x].replace(/\+/gi, " ")
		}
		return Paths[1];
	}
	else return "";
}

// Vejo qual url do passaporte o usuario irá cair
// se ja estiver logado entra com alteracao de dados forçada
// caso contrario entra para logar normalmente
function MeuRegistro()
{
	username = GetCookie('usuario');

	if (username != null)
	{
		location.replace('http://passaporte.abril.com.br/alteraUsuario.do?metodo=prepararAlterarDadosUsuario&COD_SITE=58&COD_RECURSO=758&URL_RETORNO=http://info.abril.com.br')
	}
	else{
		location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=58&COD_RECURSO=758&URL_RETORNO=http://info.abril.com.br')
	}
}


function ValidaTicket()
{
 username = GetCookie('usuario');
 ticket = GetCookie('ticket');
 if(typeof(arguments[0]) == undefined)
  URL = escape(window.location);
 else
 	URL = arguments[0];

 if ((username == null) && (ticket == null))
 {
  location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=58&COD_RECURSO=758&URL_RETORNO=' + URL);
  return false;
 }
 return true;
}

function ValidaTicket2()
{
 username = GetCookie('usuario');
 ticket = GetCookie('ticket');
 if(typeof(arguments[0]) == undefined)
  URL = escape(window.location);
 else
 	URL = arguments[0];

 if ((username == null) && (ticket == null))
 {
  var pass = 'http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=58&COD_RECURSO=758&URL_RETORNO=';
  pass = pass + 'http://info.abril.com.br/plantao/closewindow.html'
  myLightWindow.activateWindow({href: pass, title: 'Entre com seu passaporte Abril', height: 555, width: 770});							
  return false;
 }
 return true;
}
function ValidaPassaporteCommentarios()
{
 username = GetCookie('usuario');
 ticket = GetCookie('ticket');
 if(typeof(arguments[0]) == undefined)
  URL = escape(window.location);
 else
 	URL = arguments[0];

 if ((username == null) && (ticket == null))
 {  
  //global_aut = 'http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=58&COD_RECURSO=758';
  global_aut = 'http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=58&COD_RECURSO=758&URL_RETORNO=http://info.abril.com.br/plantao/closewindow.html';
  return false;
 }
 return true;
}

// funcao para pegar o codigo da materia
function SalvaMateria(){
	if((window.location.search).match(".*mensagemSalva=true.*")){
		alert('Matéria salva com sucesso!\nEsta matéria está em sua página pessoal.');
		return;
	}
	if(!ValidaTicket()){
		return;
	}

	pegaURL = window.location
	pegaCodigoMateria = pegaURL.toString()
	pegaCodigoMateria = pegaCodigoMateria.replace(/.*conteudo_/gi,"")
	pegaCodigoMateria = pegaCodigoMateria.replace(/.shtml/gi,"")
	//alert(pegaCodigoMateria)
	window.location= 'http://app.capricho.abril.com.br/paginaspessoais/app/salvamateriafavorito.servlet?codMateria='+pegaCodigoMateria+'&referer='+pegaURL;

}

function verificaApresentaMensagemMateriaSalva(){
	
	if((window.location.search).match(".*mensagemSalva=true.*")){
		alert('Matéria salva com sucesso!\nEsta matéria está em sua página pessoal.');
	}

	if((window.location.search).match(".*mensagemSalva=false.*")){
		alert('Não foi possível salvar a matéria.');
	}
}
verificaApresentaMensagemMateriaSalva();


// funcoes Denis xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
function wopen(page,nwin,larg,altu){
	window.open(page,nwin,'width='+larg+',height='+altu+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,top=10,left=10');
}


// Função para visualizar a página pessoal de uma pessoa
function verPaginaPessoal(codPessoa)
{
  var URL = "http://app.capricho.abril.com.br/paginaspessoais/app/pagina_pessoal.jsp";
  URL += "?CodPessoa=" + codPessoa;
  MM_openBrWindow(URL,'','scrollbars=yes,width=478,height=500');
}

// Função para visualizar um artigo
function lerArtigo(URL)
{
  MM_openBrWindow(URL,'Artigo','scrollbars=yes,width=800,height=600,resizable=yes,menubar=yes,toolbar=yes,location=yes');
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

// Função para validar um email
function emailValido (email)
{
   invalidChars = " /:,;"

   if (email == "") return false;
   
   for (i=0; i<invalidChars.length; i++)
   {
      badChar = invalidChars.charAt(i);
      if (email.indexOf(badChar,0) > -1) return false;
   }

   atPos = email.indexOf("@",1);
   if ((atPos == -1) || (email.indexOf("@",atPos+1) != -1)) return false;

   periodPos = email.indexOf(".",atPos)
   if ((periodPos == -1) || (periodPos+3 > email.length)) return false;

   return true;
}

// Função que checa se os emails são válidos e se a quantidade de nomes é igual a quantidade de emails
// Os valores das variáveis "nomesValue" e "emailsValue" devem estar sepadaros por ";"
function checkEmail(nomesValue, emailsValue)
{
   var NOMES = new Array();
   NOMES = nomesValue.split(";");

   if (emailsValue == "") return false;

   var emails;
   var re=/[ +]/g;
   emails = emailsValue.replace(re,"");

   var EMAILS = new Array();
   EMAILS = emails.split(";");

   if(NOMES.length > 1) {
      if(NOMES.length != EMAILS.length) {
         alert("O campo de nome e endereço do destinatário devem ter a mesma quantidade.");
         return false;
      }
   }

   for (var i=0;i<EMAILS.length;i++) {
      if (!emailValido(EMAILS[i])) {
         alert("Por favor preencha corretamente o campo do endereço do destinatário.");
         return false;
      }
   }

   return true;
}

function ImprimirMateria()
{
  var URL = "http://app.capricho.abril.com.br/abrilEmail/print.servlet";
  URL += "?URL_TEMPLATE=http://capricho2.abril.com.br/templates/imprimirMateriaForm.shtml";
  URL += "&URL_TO_LOAD=" + escape(window.location.href);
  URL += "&REGEX_TO_LOAD=" + escape("titulo|<!--titulo-->(.*?)<!--/titulo-->");
  URL += "&REGEX_TO_LOAD=" + escape("olho|<!--olho-->(.*?)<!--/olho-->");
  URL += "&REGEX_TO_LOAD=" + escape("texto|<!--texto-->(.*?)<!--/texto-->");
  URL += "&REGEX_TO_REPLACE=" + escape("<div id=[pP][aA][gG].*?>|");

  var width = 800;
  var heigth = 600;

  // Centraliza a janela
  posx = (screen.width/2)-(width/2);
  posy = (screen.height/2)-(heigth/2);
  pos = "top=" + posy + ",left=" + posx;

  MM_openBrWindow(URL,'Imprimir','scrollbars=yes,width='+width+',height='+heigth+',resizable=yes,'+pos);
}

function EmailMateria()
{

  var urlLocation = escape(window.location.href);
    
  var URL = "http://app.capricho.abril.com.br/abrilEmail/formemail.servlet";
  URL += "?URL_TEMPLATE=http://capricho2.abril.com.br/templates/emailEnviarForm.shtml";
  URL += "&URL_TO_LOAD=" + urlLocation;
  URL += "&REGEX_TO_LOAD=subject|" + escape("<!--titulo-->(.*?)<!--/titulo-->");
  URL += "&REGEX_TO_LOAD=titulo|" + escape("<!--titulo-->(.*?)<!--/titulo-->");
  URL += "&REGEX_TO_LOAD=olho|" + escape("<!--olho-->(.*?)<!--/olho-->");
  URL += "&REGEX_TO_REPLACE=" + escape("<.*?>|");
  URL += "&PARAMETRO_MAP=email_type|TEXTO";
  URL += "&PARAMETRO_MAP=user_origem|" + PegaNomeUsuario();
  URL += "&PARAMETRO_MAP=urlToReturn|" + urlLocation;
  URL += "&PARAMETRO_MAP=urlLayoutEmail|http://capricho2.abril.com.br/templates/layoutEmail.tpl";
  URL += "&PARAMETRO_MAP=link|" + urlLocation;
  URL += "&PARAMETRO_MAP=canal|" + ReturnNomeCanal();
  URL += "&PARAMETRO_MAP=subtitulo|";
  URL += "&PARAMETRO_MAP=conteudo|";

  window.location.href = URL;

}


//Function de enquete da NGTools - LabOne
function NGTools_Abre_Enquete(theURL,winName,features)	{
    window.open(theURL,winName,features);
}

if(typeof HTMLElement!="undefined" && !
HTMLElement.prototype.insertAdjacentElement){
	HTMLElement.prototype.insertAdjacentElement = function
(where,parsedNode)
	{
		switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this)
			break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(parsedNode);
			break;
		case 'afterEnd':
			if (this.nextSibling) 
this.parentNode.insertBefore(parsedNode,this.nextSibling);
			else this.parentNode.appendChild(parsedNode);
			break;
		}
	}

	HTMLElement.prototype.insertAdjacentHTML = function
(where,htmlStr)
	{
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function
(where,txtStr)
	{
		var parsedText = document.createTextNode(txtStr)
		this.insertAdjacentElement(where,parsedText)
	}
}