/* Verifica qual a origem escolhida. Se for "Outros" exibe linha para o usuário digitar, senão retira essa linha. */
function verOutraOrigemAbre(){
	
	var origem = document.getElementById('origem').value.split("||")[1];
	
	if(origem == 'Outros'){
		document.getElementById('origemOutro').innerHTML = '<label>'+
        '<span class="display_block span_atendimento">Qual? <span class="obrigatorios">*</span></span>'+
        '<input type="text" id="outroorigem" name="outroorigem" maxlength="13" maxlength="150" value="" />'+
        '</label>'; 
		document.getElementById('outroorigem').focus();
	}
	else if(origem != ''){
		document.getElementById('origemOutro').innerHTML = '';
	}
}

//Abre campos de login e senha para clientes já cadastrados
function abreLogin(){
	
	if(document.getElementById('esqueci').style.display == 'none'){
	  document.getElementById('controle_do_acesso2').style.height = '210px';
	  document.getElementById('acesso2').style.height = '210px';
	  document.getElementById('disp1').style.display = 'block';
	  document.getElementById('disp3').style.display = 'block';
	  document.getElementById('esqueci').style.display = 'block';
	  document.getElementById('jaCadastrado').innerHTML = '<strong>&laquo; Já sou cadastrado</strong>';
	}
	else{
	  document.getElementById('controle_do_acesso2').style.height = '96px';
	  document.getElementById('acesso2').style.height = '96px';
	  document.getElementById('disp1').style.display = 'none';
	  document.getElementById('disp3').style.display = 'none';
	  document.getElementById('esqueci').style.display = 'none';
	  document.getElementById('jaCadastrado').innerHTML = '<strong>&raquo; Já sou cadastrado</strong>';
	}
}

/* Verifica qual o segmento escolhido. Se for "Outros" exibe linha para o usuário digitar, senão retira essa linha. */
function verOutroRamoAbre(){
	
	var ramo = document.getElementById('segmento').value.split("||")[1];
	
	if(ramo == 'Outros'){
		document.getElementById('outroSegmento').innerHTML = '<label>'+
        '<span class="display_block span_atendimento">Qual? <span class="obrigatorios">*</span></span>'+
        '<input type="text" id="ramoOutro" name="ramoOutro" maxlength="13" maxlength="150" value="" />'+
        '</label>';
		document.getElementById('ramoOutro').focus();
	}
	else if(ramo != ''){
		document.getElementById('outroSegmento').innerHTML = '';
	}
}

function formataData(id, obj, e){

 formdata(obj);

} 
function formdata(val){

	var pass = val.value;
	var expr = /[0123456789]/;
	
	for(i=0; i<pass.length; i++){
		
 // charAt -> retorna o caractere posicionado no índice especificado
 var lchar = val.value.charAt(i);
 var nchar = val.value.charAt(i+1);

 if(i==0){
	 if ((lchar.search(expr) != 0) || (lchar>3)){
		val.value = "";
	 }
 }
 else if(i==1){

	if(lchar.search(expr) != 0){
		var tst1 = val.value.substring(0,(i));
 		val.value = tst1;
 		continue;
	}

 	if ((nchar != '/') && (nchar != '')){
		var tst1 = val.value.substring(0, (i)+1);

 	if(nchar.search(expr) != 0)
		var tst2 = val.value.substring(i+2, pass.length);
 	else
 		var tst2 = val.value.substring(i+1, pass.length);
		val.value = tst1 + '/' + tst2;
 	}

 }
 else if(i==4)
 {

 if(lchar.search(expr) != 0){
 var tst1 = val.value.substring(0, (i));
 val.value = tst1;
 continue;
 }

 if ((nchar != '/') && (nchar != '')){
 var tst1 = val.value.substring(0, (i)+1);

if(nchar.search(expr) != 0)
 var tst2 = val.value.substring(i+2, pass.length);
else
var tst2 = val.value.substring(i+1, pass.length);

val.value = tst1 + '/' + tst2;
}
}

		if(i>=6){
		
			if(lchar.search(expr) != 0) {
				var tst1 = val.value.substring(0, (i));
				val.value = tst1;
			}
		}
	}
	if(pass.length>10)
	val.value = val.value.substring(0, 10);
 	return true;
} 

function modificaTel(){

	var estado = document.getElementById('estado').value;

	switch(estado){
		case 'Acre':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address>';
			break;
		}
		case 'Alagoas':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'Amapa':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address>';
			break;
		}
		case 'Amazonas':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address>';
			break;
		}
		case 'Bahia':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Salvador - BA</h4><address>(71) 4062-0704</address>';
			break;
		}
		case 'Ceara':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'DistritoFederal':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Distrito Federal - DF</h4><address>(61) 2626-1530</address>';
			break;
		}
		case 'EspiritoSanto':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Belo Horizonte - MG</h4><address>(31) 4062-0704</address><br /><h4>Rio de Janeiro -RJ</h4><address>(21) 4062-0704</address>';
			break;
		}
		case 'Goias':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Goiania - GO</h4><address>(62) 4052-0704</address><br /><h4>Brasília - DF</h4><address>(61) 4062-0704</address>';
			break;
		}
		case 'Maranhao':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address><br /><h4>Salvador - BA</h4><address>(71) 4062-0704</address>';
			break;
		}
		case 'MatoGrosso':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address>';
			break;
		}
		case 'MatoGrossoSul':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Campo Grande - MS</h4><address>(67) 4062-0704</address>';

			break;
		}
		case 'MinasGerais':{
		document.getElementById('aparece-telefone').innerHTML = '<h4>Belo Horizonte - MG</h4><address>(31) 4062-0704</address>';

			break;
		}
		case 'Para':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address>';

			break;
		}
		case 'Paraiba':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'Parana':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Curitiba - PR</h4><address>(41) 4062-0704</address>';
			break;
		}
		case 'Pernambuco':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'Piaui':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address><br /><h4>Salvador - BA</h4><address>(71) 4062-0704</address>';
			break;
		}
		case 'RioJaneiro':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Rio de Janeiro - RJ</h4><address>(21) 4062-0704</address>';
			break;
		}
		case 'RioGrandeNorte':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'RioGrandeSul':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Porto Alegre - RS</h4><address>(51) 4062-0704</address>';
			break;
		}
		case 'SantaCatarina':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Florianópolis - SC</h4><address>(48) 4062-0704</address>';
			break;
		}
		case 'SaoPaulo':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>São Paulo - SP</h4><address>(11) 4062-0704</address>';
			break;
		}
		case 'Sergipe':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Recife - PE</h4><address>(81) 4062-0704</address>';
			break;
		}
		case 'Tocantins':{
			document.getElementById('aparece-telefone').innerHTML = '<h4>Cuiabá - MT</h4><address>(65) 4062-0704</address><br /><h4>Brasília - DF</h4><address>(61) 4062-0704</address><br /><h4>Salvador - BA</h4><address>(71) 4062-0704</address><br /><h4>Goiania - GO</h4><address>(62) 4052-0704</address>';
			break;
		}
	}

}

function soNums(e,args)
{		
	var indice='';
	if (!e) var e = window.event; 	
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);  
	var keyCode = (isNN) ? e.which : e.keyCode;   
	var keyClick = (isNN) ? e.which : e.button; 
	
	var nKeyCode = e.keyCode;

	// as teclas numÃ©ricas vÃ£o de 48 a 57
	if (keyCode <20 || (keyCode >47 && keyCode<58))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function pessoaJuridica(verif){
	
	if (verif == 's'){
		document.getElementById('pessoaJuridica').innerHTML = '<div class="item_form"><label>Razão Social:<span class="asterisco">*</span><br />'+
		'<input name="razaoSocial" id="razaoSocial" type="text" /></label></div>'+
		'<div class="item_form input_left"><label>Nome Fantasia:<span class="asterisco">*</span><br />'+
		'<input name="nomeFant" id="nomeFant" type="text"/></label></div>'+
		'<div class="item_form input_right"><label>CNPJ:<span class="asterisco">*</span><br />'+
		'<input name="campocnpj" id="campocnpj" type="text" onkeyup="validaFormulario(\'campocnpj\', \'cnpj\', this, event)" onkeypress="return(soNums(event, \'\'))" maxlength="18"></label></div>';
	}
	else{
		document.getElementById('pessoaJuridica').innerHTML = '';
	}
}

function validaFormularioTotal(){
	
	document.getElementById('superIDContinuar').onclick = '';

	var pendencias = '<ul>';
	var campoInvalido = false;
	var campoVazio = false;

	//Roda se for pessoa jurídica
	if(document.getElementById('oppessoa2').checked == true){
		if(document.getElementById('razaoSocial')){
			if(document.getElementById('razaoSocial').value == ""){
				pendencias += '<li> Razão Social';
				campoVazio = true;
			}
		}
		if(document.getElementById('nomeFant')){
			if(document.getElementById('nomeFant').value == ""){
				pendencias += '<li> Nome Fantasia';
				campoVazio = true;
			}
		}
		if(document.getElementById('campocnpj').value == ""){
			pendencias += '<li> CNPJ';
			campoVazio = true;
		}
		else if(!valida_cnpj(document.getElementById('campocnpj').value)){
			pendencias += '<li> CNPJ';
			campoInvalido = true;
		}
	}
	
	if(document.getElementById('cmpresponsavel').value == ""){
		pendencias += '<li> Nome do Responsável';
		campoVazio = true;
	}
	
	if(document.getElementById('emailPrimario').value == ""){
		pendencias += '<li> E-mail Primário';
		campoVazio = true;
	}
	
	if(document.getElementById('campotel').value == ""){
		pendencias += '<li> Telefone Fixo';
		campoVazio = true;
	}
	else if(document.getElementById('campotel').value.length != 13){
		pendencias += '<li> Telefone Fixo';
		campoInvalido = true;
	}
	
	if(document.getElementById('campocel').value == ""){
		pendencias += '<li> Telefone Celular';
		campoVazio = true;
	}
	else if(document.getElementById('campocel').value.length != 13){
		pendencias += '<li> Telefone Celular';
		campoInvalido = true;
	}

	if(document.getElementById('campocpf').value == ""){
		pendencias += '<li> CPF';
		campoVazio = true;
	}
	else if(!valida_cpf(document.getElementById('campocpf').value)){
			pendencias += '<li> CPF';
			campoInvalido = true;
	}

	if(document.getElementById('campocep').value == ""){
		pendencias += '<li> CEP';
		campoVazio = true;
	}
	else if(verificaCEP(document.getElementById('campocep').value)){
			pendencias += '<li> CEP (inexistente)';
			campoInvalido = true;
	}
	
	if(document.getElementById('rua').value == ""){
		pendencias += '<li> Rua, Av, Praça ou Travessa';
		campoVazio = true;
	}
	
	if(document.getElementById('numero').value == ""){
		pendencias += '<li> Número da Residência';
		campoVazio = true;
	}
	
	if(document.getElementById('bairro').value == ""){
		pendencias += '<li> Bairro';
		campoVazio = true;
	}
	
	if(document.getElementById('cidade').value == ""){
		pendencias += '<li> Cidade';
		campoVazio = true;
	}
	
	if(document.getElementById('uf').value == "vazio"){
		pendencias += '<li> Estado';
		campoVazio = true;
	}
	
	if(document.getElementById('msg').value == ""){
		pendencias += '<li> Descrição do Negócio';
		campoVazio = true;
	}
	
	if(document.getElementById('nomeref1').value == ""){
		pendencias += '<li> Nome da Primeira Referência';
		campoVazio = true;
	}
	
	if(document.getElementById('telref1').value == ""){
		pendencias += '<li> Telefone da Primeira Referência';
		campoVazio = true;
	}
	else if(document.getElementById('telref1').value.length != 13){
		pendencias += '<li> Telefone da Primeira Referência';
		campoInvalido = true;
	}
	
	if(document.getElementById('nomeref2').value == ""){
		pendencias += '<li> Nome da Segunda Referência';
		campoVazio = true;
	}
	
	if(document.getElementById('telref2').value == ""){
		pendencias += '<li> Telefone da Segunda Referência';
		campoVazio = true;
	}
	else if(document.getElementById('telref2').value.length != 13){
		pendencias += '<li> Telefone da Segunda Referência';
		campoInvalido = true;
	}

	pendencias += '</ul>';
	
	if(campoVazio == true || campoInvalido == true){
		document.getElementById('erro').innerHTML = "Por favor, verifique os seguintes campos: <br /> <br />" + pendencias;
		document.getElementById('superIDContinuar').onclick = function() { validaFormularioTotal(); };
	}
	else{
		//Dá submit no formulario
		document.formcadastro.submit(); 
		document.getElementById('superIDContinuar').onclick = function() { validaFormularioTotal(); };
		//===> abrirconta_final.php (neste arquivo inserimos a informação em precadastro)
		
		/*
		var nome = document.getElementById('cmpresponsavel').value;
		var email1 = document.getElementById('emailPrimario').value;
		var email2 = document.getElementById('emailSecundario').value;
		var telefone = document.getElementById('campotel').value;
		var celular = document.getElementById('campocel').value;
		var cpf = document.getElementById('campocpf').value;
		var website = document.getElementById('website').value;
		var cep = document.getElementById('campocep').value;
		var rua = document.getElementById('rua').value;
		var numero = document.getElementById('numero').value;
		var bairro = document.getElementById('bairro').value;
		var cidade = document.getElementById('cidade').value;
		var complemento = document.getElementById('complemento').value;
		var estado = document.getElementById('uf').value;
		var descricao = document.getElementById('msg').value;
		var nomeReferencia1 = document.getElementById('nomeref1').value;
		var nomeReferencia2 = document.getElementById('nomeref2').value;
		var telReferencia1 = document.getElementById('telref1').value;
		var telReferencia2 = document.getElementById('telref2').value;
		
		if(document.getElementById('oppessoa2').checked == true){
			var razaoSocial = document.getElementById('razaoSocial').value;
			var cnpj = document.getElementById('nomeFant').value;
			var nomeFantasia = document.getElementById('campocnpj').value;
		}*/
		
	}
	

}

function validaFormulario(idCampo, tipo, obj, e){

	switch(tipo){
		case 'cep': {
			formataCep(idCampo);
			break;
		}
		case 'tel':{
			formataTel(obj,e);
			break;
		}
		case 'cpf':{
			document.getElementById(idCampo).value = formataCpf(obj.value);
			break;
		}
		case 'cnpj':{
			document.getElementById(idCampo).value = formataCnpj(obj.value);
			break;
		}
	}
}

function formataCep(id)
{
	var campo = document.getElementById(id);
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( ".", "" );
	var tam = vr.length;
	if (tam < 8) { tam = vr.length + 1; }
		tam = tam - 1;
	if ( (tam > 2) && (tam <= 8) ) 
	{
		vr = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ); 
	}
	if ( (tam == 7) ) 
	{
		vr = vr.substr( 0, tam - 5 ) + '' + vr.substr( tam - 5, tam ); 
	}
	campo.value = vr;
}

function formataTel(args, e)
{
	var sMask = '(99)9999-9999';
	var objeto=args;
	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
	if(document.all) 
	{ // Internet Explorer
		nTecla = e.keyCode;
	} 
	else if(document.layers) 
	{ // Nestcape
	nTecla = e.which;
	} 
	else 
	{
		nTecla = e.which;
		if (nTecla == 8) 
		{
			return true;
		}
	}
	sValue = objeto.value;
	
	// Limpa todos os caracteres de formatação que
	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( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;
	
	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;
	
	while (i <= mskLen)
	{
		bolMask = ((sMask.charAt(i) == "-") || (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++;
	}

	if (sCod=='(0')
	{
		objeto.value = '(';
	}
	else
	{
		objeto.value = sCod;
	}
	
	if (nTecla != 8)
	{ // backspace
		if (sMask.charAt(i-1) == "9")
		{ // apenas números...
			return ((nTecla > 47) && (nTecla < 58));
		}
		else
		{ // qualquer caracter...
			return true;
		}
	}
	else 
	{
		return true;
	}
}

function soNums(e,args)
{		
	var indice='';
	if (!e) var e = window.event; 	
	var isNN = (navigator.appName.indexOf("Netscape")!=-1);  
	var keyCode = (isNN) ? e.which : e.keyCode;   
	var keyClick = (isNN) ? e.which : e.button; 
	
	var nKeyCode = e.keyCode;

	// as teclas numÃ©ricas vÃ£o de 48 a 57
	if (keyCode <20 || (keyCode >47 && keyCode<58))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function valida_cpf(cpf)
{
	
	var vr = cpf;
		vr = vr.replace( "-", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
	cpf = vr;
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	digitos_iguais = 1;
	if (cpf.length < 11 || cpf.length > 11)
		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))
			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)) 
			return false;
			return true;
	}
	else
		return false;
}

function valida_cnpj(cnpj)
{
	var vr = cnpj;
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( "-", "" );
	cnpj = vr;	
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	if (cnpj.length < 14 && cnpj.length < 15)
	  return false;
	for (i = 0; i < cnpj.length - 1; i++)
	if (cnpj.charAt(i) != cnpj.charAt(i + 1))
	{
		digitos_iguais = 0;
		break;
	}
	if (!digitos_iguais)
	{
		tamanho = cnpj.length - 2
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
		{
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0))
			  return false;
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--)
		{
			soma += numeros.charAt(tamanho - i) * pos--;
			if (pos < 2)
				pos = 9;
		}
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1))
			return false;
			return true;
		}
		else
			return false;
}

function formataCnpj(v)
{
	v=v.replace(/\D/g,"");	//Remove tudo o que não é dígito
	v=v.replace(/^(\d{2})(\d)/,"$1.$2");	//Coloca ponto entre o segundo e o terceiro dígitos
	v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3");	//Coloca ponto entre o quinto e o sexto dígitos
	v=v.replace(/\.(\d{3})(\d)/,".$1/$2");	//Coloca uma barra entre o oitavo e o nono dígitos
	v=v.replace(/(\d{4})(\d)/,"$1-$2");	//Coloca um hífen depois do bloco de quatro dígitos
	return v;
}

function formataCpf(v)
{
	v=v.replace(/\D/g,"");	//Remove tudo o que não é dígito
	v=v.replace(/(\d{3})(\d)/,"$1.$2");	//Coloca um ponto entre o terceiro e o quarto dígitos
	v=v.replace(/(\d{3})(\d)/,"$1.$2");	//Coloca um ponto entre o terceiro e o quarto dígitos
										//de novo (para o segundo bloco de números)
	v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2");	//Coloca um hífen entre o terceiro e o quarto dígitos
	return v;
}

function getHTTPObject() 
{
  var xmlhttpurl;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttpurl = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      try {
        xmlhttpurl = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
        xmlhttpurl = false;
        }
      }
  @else
  xmlhttpurl = false;
  @end @*/
  if (!xmlhttpurl && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttpurl = new XMLHttpRequest();
      } catch (e) {
      xmlhttpurl = false;
      }
    }
  return xmlhttpurl;
}

var httpcep = new getHTTPObject();
function carregaCEP(cep, p){

	var cepnovo = cep;
		cepnovo = cepnovo.replace( "-", "" );
		cep = cepnovo;
	if(cep.length != 8){ alert("Por favor, digite um CEP válido."); return; }
	
	httpcep.open("GET", './buscacidadecep.php?cep='+cep+'&p='+p, true); 
	httpcep.onreadystatechange = handlehttpResponsedestac;
	httpcep.send(null);
	handlehttpResponsedestac();
    
	function handlehttpResponsedestac(){
		
		if (httpcep.readyState == 4) {
			if (httpcep.status == 200) {
				var response = httpcep.responseText;
				if(response == 'n'){ alert("Por favor, digite um CEP válido."); return; }
					eval("var resposta = "+ response);
					document.getElementById('cidade').value = resposta.nomecidade;
					document.getElementById('uf').value = resposta.nomeuf;
					document.getElementById('bairro').value = resposta.bairro;
					document.getElementById('rua').value = resposta.logradouro;
//					retiraSelecao('cidade');
//					retiraSelecao('uf');
//					retiraSelecao('bairro');
//					retiraSelecao('rua');
			}
		}
	}
}

var httpcep2 = new getHTTPObject();
function verificaCEP(cep){
	
	var cepnovo = cep;
		cepnovo = cepnovo.replace( "-", "" );
	cep = cepnovo;
	if(cep.length != 8){ return false; }
	
	httpcep2.open("GET", './buscacidadecep.php?cep='+cep, true); 
	httpcep2.onreadystatechange = handlehttpResponsedestac;
	httpcep2.send(null);
	handlehttpResponsedestac();
    
	function handlehttpResponsedestac(){
		
		if (httpcep2.readyState == 4) {
			if (httpcep2.status == 200) {
				var response = httpcep2.responseText;
				if(response == 'n'){ return false; }
				return true;
			}
		}
	}
}

/* Se o campo não estiver vazio busca no banco de dados perguntas relacionadas à expressão digitada pelo usuário, exibe na div 'FAQ' e a quantidade de respostas encontradas na div 'respostasAA'. */
var httpcontext = new getHTTPObject();
function buscaPerguntas(id){

	if(document.getElementById(id).value != ''){
		//Faz uma requisição para pegar todas as peguntas relacionadas à expressão digitada pelo usuário.
		var endereco = './opatendext.php?op=3';
		var conteudo = '&expressao=' + document.getElementById(id).value;
		
		httpcontext.open('GET', endereco + conteudo, true); 
		httpcontext.onreadystatechange = function handlehttpResponseBot(){
			if (httpcontext.readyState == 4){
				if(httpcontext.status == 200){
					fimBuscaPerguntas(httpcontext.responseText);
				}
			}    
		}
		httpcontext.send(null);
	}

}

/* Finaliza a busca de perguntas. */
function fimBuscaPerguntas(response){
	eval("var arr="+response);

	//Se id nao é vazio
	if(arr.id != ''){
		var ids = arr.id.split("{||}");
		var perguntas = arr.pergunta.split("{||}");
		var qtde = ids.length;
		var conteudo = '';
		qtde --;
		
		for(var x = 0; x < qtde; x ++){
			conteudo += '<ul>';
			conteudo += '<li class="assunto">'+
						  '<div id="P' + ids[x] + '" onclick="abreResposta(\'' + ids[x] + '\')">'+
							'<h3>'+ perguntas[x] +'</h3>'+
						 '</div>'+
						 '<div class="resposta_FAQ" id="R' + ids[x] + '"></div>'+
						'<a class="ver_mais" onclick="abreResposta('+ids[x]+')" >Ver resposta</a>'+

					'</li>';
			conteudo += '</ul>';
		}		

		if(qtde == 1){
			document.getElementById('totalPerguntas').innerHTML = qtde + " pergunta foi encontrada.";
		}
		else{
			document.getElementById('totalPerguntas').innerHTML = qtde + " perguntas foram encontradas.";
		}
		
		document.getElementById('FAQ').innerHTML = conteudo;	

	}
	else{
		document.getElementById('totalPerguntas').innerHTML = "Nenhuma pergunta foi encontrada.";
		document.getElementById('FAQ').innerHTML = '';
	}
}

/* Faz uma requisição para pegar a resposta a determinada pergunta. */
var httpcontext2 = new getHTTPObject();
function abreResposta(id){
	var resid = 'R' + id;
	
	//Se a resposta não estiver vazia, quer dizer que o usuário já viu seu conteúdo. Logo, insere '' nela para "fechar"
	if(document.getElementById(resid).innerHTML != ''){
		document.getElementById(resid).innerHTML = '';
	}
	//Senão, faz uma requisição para pegar a resposta
	else{
		var endereco = './opatendext.php?op=4';
		var conteudo = '&id=' + id;
		var tipoReq = 'GET';
		
		httpcontext2.open(tipoReq, endereco + conteudo, true); 
		httpcontext2.onreadystatechange = function handlehttpResponseBot(){
			if (httpcontext2.readyState == 4){
				if(httpcontext2.status == 200){
					fimAbreResposta(httpcontext2.responseText, id);
	
				}
			}    
		}
		httpcontext2.send(null);
	
		/* Insere a resposta abaixo da pergunta clicada. */
		function fimAbreResposta(response, id){
			var resid = 'R' + id;
			
			//Arrumando a resposta
			response = response.split("::");
			var resp = 'RE: ' + response[0];
			for(var x = 1; x < response.length; x ++){
				resp += '<br/><br/>:: ' + response[x];
			}
			
			//Insere a resposta 
			document.getElementById(resid).innerHTML = resp;
		}
	}
}

/* Verifica qual a origem escolhida. Se for "Outros" exibe linha para o usuário digitar, senão retira essa linha. */
function verOutraOrigem(){
	
	var origem = document.getElementById('origem').value.split("||")[1];
	
	if(origem == 'Outros'){
		document.getElementById('origemOutro').innerHTML = '<label>'+
        '<span class="display_block span_atendimento">Qual? <span class="obrigatorios">*</span></span>'+
        '<input type="text" id="outroorigem" name="outroorigem" maxlength="13" maxlength="150" value="" />'+
        '</label>'; 
		document.getElementById('outroorigem').focus();
	}
	else if(origem != ''){
		document.getElementById('origemOutro').innerHTML = '';
	}
}

/* Verifica qual o segmento escolhido. Se for "Outros" exibe linha para o usuário digitar, senão retira essa linha. */
function verOutroRamo(){
	
	var ramo = document.getElementById('segmento').value.split("||")[1];
	
	if(ramo == 'Outros'){
		document.getElementById('outroSegmento').innerHTML = '<label>'+
        '<span class="display_block span_atendimento">Qual? <span class="obrigatorios">*</span></span>'+
        '<input type="text" id="ramoOutro" name="ramoOutro" maxlength="13" maxlength="150" value="" />'+
        '</label>';
		document.getElementById('ramoOutro').focus();
	}
	else if(ramo != ''){
		document.getElementById('outroSegmento').innerHTML = '';
	}
}

/* Envia a mensagem pelo contato externo. */
var httpenviaMsg = new getHTTPObject();
function enviaMensagem(tipo){
					
 	var valido = validaEnviarMensagem(tipo);
	var nome = '';
	var email = '';
	var segmento = '';
	var origem = '';
	var assunto = '';
	var telefone = '';
	var msg = '';

	if(valido){
		document.getElementById('enviarBt').onclick = '';
		document.getElementById('enviarBt').innerHTML = 'Aguarde';  
		//Pegando dados
		if(!tipo || (tipo == 0)){
			nome = document.getElementById('nome').value;
			email = document.getElementById('email').value;
			segmento = document.getElementById('segmento').value;
			if(segmento.split("||")[1] == 'Outros'){
				segmento = document.getElementById('ramoOutro').value;
			}
			else{
				segmento = segmento.split("||")[1];
			}
			origem = document.getElementById('origem').value;
			if(origem.split("||")[1] == 'Outros'){
				origem = document.getElementById('outroorigem').value;
			}
			else{
				origem = origem.split("||")[1];
			}
			assunto = document.getElementById('assunto').value;
			telefone = document.getElementById('tel').value;
			msg = document.getElementById('msg').value;
			
			if(!tipo){
				tipo = 'false';
			}			
		}
		else{
			nome = document.getElementById('nome').innerHTML;
			email = document.getElementById('email').value;			
			assunto = document.getElementById('assunto').value;
			msg = document.getElementById('msg').value;			
		}
		//Faz requisição para gravar dados
		var tipoReq = 'POST';
		var endereco = './opatendext.php?op=1';
		var conteudo = 'tipo=' + tipo + '&nome=' + nome + '&email=' + email + '&segmento=' + segmento + '&origem=' + origem + '&assunto=' + assunto + '&telefone=' + telefone + '&msg=' + msg;
		
		httpcontext.open(tipoReq, endereco + conteudo, true); 
		httpcontext.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpcontext.onreadystatechange = handlehttpResponseBot;
		httpcontext.send(conteudo);
	}
	
	function handlehttpResponseBot(){
		if (httpcontext.readyState == 4){
			if(httpcontext.status == 200){
				fimEnviaMensagem(httpcontext.responseText);
			}
		}    
	}
	/* Finaliza o envio da mensagem. */
	function fimEnviaMensagem(response){
		document.getElementById('enviarBt').onclick = function() { enviaMensagem(tipo); }; 
		document.getElementById('enviarBt').innerHTML = 'Enviar'; 
		document.getElementById('conteudo_contato').innerHTML = '<div id="atendimento"><h2 id="titulo_mensagem">Atendimento</h2><div class="campo_atendimento"><div style="text-align:center" class="centraliza"><br />Recebemos sua mensagem e em breve entraremos em contato.<br /><br />Para enviar uma nova mensagem clique <a style="color:#000" title="Abra aqui uma nova conta!" href="http://www.gerencianet.com.br/atendimento.php?email=' + email + '"><b>aqui</b></a>.</div></div>';
	}

}

function validaEnviarMensagem(tipo){
	
	var pendencias = '<ul>';
	var campoInvalido = false;
	var campoVazio = false;
	var completo = '';
	
	if(!tipo || (tipo == 0)){
		//Validando Nome
		if(document.getElementById('nome').value == ""){
			pendencias += '<li> Nome';
			campoVazio = true;
		}
		
		//Validando Ramo de atuação
		if(document.getElementById('segmento').selectedIndex == -1){
			pendencias += '<li> Ramo de atuação';
			campoVazio = true;
		}
		else{
			var valor = document.getElementById('segmento').value.split("||")[1];
			
			if((valor == 'Outros') && (document.getElementById('ramoOutro').value == '')){
				pendencias += '<li> Ramo de atuação - Outros';
				campoVazio = true;
			}
		}	
		
		//Validando Origem
		if(document.getElementById('origem').selectedIndex == -1){
			pendencias += '<li> Origem';
			campoVazio = true;
		}
		else{
			var valor = document.getElementById('origem').value.split("||")[1];
			
			if((valor == 'Outros') && (document.getElementById('outroorigem').value == '')){
				pendencias += '<li> Origem - Outros';
				campoVazio = true;
			}
		}
			
		//Validando Telefone
		if(document.getElementById('tel').value == ""){
			pendencias += '<li> Telefone';
			campoVazio = true;
		}
		else if(document.getElementById('tel').value.length != 13){
			pendencias += '<li> Telefone';
			campoInvalido = true;
		}		
	}
	
	//Validando E-mail
	if(document.getElementById('email').value == ""){
		pendencias += '<li> E-mail';
		campoVazio = true;
	}
	else{
		var ok = true;
		var str = document.getElementById('email').value;
		var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
		if(typeof(str) == "string")	{
			if(er.test(str)){ 
				ok = true; 
			}
			else{
				ok = false;
			}
		}
		else if(typeof(str) == "object"){
			if(er.test(str.value)){ 
				ok = true; 
			}
			else{
				ok = false;
			}
		}
		else{
			ok = false;
		}
		
		if(!ok){
			pendencias += '<li> E-mail';
			campoInvalido = true;
		}
	}		
	
	//Validando Assunto
	if(document.getElementById('assunto').selectedIndex == -1){
		pendencias += '<li> Assunto';
		campoVazio = true;
	}	
	
	//Validando Mensagem	
	if(document.getElementById('msg').value == ""){
		pendencias += '<li> Mensagem';
		campoVazio = true;
	}
	
	pendencias += '</ul>';
	
	//Configurando erros
	if(campoVazio == true || campoInvalido == true){
		document.getElementById('erro').innerHTML = "Por favor, verifique os seguintes campos: <br /> <br />" + pendencias;
		return false;
	}
	else{
		return true;
	}
}
function facaParteAf(){
	window.location = "http://www.gerencianet.com.br/abrir_nova_conta.php";
}
function custoenv(obj){
	var endereco = './fl.php?fl='+obj.value;
	var conteudo = '';
	var tipoReq = 'GET';
	httpcontext.open(tipoReq, endereco, true); 
	httpcontext.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpcontext.onreadystatechange = handlehttpResponseBot;
	httpcontext.send(conteudo);
	
	
	function handlehttpResponseBot(){
		if (httpcontext.readyState == 4){
			if(httpcontext.status == 200){
				document.getElementById('valorCarne').innerHTML = 'R$ '+httpcontext.responseText;
			}
		}    
	}
}
var httpsetemail = new getHTTPObject();
function setEmail(id){
	var endereco = 'setEmail.php';
	var tipoReq = 'POST';
	var conteudo = 'email='+document.getElementById(id).value;
	httpsetemail.open(tipoReq, endereco, conteudo, true);
	httpsetemail.onreadystatechange = handlehttpResponseEmail;
	httpsetemail.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpsetemail.send(conteudo);
	function handlehttpResponseEmail(){
		if (httpsetemail.readyState == 4){
			if(httpsetemail.status == 200){
				//alert(httpsetemail.responseText);
			}
		}
	}
}
