//Biblioteca de Funcoes Java Script

//Definicao de Variaveis
		user_yes = "https://www.heureca.org/ad.html";
		user_no  = "https://www.heureca.org/user_insup.php?pesq=1";		

//Funcao para tratamento da Data/Hora
//-------------------------------------------------------------------------------	
		mdata      = new Date()
		mhora      = mdata.getHours()
		mdia       = mdata.getDate()
		mdiasemana = mdata.getDay()
		mmes       = mdata.getMonth()
		mano	   = mdata.getFullYear()
								
		var msg    = "";
		
		if (mhora < 12)
			msg = "Bom dia! ";
		else if(mhora >=12 && mhora < 18)
			msg = "Boa tarde! ";
		else if(mhora >= 18 && mhora < 24)
			msg = "Boa noite! ";
		
		if(mdiasemana == 0)
		   msg = msg + "Domingo, ";
		else if(mdiasemana == 1)
		   msg = msg + "Segunda-feira, ";
		else if(mdiasemana == 2)
		   msg = msg + "Terça-feira, ";
		else if(mdiasemana == 3)
		   msg = msg + "Quarta-feira, ";
		else if(mdiasemana == 4)
		   msg = msg + "Quinta-feira, ";
		else if(mdiasemana == 5)
		   msg = msg + "Sexta-feira, ";
		else if(mdiasemana == 6)
		   msg = msg + "Sábado, ";
		
		msg = msg + mdia + " de ";
		if(mmes == 0)
		   msg = msg + "janeiro de ";
		else if(mmes == 1)
		   msg = msg + "fevereiro de ";
		else if(mmes == 2)
		   msg = msg + "março de ";
		else if(mmes == 3)
		   msg = msg + "abril de ";
		else if(mmes == 4)
		   msg = msg + "maio de ";
		else if(mmes == 5)
		   msg = msg + "junho de ";
		else if(mmes == 6)
		   msg = msg + "julho de ";
		else if(mmes == 7)
		   msg = msg + "agosto de ";
		else if(mmes == 8)
		   msg = msg + "setembro de ";
		else if(mmes == 9)
		   msg = msg + "outubro de ";
		else if(mmes == 10)
		   msg = msg + "novembro de ";
		else if(mmes == 11)
		   msg = msg + "dezembro de ";
		
		msg = msg + mano + " ";
		
		var timerID = null;
		var timerRunning = false;
		function startclock () 
		{
		stopclock();
		time();
		}
		function stopclock ()
		{
		if(timerRunning)
		clearTimeout(timerID);
		timerRunning = false;
		}
		function time()
		{
		var now     = new Date();
		var hours   = now.getHours();
		var minutes = now.getMinutes();
		var seconds = now.getSeconds();
		if (hours   < 10) { hours   = "0" + hours;   }
		if (minutes < 10) { minutes = "0" + minutes; }
		if (seconds < 10) { seconds = "0" + seconds; }
		
		var Time = (hours + ":" + minutes + ":" + seconds);
		document.getElementById("data_hora").innerHTML= msg + " - " + Time; 
		timerID = setTimeout("time()",1000);
		timerRunning = true;
		}
		function clearStatus()
		{
		if(timerRunning)
		clearTimeout(timerID);
		timerRunning = false;
		document.getElementById("data_hora").innerHTML= "";
		}

//Funcoes para tratamento das abas do Menu
//-------------------------------------------------------------------------------
	function stAba(menu,conteudo)
	{
		this.menu = menu;
		this.conteudo = conteudo;
	}
		
	var arAbas = new Array();
	var arAbasAdm = new Array();
	var arAbasMod = new Array();
	var arAbasUser = new Array();

	//Visitante		
	arAbas[0] = new stAba('td_home','div_home');
	arAbas[1] = new stAba('td_anunciar','div_anunciar');
	arAbas[2] = new stAba('td_assinar','div_assinar');
	arAbas[3] = new stAba('td_fale_conosco','div_fale_conosco');
	arAbas[4] = new stAba('td_pesquisar','div_pesquisar');
	arAbas[5] = new stAba('td_imoveis','div_imoveis');
	arAbas[6] = new stAba('td_veiculos','div_veiculos');
	arAbas[7] = new stAba('td_empregos','div_empregos');
	arAbas[8] = new stAba('td_produtos','div_produtos');
	arAbas[9] = new stAba('td_servicos','div_servicos');
	arAbas[10] = new stAba('td_parceiros','div_parceiros');
	
	//Administrador	
	arAbasAdm[0] = new stAba('td_assinar','div_assinar');
	arAbasAdm[1] = new stAba('td_pagamento','div_pagamento');
	arAbasAdm[2] = new stAba('td_atribuir_moderador','div_atribuir_moderador');
	arAbasAdm[3] = new stAba('td_anuncio','div_anuncio');
	arAbasAdm[4] = new stAba('td_adm_mod_user','div_adm_mod_user');
	arAbasAdm[5] = new stAba('td_secao','div_secao');
	arAbasAdm[6] = new stAba('td_categoria','div_categoria');
	arAbasAdm[7] = new stAba('td_tipo_negocio','div_tipo_negocio');
	arAbasAdm[8] = new stAba('td_estado_cidade','div_estado_cidade');
	arAbasAdm[9] = new stAba('td_tipo_assinatura','div_tipo_assinatura');
	arAbasAdm[10] = new stAba('td_tipo_pagamento','div_tipo_pagamento');
	arAbasAdm[11] = new stAba('td_rel_secao_categoria','div_rel_secao_categoria');
	arAbasAdm[12] = new stAba('td_fale_conosco','div_fale_conosco');
	arAbasAdm[13] = new stAba('td_pesquisar','div_pesquisar');
	arAbasAdm[14] = new stAba('td_imoveis','div_imoveis');
	arAbasAdm[15] = new stAba('td_veiculos','div_veiculos');
	arAbasAdm[16] = new stAba('td_empregos','div_empregos');
	arAbasAdm[17] = new stAba('td_produtos','div_produtos');
	arAbasAdm[18] = new stAba('td_servicos','div_servicos');
	
	//Moderador	
	arAbasMod[0] = new stAba('td_anuncio','div_anuncio');
	arAbasMod[1] = new stAba('td_pesquisar','div_pesquisar');
	arAbasMod[2] = new stAba('td_imoveis','div_imoveis');
	arAbasMod[3] = new stAba('td_veiculos','div_veiculos');
	arAbasMod[4] = new stAba('td_empregos','div_empregos');
	arAbasMod[5] = new stAba('td_produtos','div_produtos');
	arAbasMod[6] = new stAba('td_servicos','div_servicos');
	
	//Usuario Comum
	arAbasUser[0] = new stAba('td_cadastro','div_cadastro');
	arAbasUser[1] = new stAba('td_anuncio','div_anuncio');
	arAbasUser[2] = new stAba('td_assinar','div_assinar');
	arAbasUser[3] = new stAba('td_pagamento','div_pagamento');
	arAbasUser[4] = new stAba('td_pesquisar','div_pesquisar');		
	arAbasUser[5] = new stAba('td_imoveis','div_imoveis');
	arAbasUser[6] = new stAba('td_veiculos','div_veiculos');
	arAbasUser[7] = new stAba('td_empregos','div_empregos');
	arAbasUser[8] = new stAba('td_produtos','div_produtos');
	arAbasUser[9] = new stAba('td_servicos','div_servicos');
		
	//Visitante		
	function AlternarAbas(menu, conteudo)
	{
		for (i=0; i<arAbas.length; i++)
		{
			m = document.getElementById(arAbas[i].menu)
			m.className = 'menu';
			c = document.getElementById(arAbas[i].conteudo)
			c.style.display = 'none';
		}
		m = document.getElementById(menu)
		m.className = 'menu-sel';
		c = document.getElementById(conteudo)
		c.style.display = '';
	}
	
	//Administrador	
	function AlternarAbasAdm(menu, conteudo)
	{
		for (i=0; i<arAbasAdm.length; i++)
		{
			m = document.getElementById(arAbasAdm[i].menu)
			m.className = 'menu';
			c = document.getElementById(arAbasAdm[i].conteudo)
			c.style.display = 'none';
		}
		m = document.getElementById(menu)
		m.className = 'menu-sel';
		c = document.getElementById(conteudo)
		c.style.display = '';
	}
	
	//Moderador	
	function AlternarAbasMod(menu, conteudo)
	{
		for (i=0; i<arAbasMod.length; i++)
		{
			m = document.getElementById(arAbasMod[i].menu)
			m.className = 'menu';
			c = document.getElementById(arAbasMod[i].conteudo)
			c.style.display = 'none';
		}
		m = document.getElementById(menu)
		m.className = 'menu-sel';
		c = document.getElementById(conteudo)
		c.style.display = '';
	}
	
	//Usuario Comum
	function AlternarAbasUser(menu, conteudo)
	{
		for (i=0; i<arAbasUser.length; i++)
		{
			m = document.getElementById(arAbasUser[i].menu)
			m.className = 'menu';
			c = document.getElementById(arAbasUser[i].conteudo)
			c.style.display = 'none';
		}
		m = document.getElementById(menu)
		m.className = 'menu-sel';
		c = document.getElementById(conteudo)
		c.style.display = '';
	}
		
//Esta Funcao Adiciona o Endereço do Site nos Favoritos do
//Usuario para os browsers Internet Explorer, FireFox e Opera
//-------------------------------------------------------------------------------
function AdicionarFavoritos()
{
    var url		= "http://www.heureca.org/";
    var title	= "Heureca - Um novo conceito em anúncios!";
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print)
	{
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

//Esta Funcao Adiciona o Endereço do Site nos
//Favoritos do Usuario para o browser IE
//-------------------------------------------------------------------------------
function addbookmark()
{
	bookmarkurl = "http://www.heureca.org/"
	bookmarktitle = "Heureca - Um novo conceito em anúncios!"
	if (document.all) window.external.AddFavorite(bookmarkurl,bookmarktitle)
}

//Esta Funcao Abre uma Janela no Browser
//-------------------------------------------------------------------------------
function abrejanela(url)
{ 
	var myWin = window.open(url);
	myWin.focus();
}

//Esta Funcao verifica se o Campo foi preenchido com um E-mail valido
//-------------------------------------------------------------------------------
function isEmail(text)
{
   var 	arroba = "@",
       	ponto = ".",
	   	posponto = 0,
	   	posarroba = 0;
	
	 if (text == "") return false;
	
	 for (var indice = 0; indice < text.length; indice++)
	 {
	 	if (text.charAt(indice) == arroba)
		{
	 		posarroba = indice;
	      	break;
		 }
	 }
	
	for (var indice = posarroba; indice < text.length; indice++)
	{
		if (text.charAt(indice) == ponto)
		{
			posponto = indice;
	     	break;
		}
	}
	if (posponto == 0 || posarroba == 0) return false;
	if (posponto == (posarroba + 1)) return false;
	if ((posponto + 1) == text.length) return false;
	return true;
}

//Esta Funcao compara o Tamanho dos Campos
//-------------------------------------------------------------------------------
function compTam(str1, lim)
{
	var resp = "";
	if (str1.length < lim)	resp = -1;
	if (str1.length == lim)	resp = 0;
	if (str1.length > lim)	resp = 1;
	return resp;
}

//Esta Funcao verifica se o Campo esta Vazio
//-------------------------------------------------------------------------------
function isEmpty(pStrText)
{
	var	len = pStrText.length;
	var pos;
	var vStrnewtext = "";

	for (pos=0; pos<len; pos++)
	{
		if (pStrText.substring(pos, (pos+1)) != " ")
		{
			vStrnewtext = vStrnewtext + pStrText.substring(pos, (pos+1));
		}
	}

	if (vStrnewtext.length > 0)
		return false;
	else
		return true;
}

//Esta Funcao formata as mascaras de entrada dos campos do formulario
//-------------------------------------------------------------------------------
function formatar_mascara(src, mascara)
{
	var campo = src.value.length;
	var saida = mascara.substring(0,1);
	var texto = mascara.substring(campo);
	if (texto.substring(0,1) != saida)
	{
		src.value += texto.substring(0,1);
	}
}

//Esta Funcao verifica se a data digitada e maior do que a atual
//-------------------------------------------------------------------
function isMajorDate(myDate)
{
	var data = myDate;		
    var objDate = new Date();
	
    objDate.setYear(data.split("/")[2]);
    objDate.setMonth(data.split("/")[1] - 1); //- 1 porque em js os meses sao de 0 a 11
    objDate.setDate(data.split("/")[0]);

    if(objDate.getTime() > new Date().getTime())
	{
		return true;
    }
	else
	{
		return false;	
	}
}

//Esta Funcao verifica se a data digitada e valida
//Formato: dd/mm/aaaa
//-------------------------------------------------------------------
function isDate(dateStr)
{

var datePat = /^(\d{1,2})(\/|)(\d{1,2})(\/|)(\d{4})$/;
var matchArray = dateStr.match(datePat); //O formato esta ok?

if (matchArray == null)
{
	alert("Favor digitar uma data válida!");
	return false;
}

//Converte a data para variaveis
day	= matchArray[1];
month = matchArray[3];
year = matchArray[5];

if (day < 1 || day > 31)
{
	alert("O dia deve estar entre 1 e 31!");
	return false;
}

if (month < 1 || month > 12)
{	//Verifica a faixa de valores do mes
	alert("O mês deve estar entre 1 e 12!");
	return false;
}

if ((month==4 || month==6 || month==9 || month==11) && day==31)
{
	alert("O mês "+month+" não tem 31 dias!")
	return false;
}

if (month == 2)
{	//Verifica se o mês de fevereiro tem 29 dias
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	if (day > 29 || (day==29 && !isleap))
	{
		alert("Fevereiro " + year + " não tem " + day + " dias!");
		return false;
	}
}

	return true; //A data e valida

}

//Esta Funcao verifica se a hora digitada e valida
//Formato: hh:mm
//-------------------------------------------------------------------
function isHour(hourStr)
{
	var hour = hourStr.substring(0,2);
	var minute = hourStr.substring(3,5);
	if (hourStr.length < 5)
	{
		return false;	
	}
	else
	{
		if (hour < 00 || hour > 23 || minute < 00 || minute > 59)
		{
			return false;	
		}
		else
		{
			return true;	
		}
	}
}

//Verifica se o cep digitado e valido
//Formato: nnnnn-nnn
//-------------------------------------------------------------------
function isCEP(cepStr)
{
	var campo1 = cepStr.substring(0,5);
	var campo2 = cepStr.substring(5,6);
	var campo3 = cepStr.substring(6,9);
	
	if (campo2 == '-')
	{
		if (isNaN(campo1) == false && isNaN(campo3) == false)
		{
			return true;	
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;	
	}
}

//Verifica se o telefone digitado e valido
//Formato: nn nnnn-nnnn
//-------------------------------------------------------------------
function isPhone(phoneStr)
{
	var campo1 = phoneStr.substring(0,2);
	var campo2 = phoneStr.substring(2,3);
	var campo3 = phoneStr.substring(3,7);
	var campo4 = phoneStr.substring(7,8);
	var campo5 = phoneStr.substring(8,12);
	
	if ((campo2 == ' ') && (campo4 == '-'))
	{
		if (isNaN(campo1) == false && isNaN(campo3) == false && isNaN(campo5) == false)
		{
			return true;	
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

//Verifica se o cpf digitado e valido
//Formato: nnn.nnn.nnn-nn
//-------------------------------------------------------------------
function isCPF(cpfStr)
{
	var campo1 = cpfStr.substring(0,3);
	var campo2 = cpfStr.substring(4,7);
	var campo3 = cpfStr.substring(8,11);
	var campo4 = cpfStr.substring(12,14);
	
	if (isNaN(campo1) == false && isNaN(campo2) == false && isNaN(campo3) == false && isNaN(campo4) == false)
	{
		return true;	
	}
	else
	{
		return false;
	}
}

//Funcoes para tratar texto
//-------------------------------------------------------------------
var numeros	= "0123456789";
var letras	= "abcdefghijklmnopqrstuvwxyz";
var letras_maiusculas = "ABCDEFGHIJKLMNNOPQRSTUVWXYZ";

//Verifica se tem numeros no texto
//-------------------------------------------------------------------
function tem_numeros(texto)
{
   for(i=0; i<texto.length; i++)
   {
      if (numeros.indexOf(texto.charAt(i),0) != -1)
	  {
         return 1;
      }
   }
   return 0;
}

//Verifica se tem letras no texto
//-------------------------------------------------------------------
function tem_letras(texto)
{
   texto = texto.toLowerCase();
   for(i=0; i<texto.length; i++)
   {
      if (letras.indexOf(texto.charAt(i),0) != -1)
	  {
         return 1;
      }
   }
   return 0;
}

//Verifica se tem letras minusculas no texto
//-------------------------------------------------------------------
function tem_minusculas(texto)
{
   for(i=0; i<texto.length; i++)
   {
      if (letras.indexOf(texto.charAt(i),0) != -1)
	  {
         return 1;
      }
   }
   return 0;
}

//Verifica se tem letras maiusculas no texto
//-------------------------------------------------------------------
function tem_maiusculas(texto)
{
   for(i=0; i<texto.length; i++)
   {
      if (letras_maiusculas.indexOf(texto.charAt(i),0) != -1)
	  {
         return 1;
      }
   }
   return 0;
}

//Verifica o nivel de seguranca da senha
//-------------------------------------------------------------------
function seguranca_senha(senha)
{
   var seguranca = 0;
   if (senha.length != 0)
   {
      if (tem_numeros(senha) && tem_letras(senha))
	  {
         seguranca += 30;
      }
      if (tem_minusculas(senha) && tem_maiusculas(senha))
	  {
         seguranca += 30;
      }
      if (senha.length >= 4 && senha.length <= 5)
	  {
         seguranca += 10;
      }
	  else
	  {
         if (senha.length >= 6 && senha.length <= 8)
		 {
            seguranca += 30;
         }
		 else
		 {
            if (senha.length > 8)
			{
               seguranca += 40;
            }
         }
      }
   }
   return seguranca;
}

//Mostra o nivel de seguranca da senha
//-------------------------------------------------------------------
function mostra_seguranca_senha(senha, formulario)
{
	seguranca = seguranca_senha(senha);
	formulario.seguranca.value = seguranca + "%";
}

//Esta Funcao retorna a tecla pressionada
//-------------------------------------------------------------------------------
function pegaTecla(e)
{
	if (navigator.appName == 'Netscape')
	{
		return e.which;
	}
	else
	{
		//For Windows
		var e = e ? e : window.event;
	    var tecla = (e.keyCode) ? e.keyCode : e.which;
		return tecla;
	}
}

//Esta Funcao bloqueia a tecla "Ctrl"
//-------------------------------------------------------------------------------
function rejeitaTecla(e)
{
	if (navigator.appName == 'Netscape' && e.which == 17)
	{
		alert("Tecla Ctrl bloqueada!");	
		return false;
	}
	
	//For Windows
	var e = e ? e : window.event;
    var tecla = (e.keyCode) ? e.keyCode : e.which;
	if (tecla == 17)
	{
		alert("Tecla Ctrl bloqueada!");	
		return false;
	}

	return true;
}

//Esta Funcao bloqueia o botao direito do Mouse
//-------------------------------------------------------------------------------
function right(e){
	if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
	{
		alert("Botão direito do mouse bloqueado!");
		return false;
	}
	else if (navigator.appName == 'Microsoft Internet Explorer' && (event.button == 2 || event.button == 3))
	{
		alert("Botão direito do mouse bloqueado!");
		return false;
	}
	return true;
}

//Esta Funcao formata o campo valor em reais
//-------------------------------------------------------------------------------
function formataMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){

    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
	
	var whichCode = (window.Event) ? e.which : e.keyCode;    
		
	if ((objTextBox.value.length >= objTextBox.maxLength) && (whichCode != 13) && (whichCode != 8)) whichCode = 1;

	if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); //Valor para o codigo da Chave
	
    if (strCheck.indexOf(key) == -1) 
    	return false; //Chave invalida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
        	break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
        	aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) 
    	objTextBox.value = '';
    if (len == 1) 
    	objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) 
    	objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        	objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

//onKeyPress="return(formataMoeda(this,'.',',',event))"; //Usar com INPUT

//Esta Funcao verifica se o CPF digitado e valido
//-------------------------------------------------------------------------------
function valida_cpf(cpf_tmp)
{
	var numeros, digitos, soma, i, resultado, digitos_iguais, cpf;
    digitos_iguais = 1;
	
	//Retira os pontos e o traco do CPF		
	cpf = cpf_tmp.replace(".", "");
	cpf = cpf.replace(".", "");	
	cpf = cpf.replace("-", "");
		
    if (cpf.length < 11)
	{
		alert('CPF Inválido!');	
        return false;
	}
	
    for (i = 0; i < cpf.length - 1; i++)
		if (cpf.charAt(i) != cpf.charAt(i + 1))
        {
			digitos_iguais = 0;
            break;
        }
		
    if (!digitos_iguais)
    {
		numeros = cpf.substring(0,9);
        digitos = cpf.substring(9);
        soma = 0;
		
        for (i = 10; i > 1; i--)
			soma += numeros.charAt(10 - i) * i;
        
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        
		if (resultado != digitos.charAt(0))
		{
			alert('CPF Inválido!');	
            return false;
		}
        
		numeros = cpf.substring(0,10);
        
		soma = 0;
        
		for (i = 11; i > 1; i--)
			soma += numeros.charAt(11 - i) * i;
        
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        
		if (resultado != digitos.charAt(1))
		{
			alert('CPF Inválido!');	
            return false;
		}

		//alert('CPF Válido!');	
        return true;
	}
    else
	{
		alert('CPF Inválido!');	
        return false;	  
	}
}