//////////////////////////////////////////////////
// Cursos para Empresas
//////////////////////////////////////////////////
function enviarProposta(theForm){
	/*
	var f = document.form_empresas;	
	var i;
	var total;
	var nomes;
	var err = true;
	for( i=0; i < f.length; i++){
		if(f.elements[i].value != "" && f.elements[i].type == "select"){
			err = false;
			// total = total + f.elements[i].value+";";
			// nomes = nomes + f.elements[i].name+";";
		}
	}
	if(!err){
		// f.elements[0].value = nomes;
		// f.elements[1].value = total;
		f.submit();
	}
	else{
		alert("Por favor, escolha um dos cursos em que esteja interessado,\n"+ 
		"coloque uma quantidade de alunos estimada e confirme os\n"+
		"dados novamente.");
		return false;
	}*/
	// Nome
	if (theForm.nome.value == "")
	{
		alert("Preencha o campo \"Nome\".");
		theForm.nome.focus();
		return false;
	}
	// E-mail
	if (theForm.email.value == ""){
		alert("Preencha o campo \"E-mail\".");
		theForm.email.focus();
	return false;
	}
	if (Valida_Email(theForm) == false)
		return false;
	// Telefone DDD - Se existir
	if(theForm.ddd)
	{
		if (theForm.ddd.value == ""){
			alert("Preencha o campo \"DDD\".");
			theForm.ddd.focus();
		return false;
		}
	}
	// Telefone
	if (theForm.telefone.value == ""){
		alert("Preencha o campo \"Telefone\".");
		theForm.telefone.focus();
	return false;
	}
}

//////////////////////////////////////////////////
// Função para abrir pop-up
//////////////////////////////////////////////////
function abrir(pagina,largura,altura, noscroll,alvo,resizable) {
	var	resize = 'yes';
	var scrollbars = 'yes';
	if(noscroll == null || !noscroll){
		scrollbars = 'no';
	}
	if(resizable == null || !resizable){
		resize = 'no';
	}
	config="toolbar=no,location=no,width="+largura+",height="+altura+",status=0,menubar=no,scrollbars=" + scrollbars + ",resizable=" + resize;
	config=config + ",top=" + ((screen.height - altura) / 2) + ",left=" + ((screen.width - largura) /2);
	popup_window = window.open(pagina,alvo,config);
	popup_window.focus();
}

//////////////////////////////////////////////////
// Função para adicionar aos favoritos
//////////////////////////////////////////////////
function favoritos()
{
	var browser = navigator.appName;
	var bookmarkurl="http://www.portaleducacao.com.br";
	var bookmarktitle="Portal Educação";
	if (browser=="Netscape")
	{
		alert ("Aperte CTRL+D para adicionar o Portal Educação aos seus favoritos")
	}
	else if(browser=="Microsoft Internet Explorer")
	{
		window.external.AddFavorite(bookmarkurl,bookmarktitle)
	}
}

//////////////////////////////////////////////////
// Função para checar ou unchecar todos checkbox
//////////////////////////////////////////////////
function checkaTodos(algumAlterado)
{
	f = validar;
	if (algumAlterado)
	{ 
		if (algumAlterado.checked == false) 
			f.br.checked = false;
	}
	else 
		for (i=0; i<f.length; i++) 
		if (f.elements[i].type == "checkbox")
		if (f.br.checked) f.elements[i].checked = true
		else f.elements[i].checked = false
}

//////////////////////////////////////////////////
// Função para validar Cadastro
//////////////////////////////////////////////////
function Valida_Cadastro(theForm)
{
	//Pessoa Jurídica
	if(document.getElementById('cnpj')) {
		// Se estiver cadastrando pessoa juridica então valida seus dados 
		if(document.getElementById('pjuridica') && document.getElementById('pjuridica').checked == true) {
		
			if(theForm.cnpj.value == ""){
				alert("Preencha o campo \"Cnpj \"da pessoa jurídica.");
				theForm.cnpj.focus();
				return false;	
			}
			if(theForm.nome_empresa.value == ""){
				alert("Preencha o campo \"Nome Empresa \"da pessoa jurídica.");
				theForm.nome_empresa.focus();
				return false;	
			}
			if(theForm.jcep1.value == ""){
				alert("Preencha o campo \"Cep \" da pessoa jurídica.");
				theForm.jcep1.focus();
				return false;	
			}
			if(theForm.jendereco.value == ""){
				alert("Preencha o campo \"Endereço \" da pessoa jurídica.");
				theForm.jendereco.focus();
				return false;	
			}
			if(theForm.jbairro.value == ""){
				alert("Preencha o campo \"Bairro \" da pessoa jurídica.");
				theForm.jbairro.focus();
				return false;	
			}
			
			if(theForm.jcidade.value == ""){
				alert("Preencha o campo \"Cidade \" da pessoa jurídica.");
				theForm.jcidade.focus();
				return false;	
			}
			if(theForm.jendereco_num.value == ""){
				alert("Preencha o campo \"Número \" da pessoa jurídica.");
				theForm.jendereco_num.focus();
				return false;	
			}
			
			if (theForm.atividade.selectedIndex <= 0)
			{
				alert("Por favor selecione uma \"Atividade\" da pessoa jurídica.");
				theForm.atividade.focus();
				return false;
			}
			
				
			
		} 
		
				
	}	
	
	
	// Nome
	if (theForm.nome.value == "")
	{
		alert("Preencha o campo \"Nome\".");
		theForm.nome.focus();
		return false;
	}
	
	// Sexo - Requer que pelo menos um radiobutton esteja selecionado
	var radioSelected = false;
	for (i = 0; i < theForm.sexo.length; i++)
	{
		if (theForm.sexo[i].checked)
			radioSelected = true;
	}
	if (!radioSelected)
	{
		alert("Por favor selecione o \"Sexo\".");
		return false;
	}

	// Endereço
	if (theForm.endereco.value == "")
	{
		alert("Preencha o campo \"Endereço\".");
		theForm.endereco.focus();
		return false;
	}
	if (theForm.endereco.value.length < 3)
	{
		alert("O campo \"Endereço\" não está preenchido corretamente!");
		theForm.endereco.focus();
		return false;
	}

	// Endereço - Número
	if (theForm.endereco_num.value == "")
	{
		alert("Preencha o campo \"Número do Endereço\".");
		theForm.endereco_num.focus();
		return false;
	}
	//isValidDigitNumber(theForm.endereco_num, "Número do Endereço");

	// Bairro
	if (theForm.bairro.value == "")
	{
		alert("Preencha o campo \"Bairro\".");
		theForm.bairro.focus();
		return false;
	}

	// Cidade
	if (theForm.cidade.value == "")
	{
		alert("Preencha o campo \"Cidade\".");
		theForm.cidade.focus();
		return false;
	}
	if (theForm.cidade.value.length < 3)
	{
		alert("O campo \"Cidade\" não está preenchido corretamente!");
		theForm.cidade.focus();
		return false;
	}

	// País
	
	// Estado - Se existir
	if(theForm.estado)
	{
		if (theForm.estado.selectedIndex < 0)
		{
			alert("Por favor selecione um \"Estado\".");
			theForm.estado.focus();
			return false;
		}
	}
	
	// Provincia - Se existir
	if(theForm.provincia)
	{
		if (theForm.provincia.value == "")
		{
			alert("Preencha o campo \"Provincia\".");
			theForm.provincia.focus();
			return false;
		}
	}
	

	// CEP - Se existir cep1
	if(theForm.cep1)
	{
		if (theForm.cep1.value == "")
		{
			alert("Preencha o campo \"CEP\".");
			theForm.cep1.focus();
			return false;
		}
		if (theForm.cep1.value.length < 5){
			alert("O campo \"CEP\" não está preenchido corretamente!");
			theForm.cep1.focus();
			return false;
		}
		if (theForm.cep2.value == "")
		{
			alert("Preencha o campo \"CEP\".");
			theForm.cep2.focus();
			return false;
		}
		if (theForm.cep2.value.length < 3){
			alert("O campo \"CEP\" não está preenchido corretamente!");
			theForm.cep2.focus();
			return false;
		}
	}

	// CEP - Se existir cep
	if(theForm.cep)
	{
		if (theForm.cep.value == "")
		{
			alert("Preencha o campo \"CEP\".");
			theForm.cep.focus();
			return false;
		}
		if (theForm.cep.value.length < 8){
			alert("O campo \"CEP\" não está preenchido corretamente!");
			theForm.cep.focus();
			return false;
		}
	}

	// Telefone DDD - Se existir
	if(theForm.ddd1)
	{
		if (theForm.ddd1.value == ""){
			alert("Preencha o campo \"DDD\".");
			theForm.ddd1.focus();
		return false;
		}
	}

	// Telefone
	if (theForm.fone1.value == ""){
		alert("Preencha o campo \"Telefone\".");
		theForm.fone1.focus();
	return false;
	}

	// Nascimento - Se existir
	if(theForm.dia)
	{
		if (theForm.dia.value == ""){
			alert("Preencha o dia do \"Nascimento\".");
			theForm.dia.focus();
			return false;
		}
		else
		{
			if(theForm.dia.value.length < 2)
			{
				alert("Dia do \"Nascimento\" deve conter 2 dígitos.");
				theForm.dia.focus();
				return false;
			}
		}
		
		if (theForm.mes.value == ""){
			alert("Preencha o mês do \"Nascimento\".");
			theForm.mes.focus();
			return false;
		}
		else
		{
			if(theForm.mes.value.length < 2)
			{
				alert("Mês do \"Nascimento\" deve conter 2 dígitos.");
				theForm.mes.focus();
				return false;
			}
		}
		
		if (theForm.ano.value == ""){
			alert("Preencha o ano do \"Nascimento\".");
			theForm.ano.focus();
			return false;
		}
		else
		{
			if(theForm.ano.value.length < 4)
			{
				alert("Ano do \"Nascimento\" deve conter 4 dígitos.");
				theForm.ano.focus();
				return false;
			}
		}
		
		if (theForm.dia.value < 0 || theForm.dia.value > 31)
		{
			alert("O dia do \"Nascimento\" está incorreto.");
			theForm.dia.focus();
			return false;
		}
		if (theForm.mes.value < 0 || theForm.mes.value > 12)
		{
			alert("O Formato do mês do \"Nascimento\" está incorreto.");
			theForm.mes.focus();
			return false;
		}
		if (theForm.dia.value > 29 && (theForm.mes.value == 02 || theForm.mes.value == 2))
		{
			alert("O dia para o mês de fevereiro do \"Nascimento\" não confere.");
			theForm.dia.focus();
			return false;
		}
	}

	// CPF - Se existir
	if (theForm.cpf)
	{
		if (theForm.cpf.value == ""){
			alert("Preencha o campo \"CPF\".");
			theForm.cpf.focus();
			return false;
		}
		if (Valida_CPF(theForm) == false)
			return false;
	}

	// Profissão
	if(theForm.profissao)
	{
		if (theForm.profissao.selectedIndex <= 0)
		{
			alert("Por favor selecione \"Profissao\".");
			theForm.profissao.focus();
		return (false);
		}
	}

	// Instituição - Se existir
	if(theForm.instituicao)
	{
		if (theForm.instituicao.value == ""){
			alert("Preencha o campo \"Instituição\".");
			theForm.instituicao.focus();
			return false;
		}
	}

	// Como ficou sabendo - Se existir
	if(theForm.como)
	{
		if (theForm.como.selectedIndex <= 0)
		{
			alert("Por favor selecione \"Como ficou sabendo dos cursos\".");
			theForm.como.focus();
		return (false);
		}
	}

	// E-mail
	if (theForm.email.value == ""){
		alert("Preencha o campo \"E-mail\".");
		theForm.email.focus();
		return false;
	}
	if (Valida_Email(theForm) == false)
		return false;
	
	// Senha
	//Adicionado if existir pois em usuarios_detalhes nao ira possuir campo senha
	//caso usuario logado nao seja administrador
	if(theForm.senha)
	{
		if (theForm.senha.value == ""){
			alert("Preencha o campo \"Senha\".");
			theForm.senha.focus();
			return false;
		}
	}

	// Senha2 - Se existir senha2
	if(theForm.senha2)
	{
		// Senha 2
		if (theForm.senha2.value == "")
		{
			alert("Preencha o campo de confirmação de \"Senha\".");
			theForm.senha2.focus();
			return false;
		}
	
		if (theForm.senha.value != theForm.senha2.value)
		{
			alert("As senhas não conferem.");
			theForm.senha.focus();
			return false;
		}
	}
	
	// Valida o campo senha do form em meus_dados.asp em que não é brigatório o preenchimento de senha, mas caso preencha deve preencher tb a confirmação de senha

	if(theForm.senha3)
	{	
		if (theForm.senha3.value != ""){
			
			if(theForm.senha4)
			{
				// Senha 4 confirmação de senha
				if (theForm.senha4.value == "")
				{
					alert("Preencha o campo de confirmação de \"Senha\".");
					theForm.senha4.focus();
					return false;
				}
			
				if (theForm.senha3.value != theForm.senha4.value)
				{
					alert("As senhas não conferem.");
					theForm.senha3.focus();
					return false;
				}
			}
		}
	}
}

//////////////////////////////////////////////////
// Valida Identificação de Residente
//////////////////////////////////////////////////
function Valida_Identificacao(theForm)
{
	// Residente
	var radioSelected = false;
	for (i = 0; i < theForm.residente.length; i++)
	{
		if (theForm.residente[i].checked)
			radioSelected = true;
	}
	if (!radioSelected)
	{
		alert("Por favor selecione o \"Onde você está\".");
	return false;
	}
}

//////////////////////////////////////////////////
// Função que faz uma máscara para cep
//////////////////////////////////////////////////
function Formata_CEP(objeto){
	if (objeto.value.indexOf("-") == -1 && objeto.value.length > 5){ objeto.value = ""; }
	if (objeto.value.length == 5){
		objeto.value += "-";
	}
}
//OnKeyPress="Formata_CEP(this)"


//////////////////////////////////////////////////
// Verifica CPF
//////////////////////////////////////////////////
function Valida_CPF(theForm)
{
var CPF = theForm.cpf.value; 

var POSICAO, I, SOMA, DV, DV_INFORMADO;
var DIGITO = new Array(10);
DV_INFORMADO = CPF.substr(9, 2); 

for (I=0; I<=8; I++) {
 DIGITO[I] = CPF.substr( I, 1);
}

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];
}

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];
 }

DV = DIGITO[9] * 10 + DIGITO[10];
 if (DV != DV_INFORMADO) {
 alert('CPF inválido');
 theForm.cpf.value = '';
 theForm.cpf.focus();
 return false;
 }

 for (I=0; I<=9; I++) {

	if (DIGITO[I] == DIGITO[9] && DIGITO[I] == DIGITO[8] && DIGITO[I] == DIGITO[7] && DIGITO[I] == DIGITO[6] && DIGITO[I] == DIGITO[5] && DIGITO[I] == DIGITO[4] && DIGITO[I] == DIGITO[3] && DIGITO[I] == DIGITO[2] && DIGITO[I] == DIGITO[1] && DIGITO[I] == DIGITO[0]) {
	  alert('CPF inválido');
  	  theForm.cpf.value = '';
      theForm.cpf.focus();
      return false;
    }
 }

}

//////////////////////////////////////////////////
// Função para validar entrada do Informativo
//////////////////////////////////////////////////
function Valida_Informativo(theForm)
{
	// Nome
	if (theForm.nome.value == "")
	{
		alert("Preencha o campo \"Nome\".");
		theForm.nome.focus();
		return false;
	}
	
	// E-mail
	if (theForm.email.value == ""){
		alert("Preencha o campo \"E-mail\".");
		theForm.email.focus();
	return false;
	}
	if (Valida_Email(theForm) == false)
		return false;
}

//////////////////////////////////////////////////
// Função para validar entrada do Indique
//////////////////////////////////////////////////
function Valida_Indique(theForm)
{
	// Nome
	if (theForm.nome.value == "")
	{
		alert("Preencha o campo \"Nome\".");
		theForm.nome.focus();
		return false;
	}
	
	// E-mail
	if (theForm.email.value == ""){
		alert("Preencha o campo \"E-mail\".");
		theForm.email.focus();
	return false;
	}
	if (Valida_Email(theForm) == false)
		return false;
		
	// Destinatário
	if (theForm.destinatario.value == "")
	{
		alert("Preencha o campo \"Destinatário\".");
		theForm.destinatario.focus();
		return false;
	}
	
	// E-mail do destinatário
	if (theForm.emaildestinatario.value == ""){
		alert("Preencha o campo \"E-mail do destinatário\".");
		theForm.emaildestinatario.focus();
	return false;
	}
	if (Valida_Email(theForm) == false)
		return false;
}

//////////////////////////////////////////////////
// Função para validar e-mail
//////////////////////////////////////////////////
/*
function Valida_Email(theForm)
{
	var str = theForm.email.value;
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (!filter.test(str))
	{
		alert("Por favor digite um e-mail válido.");
		return false;
	}

}
*/

function Valida_Email(theForm)
{
	var email = theForm.email.value;
    var BadChars = "*|,\":<>[]{}`\'';()&$#% ";
    var GoodChars = "@.";
    var posarroba = email.indexOf ('@',0);
    if (email.length < 6){
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
    for (var i = 0; i < email.length; i++){
        if (BadChars.indexOf(email.charAt(i)) != -1){
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
    }
    for (var i = 0; i < GoodChars.length; i++){
        if (email.indexOf(GoodChars.charAt(i)) == -1){
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
        if (email.indexOf(GoodChars.charAt(i),0) == 0){
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
        if (email.lastIndexOf(GoodChars.charAt(i)) > email.length-3){
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
    }
    if (email.lastIndexOf('@') > email.lastIndexOf('.')){
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }

    if (email.indexOf ('@.',0) != -1 || email.indexOf ('.@',0) != -1){
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
    if (email.indexOf ('@',posarroba+1) != -1){
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
}

//////////////////////////////////////////////////
// Valida Forma de Pagamento
//////////////////////////////////////////////////
function Valida_Forma_Pagto(theForm)
{
	// Residente
	var radioSelected = false;
	for (i = 0; i < theForm.forma_pagto.length; i++)
	{
		if (theForm.forma_pagto[i].checked)
			radioSelected = true;
	}
	if (!radioSelected)
	{
		alert("Por favor selecione uma Forma de Pagamento.");
	return false;
	}
	//////////////////////////////////////////////////
	// Função para desabilitar um botao, e submeter
	//////////////////////////////////////////////////
	//setTimeout('document.form1.submit()',3000);
	//function desabilita(TheForm, botao)
	//{
	document.formulario_pagto.matricular.disabled = true;
	document.formulario_pagto.matricular.value = '   Enviando, aguarde...   ';
	//}
}

//////////////////////////////////////////////////
// Passa cursos do CEP
//////////////////////////////////////////////////
function passa_cep()
{
var cep = document.form_cadastro.cep1.value;
	if(cep.length==5)
	{
		document.form_cadastro.cep2.focus();
		return false
	}
}

//////////////////////////////////////////////////
// Valida Prova
//////////////////////////////////////////////////
function Valida_Prova(theForm, campo)
{
	for (i = 0; i < 10; i++)
	{
		var nomecampo = parseInt(campo) + parseInt(i);
		alert(nomecampo);

		//var nomecampo1 = nomecampo.toString()
		//alert(nomecampo1);
		
		var radioSelected = false;
		for (i = 0; i < theForm.nomecampo.length; i++)
		{
			if (theForm.nomecampo[i].checked)
				radioSelected = true;
		}
		if (!radioSelected)
		{
			alert("Há perguntas não respondidas nesta Prova. Por favor verifique se todas as respostas estão marcadas.");
		return false;
		}
	}
}

//////////////////////////////////////////////////
// FAQ
//////////////////////////////////////////////////
function changeVisibility(id) {
  if (document.getElementById(id).style.display != "inline")
    document.getElementById(id).style.display="inline";
  else
    document.getElementById(id).style.display="none";
}

var answers = new Array(0);

function setVisibility(id, visibility) {
  if (visibility)
    document.getElementById(id).style.display="inline";
  else
    document.getElementById(id).style.display="none";
}

function expand(visibility) {
  for (i = 0 ; i < answers.length ; i++) {
    setVisibility(answers[i], visibility);
  }
}

function openChecked() {
    var formulary = document.form;
    for (i = 0; i< formulary.elements.length; i++) {
        var element = formulary.elements[i];
        // alert("element = " + element.name);
        if (element.type == "checkbox" && element.checked) {
            // var parent = element.parentNode.parentNode.parentNode.nodeName;

            var parent = element.parentNode;

            while (parent != null && parent.nodeName != "DIV") {
                parent = parent.parentNode;
            }

            // alert("parent = " + parent.nodeName);

            // if (parent.nodeName == "DIV") {
                
            if (parent != null && parent.nodeName == "DIV") {
               // var par_element = element.parentNode.parentNode.parentNode;
               // alert("Check box! Parent node = " + par_element.nodeName);
               // alert("Name of the div = " + parent.id);
               
               if (parent.id != "") {
                  var avo = parent.parentNode;

                  // alert("Grand parent node = " + avo.id);
                  
                  document.getElementById(parent.id).style.display="inline";
                  // changeVisibility(par_element.id);

                   if (avo.id != "") {
                       document.getElementById(avo.id).style.display="inline";
                       // changeVisibility(avo.id);
                   }
               }
            }
        }
    }
}

//////////////////////////////////////////////////
// USUARIOS
//////////////////////////////////////////////////
function changecheckVisibility(id) {

	if (document.getElementById(id).style.display != "inline")
    	document.getElementById(id).style.display = "inline";
  	else
    	document.getElementById(id).style.display = "none";
}




/////////////////////////////////////////////////////////////////////////
// Formata cnpj  
// Forma de uso  ==> onKeyPress="javascript:FormataCNPJ(this,event);"
/////////////////////////////////////////////////////////////////////////
function FormataCNPJ(Campo, teclapres){

   var tecla = teclapres.keyCode;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1 ;

   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
}

//////////////////////////////////////////////////////////////
// Verifica se o CNPJ é válido
// Forma de usar onBlur="javascript:validaCnpj(this.value)"
///////////////////////////////////////////////////////////////
function validaCnpj(s)
{

	var i;
	
	 s = s.replace('-',''); 	
	 s = s.replace('/','');
	 s = s.replace('.','');
 	 s = s.replace('.','');
	
	 
	 var c = s.substr(0,12);	
	 var dv = s.substr(12,2);	
	 var d1 = 0;
		
	 for (i = 0; i < 12; i++)	
	 {
	  	d1 += c.charAt(11-i)*(2+(i % 8));	
	 }
		 	
	if (d1 == 0) { 
		return false; 
		s.focus();
	}
	
	d1 = 11 - (d1 % 11);
		
	if (d1 > 9) d1 = 0;
	
	if (dv.charAt(0) != d1)	
	{	
		 return false;	
		 s.focus();
	}
		
	 d1 *= 2;
	
	 for (i = 0; i < 12; i++)	
	{	
		 d1 += c.charAt(11-i)*(2+((i+1) % 8));	
	}
	
	d1 = 11 - (d1 % 11);
	
	if (d1 > 9) d1 = 0;
	
	
	if (dv.charAt(1) != d1)	
	{	
		 return false;
		 s.focus();
	}
	
    return true;

}


// Verifica se a empresa já foi cadastrada
// Passa o cnpj e os id´s dos itens de retorno.
function verificaPessoaJuridica (id,cnpj,cep,endereco,bairro,cidade,complemento,numero,atividade,estado,nome_empresa) {

try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}


xmlhttp.open("GET", "../../sistema/codigo/verifica_cadastro_pjuridica.asp?cnpj="+cnpj,true);
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4){
	     var texto = xmlhttp.responseText;
		 var dados = texto.split("#");
        
		if (dados[0] != '') {

			// Atualiza valores			
			document.getElementById(id).value = dados[0];
			document.getElementById(cep).value = dados[6];
			document.getElementById(endereco).value = dados[2];					
			document.getElementById(bairro).value = dados[4];
			document.getElementById(cidade).value = dados[7];
			document.getElementById(numero).value = dados[3];
			document.getElementById(complemento).value = dados[5];
			document.getElementById(nome_empresa).value = dados[10];	

			
						
			for(var i=0; i<document.getElementById("atividade").options.length; i++) {
             			
			            if(document.getElementById("atividade").options[i].value == dados[8])
                            document.getElementById("atividade").selectedIndex = i;
			}
			for(var i=0; i<document.getElementById(estado).options.length; i++) {
             			
			            if(document.getElementById(estado).options[i].value == dados[9])
                            document.getElementById(estado).selectedIndex = i;
			}
			
		}											
    }
}
xmlhttp.send(null)
}

//redimensiona iframes
function calcHeight(objIFrame)
{
  //find the height of the internal page
  var the_height= objIFrame.contentWindow.document.body.scrollHeight;

  //change the height of the iframe
  objIFrame.height= the_height;
}

//copia o conteudo do iframe para o div
function insertIt() 
{
	var _y = document.getElementById('framediv');
	var _x = window.frames[0].document.body.innerHTML;
	_y.innerHTML = _x;
} 

//copia o conteudo do iframe para o div
function insertIt2(iframename) 
{
	var _y = document.getElementById('framediv');
	var _x = window.frames[iframename].document.getElementById('content').innerHTML;
	_y.innerHTML = _x;
}

function expandCollapse(element) 
{	
	element.style.display = (element.style.display == "none") ? "block" : "none";
}


/******************* 
 Animated Expand Collapse Var And Functions START
							*******************/
	var timerlen = 3;
	var slideAniLen = 1000;
	
	var timerID = new Array();
	var startTime = new Array();
	var obj = new Array();
	var endHeight = new Array();
	var moving = new Array();
	var dir = new Array();
	
function animatedExpandCollapse(rowId) 
{	
	var divId = 'div_' + rowId;

	if(document.getElementById(divId).style.display == "none")
		slidedown(divId);
	else
		slideup(divId);
}

function slidedown(objname)
{
  if(moving[objname])
    return;
 
  if(document.getElementById(objname).style.display != "none")
    return; // cannot slide down something that is already visible
 
  moving[objname] = true;
  dir[objname] = "down";
  startslide(objname);
}
 
function slideup(objname)
{
  if(moving[objname])
    return;
 
  if(document.getElementById(objname).style.display == "none")
    return; // cannot slide up something that is already hidden
 
  moving[objname] = true;
  dir[objname] = "up";
  startslide(objname);
}

function startslide(objname)
{
	obj[objname] = document.getElementById(objname);
	
	if(dir[objname] == "down")
	{
		obj[objname].style.height = "1px";
	}
	
	obj[objname].style.display = "block";
	startTime[objname] = (new Date()).getTime();
	endHeight[objname] = obj[objname].scrollHeight;
	
	timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}

function slidetick(objname)
{
  var elapsed = (new Date()).getTime() - startTime[objname];
 
  if (elapsed > slideAniLen)
    endSlide(objname)
  else 
  {
    var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
    if(dir[objname] == "up")
      d = endHeight[objname] - d;
 
    obj[objname].style.height = d + "px";
  }
 
  return;
}

function endSlide(objname)
{
  clearInterval(timerID[objname]);
 
  if(dir[objname] == "up")
    obj[objname].style.display = "none";
 
  obj[objname].style.height = endHeight[objname] + "px";
 
  delete(moving[objname]);
  delete(timerID[objname]);
  delete(startTime[objname]);
  delete(endHeight[objname]);
  delete(obj[objname]);
  delete(dir[objname]);
 
  return;
}

/******************* 
 Animated Expand Collapse Var And Functions END
							*******************/


// Altera a visibilidade do cadastro de pessoa jurídica
function alteraVisibilidade(id,element) {
	
	if (element.id == "pfisica")
		document.getElementById(id).style.display = "none";
	else 
		document.getElementById(id).style.display = "block";
		
		
}

//Valida campos obrigatórios do cadastro de cupom =================================
function validaCadCupom(frm) {
		
		if (frm.data_expira.value == "") {
			alert("Selecione a data de expiração.");
			return false;
		
		} else {
		
			for(i=0; i < frm.elements.length; i++) {	
				
				if(frm.elements[i].name == 'idutilizacao' && frm.elements[i].type == 'radio') {
					
					if (frm.elements[i].checked == true) {
					
						return true;						
					}	
				}		
			}
			
			alert('Selecione a utilização do cupom.');
			return false;
		}
	
	}
