// 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;
}

function carregaCidades(UF,Cidade) {
	http.open("GET", "ajax_cidades.php?uf=" + UF + '&cidade=' + Cidade + "&maiusculas=FALSE", true);
	http.onreadystatechange =  handleHttpResponse_carregaCidades;
	http.send(null);
}

function handleHttpResponse_carregaCidades()
{
  if (http.readyState == 4) {
    results = http.responseText;
	document.getElementById('layerWaiting').style.visibility='hidden'
	if(results != "ERRO") {
		document.getElementById('cidades').innerHTML = results;
	}
  } else {
	  document.getElementById('layerWaiting').style.visibility='visible'
  }
}

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

function handleHttpResponse_recuperaLogradouroCompleto()
{
  if (http.readyState == 4) {
    results = http.responseText;
	document.getElementById('layerWaiting').style.visibility='hidden'
	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]+"'>";
		document.getElementById('estados').innerHTML = "<input name='uf' type='text' value='"+vetor[3]+"'>";
		document.getElementById('numero').focus();
	} else {
		alert('Erro na busca do CEP '+xCep+'.\nTente novamente');
		document.getElementById('cep').value='';
		document.getElementById('logradouro').value = "";
		document.getElementById('bairro').value = "";
		if(!document.getElementById('uf')) {
			document.getElementById('cidades').innerHTML = "<input name='cidade' type='text' value=''>";
			document.getElementById('estados').innerHTML = "<input name='uf' type='text' value=''>";
		}
		document.getElementById('cep').focus();
		return false;
	}
	
  } else {
	  posicionaLayerWaiting();
	  document.getElementById('layerWaiting').style.visibility='visible'
  }
}

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

// Verifica se o navegador permite Ajax
function ajax()
{
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch(ex) {
            try {
                return new XMLHttpRequest();
            } catch(exc) {
                alert("Esse browser não tem recursos para uso do AJAX");
                return false;
            }
        }
    }
}

function handleHttpResponse_calculaFrete()
{
  if (http.readyState == 4) {
    results = http.responseText;
	document.getElementById('layerWaiting').style.visibility='hidden'
	if(results == "ERRO") {
		alert('Erro no cálculo do frete!\nTente novamente');
		return false;
	}
	document.getElementById('valor_frete').value=results;
	textoCalculosCubagem1='O que é cubagem e como se faz o cálculo? Cubagem é o peso equivalente ao espaço que o volume ocupa na aeronave. A cubagem é calculada através das dimensões do volume, em centímetros. Multiplica-se o comprimento pela largura e pela altura, e divide-se o resultado por 6000, o resultado será o peso cubado. 6000cm&sup3; é o espaço que 1kg ocupa na aeronave.';
	textoCalculosCubagem2='Para os produtos que você selecionou temos:<br>Peso total: '+document.getElementById('peso_total').value+'Kg';
	textoCalculosCubagem2+='<br>Cubagem total: '+alterError(document.getElementById('volume_total').value/6000)+'Kg';
	textoCalculosCubagem2+='<br>Volume total: '+document.getElementById('volume_total').value+'cm³';
	document.getElementById('linhaCubagem').innerHTML="<img src='images/b_docs.png' width='16' height='16' align='absmiddle' border='0' onMouseover='layerTip(\""+textoCalculosCubagem1+"\");' onMouseout='hidelayerTip()'>&nbsp;<img src='images/peso.gif' height='16' align='absmiddle' border='0' onMouseover='layerTip(\""+textoCalculosCubagem2+"\");' onMouseout='hidelayerTip()'>";
	document.getElementById('campoValorFrete').innerHTML='<span class=\"TabelaCarrinhoMoeda\">R$</span> '+results;
	calculaTotal();
  } else {
	  document.getElementById('layerWaiting').style.visibility='visible'
	  //document.getElementById('campoValorFrete').innerHTML='&nbsp';
  }
}

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