function getHTTPObject(){
	// Mozilla, Safari,...
	if (window.XMLHttpRequest){
		return new XMLHttpRequest();
	
	// IE
	}else if (window.ActiveXObject){
		try{
			return new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){}
		}
	}		
}

function ExecAjax(url, funcRetorno){
	ajax = false ;
	ajax = getHTTPObject();
	
	ajax.onreadystatechange = funcRetorno;
	ajax.open("GET", url, true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	ajax.setRequestHeader("Pragma", "no-cache");
	ajax.send(null);
}

function consultaCEP(){
	var txt_cep 	= document.getElementById('cep');
	var cep			= txt_cep.value;
	var txt_status 	= document.getElementById('txt_status');
	if(cep.length >= 8){
		var oForm	= document.getElementById("frmCadastrar");
		if(Verifica(oForm.cep, "CEP", false) == false ){
			txt_cep.focus();
			return;
		}else{
			txt_status.innerHTML = 'Consultando CEP...';
			ExecAjax('buscaCEP.php?cep='+cep, preencheCEP)		
		}
	}else{
		txt_cep.focus();
		return;
	}
}

function preencheCEP(){
	var txt_status 	= document.getElementById('txt_status');
	if(ajax.readyState >= 4){
		var result 		= ajax.responseText.split("#");
		var resultado	= result[0];
		var UF			= result[1];
		var cidade		= result[2];
		var bairro		= result[3];
		var endereco	= result[4];
		if(resultado <= 0){
			alert('Erro: CEP inexistente.');
			txt_status.innerHTML = '&nbsp;Digite o CEP para completar o restante do endere&ccedil;o.';
		}else{
			var oForm			 	= document.getElementById("frmCadastrar");
			txt_status.innerHTML 	= '&nbsp;Endere&ccedil;o preenchido, digite o n&uacute;mero de sua casa.';
			oForm.endereco.value	= endereco;
			oForm.bairro.value 		= bairro;
			oForm.cidades.value 	= cidade;
			montaSub(UF);
			oForm.numero.value 		= '';
			oForm.numero.focus();
		}
	}
}

function montaSub(uf){
	var subCombo 	= document.getElementById("estado");
	var listaEstado = 'AC#AL#AP#AM#BA#CE#DF#ES#GO#MA#MT#MS#MG#PA#PB#PR#PE#PI#RJ#RN#RS#RO#RR#SC#SP#SE#TO';
	var resultado 	= '';
	var selecao 	= false;
	subCombo.options.length = 0;
	resultado = listaEstado.split("#");
	for( i = 0; i < resultado.length; i++ ){
		if(uf == resultado[i]){
			selecao = true;
		}else{
			selecao = false;		
		}
		subCombo.options[i] = new Option( resultado[i], resultado[i], '', selecao);
	}	
}

