/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author "Desconhecido" projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para aplicação de Máscaras
*/
 
function jMascara (objForm, strField, sMask, evtKeyPress) {
      var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

      if(window.event) { // Internet Explorer
        nTecla = evtKeyPress.keyCode; }
      else if(evtKeyPress.which) { // Nestcape
        nTecla = evtKeyPress.which;
      }

      sValue = objForm[strField].value;

      // Limpa todos os caracteres de formatação que
      // já estiverem no campo.
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( "-", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( ".", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "/", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( "(", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( ")", "" );
      sValue = sValue.toString().replace( " ", "" );
      sValue = sValue.toString().replace( " ", "" );
      fldLen = sValue.length;
      mskLen = sMask.length;

      i = 0;
      nCount = 0;
      sCod = "";
      mskLen = fldLen;

      if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...
          return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
        else { // qualquer caracter...

		
		  while (i <= mskLen) {
	        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
	        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
	
	        if (bolMask) {
	          sCod += sMask.charAt(i);
	          mskLen++; }
	        else {
	          sCod += sValue.charAt(nCount);
	          nCount++;
	        }
	
	        i++;
	      }
	
	      objForm[strField].value = sCod;

          return true;
        } }
      else {
        return true;
      }
    }

/////////////////////////////////////////////////////////////////////////////////////////////////	
/**
* @author Tiago Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para ocultar/mostrar qualquer objeto
*/
 
function jMostraOculta_Objeto ( campo , acao )
{
	if ( acao == 'onBlur' ) 
	{
		document.getElementById(campo).style.display='none';
	}
	else if ( acao = 'onFocus' ) 
	{
		document.getElementById(campo).style.display='';
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author "Desconhecido" projetos@logicadigital.com.br
* @copyright (c) 2005 Lógica Digital
* Descrição: Script para validar C.P.F.
*/

function fVerificaCPF(campo) {
	var CPF = campo.value; // Recebe o valor digitado no campo
	CPF = CPF.replace("-", "");
	CPF = CPF.replace(".", "");
	CPF = CPF.replace(".", "");

	// Aqui começa a checagem do CPF
	var posicao, i, soma, dv, dv_informado;
	var digito = new Array(10);
	dv_informado = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado
	
	// Desemembra o número do CPF na array DIGITO
	for (i=0; i<=8; i++) {
	  digito[i] = CPF.substr( i, 1);
	}
	
	// Calcula o valor do 10º dígito da verificação
	posicao = 10;
	soma = 0;
	   for (i=0; i<=8; i++) {
	      soma = soma + digito[i] * posicao;
	      posicao = posicao - 1;
	   }
	digito[9] = soma % 11;
	   if (digito[9] < 2) {
	        digito[9] = 0;
	}
	   else{
	       digito[9] = 11 - digito[9];
	}
	
	// Calcula o valor do 11º dígito da verificação
	posicao = 11;
	soma = 0;
	   for (i=0; i<=9; i++) {
	      soma = soma + digito[i] * posicao;
	      posicao = posicao - 1;
	   }
	digito[10] = soma % 11;
	   if (digito[10] < 2) {
	        digito[10] = 0;
	   }
	   else {
	        digito[10] = 11 - digito[10];
	   }
	
	// Verifica se os valores dos dígitos verificadores conferem
	dv = digito[9] * 10 + digito[10];
	   if (CPF.length > 0)
	   {
		   if (dv != dv_informado)  
		   {
		      document.getElementById('cpf_erro').style.display = '';
		      document.getElementById('cpf_ok').style.display = 'none';
			  document.getElementById('cpf').className = 'formularioinput_erro';
			  return false;
		   }
		   else
		   {
		   	  document.getElementById('cpf_erro').style.display = 'none';
		      document.getElementById('cpf_ok').style.display = '';
			  document.getElementById('cpf').className = 'formularioinput';
			  return false;
		   }
		}
		else
		{
			document.getElementById('cpf_erro').style.display = 'none' ;
			document.getElementById('cpf_ok').style.display = 'none' ;
			document.getElementById('cpf').className = 'formularioinput';
		}
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Tiago Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para comparar se dois campos são iguais
*/

function jVerificaCampos ( campo , campo_confirmacao , imagem_ok , imagem_erro , nome_campo)
{
	if ( campo.length > 0 && campo_confirmacao.length > 0)
	{
		if ( campo == campo_confirmacao )
		{
			document.getElementById(imagem_erro).style.display = 'none' ;
			document.getElementById(imagem_ok).style.display = '' ;
			document.getElementById(nome_campo).className = 'formularioinput';
		}
		else
		{
			document.getElementById(imagem_erro).style.display = '' ;
			document.getElementById(imagem_ok).style.display = 'none' ;
			document.getElementById(nome_campo).className = 'formularioinput_erro';
		}
	}
	else
	{
		document.getElementById(imagem_erro).style.display = 'none' ;
		document.getElementById(imagem_ok).style.display = 'none' ;
		document.getElementById(nome_campo).className = 'formularioinput';
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author André Ferraro projetos@logicadigital.com.br
* @copyright (c) 2005 Lógica Digital
* Descrição: Script para validar se campo foi preenchido
*/

function jValidaCampo( label_campo , nome_campo , tamanho_campo , tipo_campo )
	{
		//T - Input Text Caracter
		//N - Input Text Inteiro
		//C - Input Checkbox
		//D - Data
		if (tipo_campo == "T")
		{
			if (nome_campo.value.length == 0 || nome_campo.value.length < tamanho_campo)
			{
				alert("Por favor, preencha o campo " + label_campo + " corretamente.");
				nome_campo.focus();
				return false;
			}
		}
		if (tipo_campo == "C")
		{
			if ((nome_campo[0].checked == false) && (nome_campo[1].checked == false))
			{
				alert("Por favor, preencha o campo " + label_campo + " corretamente.");
				return false;
			}
		}
		/*** implementar para validar data
		if (tipo_campo == "D")
		{
			if ((nome_campo[0].checked == false) && (nome_campo[1].checked == false))
			{
				alert("Por favor, preencha o campo " + label_campo + " corretamente.");
				return false;
			}
		}*/
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Maikel Finck projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para usuário digitar apenas números
*/

function jCampoNumerico ( x , y , evtKeyPress )
{
// Inicializa a variavel
var nTecla = 0;
// Verifica plataforma
if (document.all)
{
// Plataformas tipo IE
nTecla = evtKeyPress.keyCode ;
}
else
{
// Plataformas tipo NETSCAPE
nTecla = evtKeyPress.which ;
}
// Verifica tecla pressionada
if ((( nTecla > 47 ) && ( nTecla < 58 ))  // numerico (0123456789)
|| ( nTecla == 8   )   // backspace
|| ( nTecla == 127 )   // delete
|| ( nTecla == 0   )   // teclas nao definidas
//|| ( nTecla == 9   )   // tabulacao
|| ( nTecla == 13  )   // enter
//|| ( nTecla == 44  )   // , (vírgula)
//|| ( nTecla == 46  ))  // . (ponto)
)
{
// Digita a tecla pressionada
return true;
}
else
{
// Ignora a tecla pressionada
return false;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Tiago de Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Montagem de Combo Box dinâmica com AJAX
*/
	function pesquisar_dados( valor , pagina , campo , selecionado )
	{
	
		extensao = 1 ;

		for ( cont_string = 0 ; cont_string < pagina.length ; cont_string ++ )
		{
			if ( pagina.charAt(cont_string) == '.' )
			{
				extensao = 0 ;
			}
		}
		
		if ( extensao != 0 )
		{
			pagina = pagina + '.php?' ;
		}
		
		else
		{
			pagina = pagina + '&' ;
		}
		http.open( "GET", pagina + "id=" + valor , true ); 
		http.onreadystatechange = function()
        {
            // chama a função que colocará o conteúdo
            handleHttpResponse(campo , selecionado);
        };
		
		http.send(null);
	}

/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Tiago de Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Essa função tem a finalidade de "pegar" o resultado da página processada, 
             e apresentar no seu defido lugar. Poderiamos jogar em um textarea, uma <div>, 
			 um <p>, ou até mesmo um alert.
*/		
	function handleHttpResponse( campo , selecionado )
	{
		campo_select = document.getElementById(campo);
		if (http.readyState == 4) 
		{
	  		campo_select.options.length = 0;
		    results = http.responseText.split(",");
		    for( i = 0; i < results.length; i++ )
		    {
			
	    		string = results[i].split( "|" );

				// checa se o texto não está vazio...
				if ( string[0] != '' )
				{

					campo_select.options[i] = new Option( string[0], string[1] ) ;

					// checa se a opção é a selecionada...
					if ( selecionado == string[1] )
					{
						// se for, coloca ela como selecionada
						campo_select.options[i].selected = true ;
					}
					
				}
				
				// verifica se o selecionado está vazio
				if ( selecionado == '' )
				{
					// se estiver, coloca o 1o item como selecionado.
					campo_select.options[0].selected = true ;
				}
	  		}
		}
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Tiago de Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Identificação do Navegador e Suporte ao XMLHttpRequest.
*/
function getHTTPObject() 
{
		if(typeof ActiveXObject == "undefined" && typeof XMLHttpRequest == "undefined") return null;
		var xmlhttp;
		/*@cc_on
		@if (@_jscript_version >= 5) {
		try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
		try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
		xmlhttp = false;
		}
		}
		}
		@else xmlhttp = null;
		@end @*/

		if (xmlhttp == null && typeof XMLHttpRequest != 'undefined') {
		try {
		xmlhttp = new XMLHttpRequest();
		} catch (e) {
		xmlhttp = null;
		}
		}
		return xmlhttp;
}
	
	var http = getHTTPObject();
	
////////////////////////////////////////////////////////////////////////////////////////////////

//*** Código base do Ajax
function abreAjax(url, div)
{

	// se conectar, executa...
	http.onreadystatechange = function()
	{
		// chama a função que colocará o conteúdo
		conteudoPagina(http , div);
	};

	// define método como GET
	http.open('GET', url, true);
	http.send(null);
}

//*** função para exibição da página
function conteudoPagina(http, div)
{

	// se estiver carregando...
	if(http.readyState == 1)
	{
			// Quando estiver carregando, exibe: carregando...
			document.getElementById(div).innerHTML = "<center><h2>Carregando...</h2></center>";
	}

	// quando tiver terminado de carregar
	if (http.readyState == 4)
	{
			// checagem de status
			if (http.status == 200)
			{

				// Aqui é onde se mostra a página carregada

				// Conteúdo da página chamada
				var resultado = http.responseText;

				// Resolve o problema dos acentos
				resultado = resultado.replace(/\+/g," ");
				resultado = unescape(resultado);

				// Coloca na página atual o conteúdo da página requisitada pelo AJAX
				document.getElementById(div).innerHTML = resultado;
			}

			// se checagem de status falhar...
			else
			{
				alert('Houve um problema de conexão no servidor. Por favor tente novamente mais tarde.');
			}
	}

}

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

/**
* @author Tiago Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para validação de datas
*/
function jValidaData ( data , campo )
{
	// Validando Data
	dia = (data.substring(0,2)); 
    mes = (data.substring(3,5)); 
	ano = (data.substring(6,10)); 
	
	cons = true; 
			
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		//alert("Preencha a data somente com números."); 
		document.getElementById('data_erro').style.display = '';
		document.getElementById('data_ok').style.display = 'none';
		document.getElementById(campo).className = 'formularioinput_erro';
		document.getElementById('idade').value = '' ; 
		return false;
	}
				
    // verifica o dia valido para cada mes 
    if ( (dia < 1) || (dia < 1 || dia > 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || dia > 31 ) { 
    	cons = false; 
	} 
		
	// verifica se o mes e valido 
	if (mes < 1 || mes > 12 ) { 
		cons = false; 
	} 
		
	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 1 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
	
	hoje = new Date()
		
	if ( ano < hoje.getFullYear() )
	{
		if ( mes < hoje.getMonth() )
		{
			if ( dia < hoje.getDay() )
			{
				cons = false ; 
			}
		}
	}
	
	if (cons == false) { 
		document.getElementById('data_erro').style.display = '';
		document.getElementById('data_ok').style.display = 'none';
		document.getElementById(campo).className = 'formularioinput_erro';
		document.getElementById('idade').value = '' ; 
		return false;
	}
	else
	{
		document.getElementById('data_erro').style.display = 'none';
		document.getElementById('data_ok').style.display = '';
		document.getElementById(campo).className = 'formularioinput';
		document.getElementById('idade').value = '' ;
		jCalculaIdade ( ano , mes , dia ) ;
	} 
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @author Tiago Carvalho projetos@logicadigital.com.br
* @copyright (c) 2006 Lógica Digital
* Descrição: Script para calcular a idade
*/
function jCalculaIdade ( ano , mes , dia )
{
	hoje = new Date()
	
	ano_hoje = hoje.getFullYear() ;
	
	idade = ( ano_hoje - ano ) ;
	
	if ( mes >= hoje.getMonth() + 1 )
	{
		if ( dia > hoje.getDay() + 1 )
		{
			idade = idade - 1 ; 
		}
	}
	
	document.getElementById('idade').value = idade ;
}


/**
 * @author Maikel Finck
 */
function fn_limita_campo ( valor , campo , evento )
{
    var nTecla = '' ;
    if (document.all)
    {
        nTecla = evento.keyCode ;
    }
    else
    {
        nTecla = evento.which ;
    }
    if (( nTecla == 8   )   // backspace
        || ( nTecla == 127 )   // delete
        || ( nTecla == 0   )   // teclas nao definidas
        || ( nTecla == 13  )   // enter
    )
    {
        return true ;
    }
	var tamanho = document.getElementById( campo ).value ;
    tamanho = tamanho.length ;
	if ( tamanho > valor )
	{
		return false ;
	}
	return true ;
}
//desabilita selecionar
function seleciona(){
  document.getElementById('menu').style.cursor = 'default' ;
  function disabletext(e){
    return false
	
  }

  function reEnable(){
    return true 
  }

  //if the browser is IE4+
  document.onselectstart=new Function ("return false")

  //if the browser is NS6
  if (window.sidebar){
    document.onmousedown=disabletext
    document.onclick=reEnable
  }
}

//abilita selecionar
function deselciona(){
  function reEnable(){
    return true
  }

  //if the browser is IE4+
  document.onselectstart=new Function ("return true")

  //if the browser is NS6
  if (window.sidebar){
    document.onmousedown=reEnable
    document.onclick=reEnable
	
  }
}
//funcao pra mostrar ou ocultar borda nas opções de planos
function mostra_planos(num_op)
{
  for(i=1; i<=num_op; i++)
  {
	  if(document.getElementById('p'+i).checked == true)
	  {
		document.getElementById('plano'+i).className = 'borda';
	  }
	  else
	  {
	    document.getElementById('plano'+i).className = 'tabela_planos';
  	  }
  }
}
function AbrePopUp(url, scrollbar) 
{
	 largura = screen.width;
	 altura = screen.height;
	 titulo = 'Vagas_e_Talentos';

	var myWin = window.open(url ,titulo ,'width=' + largura + ', height=' + altura +', scrollbars=yes, toolbar=no, location=no, status=yes, menubar=no, resizable=no, left=10, top=10');
	myWin.focus();
}

