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

function PegaEmailUsuario() // Retorna o email 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[2];
 }
 else return "";
}

function ValidaTicket()
{
	username = getCookie('usuario');
	ticket = getCookie('ticket');
	codigo = '';

	if (username != null) {
		valores = username.split(';');
		codigo = valores[0];
	}

	if ((username == null && ticket == null) || (codigo == '2516185'))
	{
		location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=42&COD_RECURSO=90&URL_RETORNO=' + escape(window.location));
		return false;
	}
	return true;
}

function envAmigo() {

	//username = getCookie('usuario');
	//ticket = getCookie('ticket');

	/*if ((username == null) && (ticket == null))
	{
		location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=42&COD_RECURSO=90&URL_RETORNO=' + escape(window.location + '?envAmigo=true'));
		return false;
	}*/

	/*var wEnv =*/ window.open('/_areascomuns/envieamigo/envie.shtml', 'PopEnviar', 'width=430,height=400,left=0,top=0');
	//wEnv.focus();
}

if (URL.indexOf("envAmigo=true") > 0) {
	envAmigo();
}

// 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("Os campos 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;
}


// Mostra o nome de um usuário
function showUserName()
{
	username = getCookie('usuario');
	if (username != null) {
		var params = new Array;
		params = username.split(';');
		for(var x=0;x<params.length;x++) {
			params[x] = params[x].replace(/\+/gi, " ")
		}

    var name = params[1];
    document.write(name);
	}
	else {
		document.write("Visitante");
	}
}

// Mostra o primeiro nome do usuário
function showUserFirstName()
{
	username = getCookie('usuario');
	if (username != null) {
		var params = new Array;
		params = username.split(';');
		for(var x=0;x<params.length;x++) {
			params[x] = params[x].replace(/\+/gi, " ")
		}

		var name = params[1].split(' ');
		document.write(name[0]);
	}
	else {
		document.write("Visitante");
	}
}

function envComent() {

	username = getCookie('usuario');
	ticket = getCookie('ticket');

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

	var wComent = window.open('/fwa/comentario/aberto/' + codigofwa + '_comente.shtml?' + origem, 'PopComent', 'width=430,height=300,left=0,top=0');
	wComent.focus();
}

function participarPromocao(codigo,rec){

            var retorno = 'http://casa.abril.com.br/promocao/casa-brasil/ok.shtml';

            var retornoRG = 'http://passaporte.abril.com.br/alteraUsuario.do?metodo=prepararAlterarDadosUsuario&URL_RETORNO=' + retorno;

            username = getCookie('usuario');

            ticket = getCookie('ticket');

            alert("User:" +username);
            alert("ticket:" +ticket);

            if ((username == null) && (ticket == null)){

                        //location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=63&COD_RECURSO=383&URL_RETORNO=' + escape(retornoRG));
                        location.replace('http://passaporte.abril.com.br/alteraUsuario.do?metodo=prepararAlterarDadosUsuario&COD_SITE=5&COD_RECURSO='+rec+'&URL_RETORNO=' + escape(retorno));

            }else{

                        location.replace(retorno);

            }

}


function iniPagComent() {
  var UrlChk = window.opener.location.href ;
  UrlChk = UrlChk.split('?') ;
  UrlChk = UrlChk[0] ;
  window.opener.location.href = UrlChk  ;
}