// Form Validation Functions
//
//----------------------------------------------------------------------------------------------------------
function MM_format(e,src,mask) {
	if(window.event) { 
		_TXT = e.keyCode; }
	else 
		if(e.which) { 
			_TXT = e.which; 
		}
	if(_TXT > 47 && _TXT < 58) {
		var i = src.value.length; 
		var saida = mask.substring(0,1); 
		var texto = mask.substring(i)
		if (texto.substring(0,1) != saida) { 
			src.value += texto.substring(0,1); 
		}
    	return true; } 
	else { 
		if (_TXT != 8) { 
			return false; }
		else { 
			return true; 
		}
	}
}

//----------------------------------------------------------------------------------------------------------
function validaDATA(dt)  {

	// O parâmetro passado deve ter o formato: "99/99/9999"
	var dia = dt.substr(0,2);
	var mes = dt.substr(3,2);
	var ano = dt.substr(6,4);
	var erro = false;
	if (dia == 0 || dia > 31) {erro = true;}
	if (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes == 11)) {erro = true;}
	if (dia > 29 && mes == 2) {erro = true;}
	// Calcula ano bissexto
	if (dia == 29 && mes == 2 && ((ano%4)!=0)) {erro = true;}
	if (mes == 0 || mes > 12) {erro = true;}
	if (ano == 0 || ano < 1900) {erro = true;}
	if(erro)
		return(false);
	else
		return(true);
}

//----------------------------------------------------------------------------------------------------------
function validaCPF(cpf1) {
	// O campo deve vir formatado (999.999.999-99)
	// Para isso trabalha em conjunto com a função MM_format()
	//
	//cpf1 = theForm.cpf.value;
	var erro = new String;
	var cpf = new String;
	for (i=0; i<14; i++){
		if (cpf1.charAt(i) != "." && cpf1.charAt(i) != "-" && cpf1.charAt(i) != "/") {
			cpf += cpf1.charAt(i);
		}
	}
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
//		alert("<?php echo $txt_wrong_cpf; ?>");
		return(false);
	} 
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			return(false);
		}
	if (erro.length > 0){
		return(false);
	}
	return true;
}

//----------------------------------------------------------------------------------------------------------
function validaCNPJ(CNPJ1) {
	// O campo deve vir formatado (99.999.999/9999-99)
	// Para isso trabalha em conjunto com a função MM_format()
	//
	//CNPJ1 = theForm.cgc.value;
	var erro = new String;
	var CNPJ = new String;
	for (i=0; i<18; i++){
		if (CNPJ1.charAt(i) != "." && CNPJ1.charAt(i) != "-" && CNPJ1.charAt(i) != "/") {
			CNPJ += CNPJ1.charAt(i);
		}
	}
	erro = new String;
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			return(false);
	}
	if (erro.length > 0){
		return(false);
	}
	return true;
}

UFxx="";
Cidadexx="";
function carregaCidades(UF,Cidade,subDir) {
	if(!UF) {
		carregaEstados(UF,Cidade,subDir);
		return true;
	}
	http.open("GET", subDir + "include/ajax_cidades.php?uf=" + UF + '&cidade=' + Cidade, true);
	http.onreadystatechange =  handleHttpResponse_carregaCidades;
	http.send(null);
}

function handleHttpResponse_carregaCidades()
{
  if (http.readyState == 4) {
	fechaLayerWaiting()
    results = http.responseText;
	if(results != "ERRO") {
		document.getElementById('cidades').innerHTML = results;
	}
  } else {	  posicionaLayerWaiting();
}
}

function carregaEstados(UF,Cidade,subDir) {
	UFxx=UF;
	Cidadexx=Cidade;
	http.open("GET", subDir + "include/ajax_estados.php?uf=" + UF + "&sub_dir=" + subDir, true);
	http.onreadystatechange =  handleHttpResponse_carregaEstados;
	http.send(null);
}

function handleHttpResponse_carregaEstados()
{
  if (http.readyState == 4) {
	fechaLayerWaiting()
    results = http.responseText;
	if(results != "ERRO") {
		document.getElementById('estados').innerHTML = results;
		if(!UFxx.length) {
			document.getElementById('cidades').innerHTML = "<select name='cidade'><option value=''>Escolha o estado</option></select>";
		}
	}
  } else {	  posicionaLayerWaiting();
}
}

function checkmail(e) {
	if(!e.length) return(false);
	var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
	return emailfilter.test(e);
}

function alterError(value) {
	if (value<=0.99) {
		newDollar = '0';
	} else {
		newDollar = parseInt(value);
	}
	newCent = parseInt((value+.0008 - newDollar)* 100);
	if (eval(newCent) <= 9) newCent='0'+newCent;
	newString = newDollar + '.' + newCent;
	return (newString);
}

function IsNumeric(campo){
	// Se tem vírgula troca por ponto
	var ok = true;
	var caracteresInvalidos = "";
	var campoNovo = new String;
	var campoVelho = document.getElementById(campo).value;
	var qtPontos = 0;
	for (i=0; i<campoVelho.length; i++){
		if (campoVelho.charAt(i) == ",") {
			campoNovo += ".";
			qtPontos++;
		} else if(((campoVelho.charAt(i)>=0) && (campoVelho.charAt(i)<=9)) || (campoVelho.charAt(i)==".")) { // Aceita somente números
			campoNovo += campoVelho.charAt(i);
			if(campoVelho.charAt(i)==".") qtPontos++;
		} else { // Caracteres inválidos
			caracteresInvalidos+=campoVelho.charAt(i);
			ok=false;
		}
	}
	document.getElementById(campo).value=campoNovo;
	// Se não tem a parte decimal adiciona ".00"
	if((document.getElementById(campo).value>0) && (qtPontos<=1)) {
		document.getElementById(campo).value=alterError(eval(document.getElementById(campo).value));
	} else { // Ficou somente o PONTO
		ok=false;
	}
	var er = /^[0-9]{0,12}\.[0-9]{0,2}$/;
	if(!er.test(document.getElementById(campo).value) || !ok) {
		document.getElementById(campo).value="";
		alert('Preenchimento inválido!!! '+(caracteresInvalidos.length?"("+caracteresInvalidos+")":"")+'\nNeste campo são permitidos somente NÚMEROS.\nUse PONTO como separador de centavos.\nMáximo de DUAS casas decimais.\nNão é permitido deixar zerado (0.00)');
		document.getElementById(campo).focus();
	}

}

function MM_formatMoney(e) {
	if(window.event) { 
		_TXT = e.keyCode; }
	else 
		if(e.which) { 
			_TXT = e.which; 
		}
	if( (_TXT > 47 && _TXT < 58) || (_TXT == 8) || (_TXT == 46) || (_TXT == 44)  || (_TXT == 3) ){
		return true; 
	} else { 
		return false; 
	}
}

xCep="";
xSubDir="";
function recuperaLogradouroCompleto(Cep,subDir) {
	xCep=Cep;
	xSubDir=subDir;
	if(Cep=="") {
		alert('Informe o CEP!');
		document.getElementById('cep').focus();
		return false;
	}
	http.open("GET", subDir + "include/ajax_cep.php?cep=" + Cep, true);
	http.onreadystatechange =  handleHttpResponse_recuperaLogradouroCompleto;
	http.send(null);
}

function handleHttpResponse_recuperaLogradouroCompleto()
{
  if (http.readyState == 4) {
    results = http.responseText;
	fechaLayerWaiting()
	if(results !== "ERRO") {
		var vetor = results.split("|");
		document.getElementById('logradouro').value = vetor[0];
		document.getElementById('bairro').value = vetor[1];
		document.getElementById('cidades').innerHTML = "<input name='cidade' type='text' value='"+vetor[2]+"' size='20' maxlength='50' onfocus=\"javascript:carregaCidades('"+vetor[3]+"','"+vetor[2]+"','"+xSubDir+"');\">";
		//document.getElementById('estados').innerHTML = "<input name='uf' type='text' value='"+vetor[3]+"' size='2' maxlength='2'>";
		carregaEstados(vetor[3],vetor[2],xSubDir);
		document.getElementById('logradouro').focus();
	} else {
		alert('Erro na busca do CEP '+xCep+'.\nTente novamente');
		document.getElementById('cep').value='';
		document.getElementById('logradouro').value = "";
		document.getElementById('bairro').value = "";
		//document.getElementById('cidades').innerHTML = "<input name='cidade' type='text' value='' size='20' maxlength='50'>";
		//document.getElementById('estados').innerHTML = "<input name='uf' type='text' value='' size='2' maxlength='2'>";
		carregaEstados('','',xSubDir);
		document.getElementById('uf').value = "";
		document.getElementById('cidades').value = "<select name='cidade' onfocus=\"javascript:carregaCidades('','','"+xSubDir+"');\"><option value=''>Escolha o estado</option></select>";
		document.getElementById('cep').focus();
		return false;
	}
	
  } else {	  posicionaLayerWaiting();
}
}

function habilitaSubmit() {
	document.getElementById("botao_avancar").innerHTML = "<input name='submit' type='image' src='images/bt_avancar.jpg'>";
}

function captchaCheck(valor) {
	http.open("GET", ".include/captcha/ajax_captcha.php?senha_imagem=" + valor , false);
	http.send(null);
   	results = http.responseText;
	return (results==1?true:false);
}

function pesquisar_dados(Tabela,Campo,Dado) {
	if(!Tabela || !Campo || !Dado) return false;
	http.open("GET", "include/ajax_consult.php?tabela=" + Tabela + '&campo=' + Campo + '&dado=' + Dado, true);
	http.onreadystatechange = handleHttpResponse_pesquisar_dados;
	http.send(null);
}

function handleHttpResponse_pesquisar_dados() {
  if (http.readyState == 4) {
	fechaLayerWaiting();
    results = http.responseText;
//alert(results);
	return results;
  } else {
	posicionaLayerWaiting();
  }
}

