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

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

function ValidaTicket(url){
	username = GetCookie('usuario');
	ticket = GetCookie('ticket');
	if ((username == null) && (ticket == null)){
		location.replace('http://passaporte.abril.com.br/autenticaUsuario.do?metodo=checarTipoAutenticacao&COD_SITE=24&COD_RECURSO=756&URL_RETORNO='+url);
		return false;
	}
	return true;
}

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

// 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 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=24&COD_RECURSO=756&URL_RETORNO=' + escape(window.location));
		return false;
	}

	var wComent = window.open('http://bonsfluidos.abril.com.br/comente/' + codigofwa + '_comente.shtml', 'PopComent', 'width=430,height=430,left=0,top=0');
	wComent.focus();
}

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=24&COD_RECURSO=756&URL_RETORNO=' + escape(window.location + '?envAmigo=true'));
		return false;
	}

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

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

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

function popVejaComent() {
   var wVjComent = window.open('/comente/' + codigofwa + '_comentarios.shtml', 'PopComent', 'width=430,height=500,left=0,top=0,scrollbars=yes');
   wVjComent.focus();
}

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

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

function addBookmark(url, desc)
{
	var desc=document.title;

	var ver = navigator.appName;
	var num = parseInt(navigator.appVersion);
	
	if ((ver == "Microsoft Internet Explorer")&&(num >= 4))
	{
		javascript:window.external.AddFavorite(url, desc);
	}
	else
	{
		alert("Para adicionar esta página nos favoritos tecle Control-D.");
	} 
}

function janela(param,w,h,nome,scroll) {
		if (scroll!='yes' || scroll!='no'){
			scroll='yes';
		}
        var nomearq=param;
        var windowvar = window.open(nomearq,nome,"scrollbars="+scroll+",location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,width="+ w + ",height="+h );
}

function participarPromocao(codigo,rec) {

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

	username = GetCookie('usuario');
	ticket = GetCookie('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=24&COD_RECURSO='+rec+'&URL_RETORNO=' + escape(retorno));
	} else {
		location.replace(retorno);
	}
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

/////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////funçoes de testes////////////////////////////////
function getElementByClass(classname){
ccollect=new Array()
var alltags=document.all? document.all : document.getElementsByTagName("*");
for(i=0; i<alltags.length; i++){
if(alltags[i].className==classname){
ccollect[ccollect.length]=alltags[i].innerHTML;
}
}
switch (classname) 
{ 
	case "tipo1" :
	teste1(0,0);
	break;

	case "tipo2" :
	teste2(0,"");
	break;

	case "tipo3" :
	teste3(0,"","","");
	break;

	default : 
      return false;
}
}
//////////////////////////////////////////teste tipo 1///////////////////////////////////////////////
function teste1(num,tot){
	rExp = /<\/div>/gi;
	moz=ccollect[num].replace(rExp,'</DIV>');
	cont=moz.split('</DIV>');
//pega o titulo do teste//////
		sub=cont[0]+"</DIV>";
/////////////////////////////
var valor=new Array;
	for (x=1;x<cont.length;x++){
	if (x%2!=0){
		subcount=cont[x].replace('<DIV>','');
		subcount=subcount.replace('<div>','');
		}
		else{
		sub+='<a href="'+urlloca[0]+'?resposta='+subcount+'&pergunta='+num+'&total='+tot+'">'+cont[x]+'</DIV></a>';
		}
	}
document.getElementById('enquete').innerHTML=sub;
}

function resposta1(resp,perg,tot){
	if (perg==0){var contador=parseInt(resp);}
	else{
	contador=parseInt(tot)+parseInt(resp);
	}
	nextperg=parseInt(perg)+1;
	if (nextperg<ccollect.length){
	teste1(nextperg,contador);
	}
	else{
		rep=document.getElementById('resposta').innerHTML;
		range1=rep.split(',');
			for (i=0;i<range1.length;i++){
				range2=range1[i].split('-');
				if (range2[1]=='n'){maior=contador+1;}
				else{maior=parseInt(range2[1]);}

				if (contador>=parseInt(range2[0]) && contador<=maior){
					numok=i+1;
			document.getElementById('enquete').innerHTML=document.getElementById('resposta'+numok).innerHTML;
				}
			}
	}
}

var theURL = location.href;
urlloca=theURL.split('?');

/////////////////////////////////////////teste tipo 2 /////////////////////////////////////////////////////////
function teste2(num,tot){
	rExp = /<\/div>/gi;
	moz=ccollect[num].replace(rExp,'</DIV>');
	cont=moz.split('</DIV>');
//pega o titulo do teste//////
		sub=cont[0]+"</DIV>";
/////////////////////////////
var letra=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Z'];
	for (x=1;x<cont.length;x++){
	i=x-1;
		if(cont[x]!=''){
		sub+='<a href="'+urlloca[0]+'?resposta2='+letra[i]+'&pergunta='+num+'&letras='+tot+'">'+cont[x]+'</DIV></a>';
		}
		//sub+='<a href="'+urlloca[0]+'?resposta2='+letra[i]+'&pergunta='+num+'&letras='+tot+'"><DIV>TESTE</DIV></a>';
		}
document.getElementById('enquete').innerHTML=sub;
}

function reverseSort(a, b) 
{ 
	if(a > b) 
		return -1 
	if(a < b) 
		return 1 
	return 0 
} 

function resposta2(resp,perg,letras){
	var letra=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Z'];
	contador=letras+'|'+resp;
	nextperg=parseInt(perg)+1;
	if (nextperg<ccollect.length){
		teste2(nextperg,contador);
	}else{
		ttletras=contador.split('|');
		ttletras.sort();
		contletras=new Array;
		j=0;
		k=0;
		L=0;
		for (x=0;x<ttletras.length;x++){
			if (ttletras[x]!=""){
				if (ttletras[x]==letra[j]){
					k++;
					contletras[L]=k+'|'+letra[j];
				}else{
					k=1;
					L++;
					while(ttletras[x]!=letra[j]){
						j++;
					}
					contletras[L]=k+'|'+letra[j];
				}
			}
		}
		contletras.sort(reverseSort);
		numok=contletras[0].split('|');
		numb=numok[0];
		repetidos="";
///////verifica se há empate/////////////
		if (contletras[1]){
			numseg=contletras[1].split('|');
			if (numseg[0]==numok[0]){
				repetidos='Há valores repetidos nas seguintes letras:<br><bR>';
				if(theURL.indexOf("teste_terapia.shtml")!=-1){
					repetidos='Empate! - Se as respostas A e B tiveram o mesmo número de escolhas, então, qualquer uma das terapias combina com você. Isto significa que não há nenhuma característica em nenhuma das opções que você - talvez - não se sinta à vontade.<br><bR>';
				}
				contletras.sort();
				for (x=0;x<contletras.length;x++){
					if (contletras[x]!=null){
						num=contletras[x].split('|');
						if (num[0]==numb){
							numb=num[0];
							repetidos+='<a href="javascript:mostraresp(\''+num[1]+'\')">• Letra '+num[1]+'</a>&nbsp;'
						}
					}
				}
				document.getElementById('enquete').innerHTML=repetidos;
			}
		}
		if (repetidos==""){
			document.getElementById('enquete').innerHTML=document.getElementById('resposta'+numok[1]).innerHTML;
		}
	}
}

function mostraresp(letra){
		resposta=document.getElementById('resposta'+letra).innerHTML;
		document.getElementById('enquete').innerHTML=repetidos+'<br><br>'+resposta;
}

//////////////////////////////////////teste tipo 3/////////////////////////////////////////////////
function teste3(num,sim,nao,resp){
	cont=ccollect[num];
	if (resp=="sim"){sim++;}
	if (resp=="nao"){nao++;}

contador=parseInt(sim);
num++;

	sub='<div class="perg"><a href="'+urlloca[0]+'?resposta3=sim&sim='+sim+'&nao='+nao+'&pergunta='+num+'">• SIM</a></div><div class="perg"><a href="'+urlloca[0]+'?resposta3=nao&sim='+sim+'&nao='+nao+'&pergunta='+num+'">• NÃO</a></div>';

	if (num>ccollect.length)
	{
			if(sim>nao){
			document.getElementById('enquete').innerHTML=document.getElementById('resposta1').innerHTML;
			}
			else if(nao>sim){
			document.getElementById('enquete').innerHTML=document.getElementById('resposta2').innerHTML;
			}
			else{
			document.getElementById('enquete').innerHTML=document.getElementById('resposta3').innerHTML;
			}
	}
	else{
		document.getElementById('enquete').innerHTML=cont+sub;
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////