// JavaScript Document
// Função que cria o objeto XMLHttpRequest
function getXMLRequest() {
	try{ // tenta criar o objeto padrão (ECMA script - Browser´s filhos do mozilla
		xmlhttp = new XMLHttpRequest();
	}catch(ee){ // se não conseguir
		try{ // tenta criar o objeto compativel com as versões mais antigas do IE
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){ // Se falhar
			try{ // Cria o objeto compativel com o IE 5.5 ou superior
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(E){ // Retorna false se o browser não tiver suporte
				xmlhttp = false;
			}
		}
	}
	
	return xmlhttp; // retorna uma instancia XMLHttpRequest
}

function getEndereco(cep) {
	var ajax = getXMLRequest(); // pegando uma instancia do objeto XMLHttpRequest
	
	if (!ajax) { // se o browser não tiver suporte
		alert("browser sem suporte.");
		return false;
	}
	
	document.getElementById("loadCep").innerHTML = "Carregando...";
	
	var url = "cadastro/buscaCep.asp?cep=" + cep;

//	var url = "http://www.divaonline.com.br/diva/cadastro/buscaCep.asp?cep=" + cep;
	ajax.open("GET",url,true); // Metodo que envia a requisição
	
	ajax.onreadystatechange = function() { // metodo atualizado durante todo o processo da requisição
		if (ajax.readyState == 4) { // se o readyState for 4 a transação foi finalizada.
			document.getElementById("loadCep").innerHTML = "";
			escreveCep(unescape(ajax.responseText));
		}
	}
	
	xmlhttp.send(null); // para mandar variaveis via POST
}

function escreveCep(end) {

	var confirma = end.indexOf(",")
	if (confirma == -1) {
		document.getElementById("loadCep").innerHTML = "Esse CEP não existe."
		document.getElementById("cep_um").style.backgroundColor = "#FBE9A6";
		document.getElementById("cep_dois").style.backgroundColor = "#FBE9A6";
				
		document.getElementById("endereco").value = ""
		document.getElementById("bairro").value = ""
		document.getElementById("cidade").value = ""
		document.getElementById("estado").selectedIndex = 0;
		
		alert("CEP inválido, por favor digite novamente.");	

		return false;
	}	

	var arrEnd = end.split(",");

	document.getElementById("cep_um").style.backgroundColor = 
	document.getElementById("cep_dois").style.backgroundColor = "#F3F8FB";
	
	document.getElementById("cep_um").onfocus = 
	document.getElementById("cep_dois").onfocus = null;
	
	document.getElementById("endereco").value = arrEnd[0];
	document.getElementById("bairro").value = arrEnd[1];
	document.getElementById("cidade").value = arrEnd[2];
	document.getElementById("estado").value = arrEnd[3];
	
	/*
	for (var i = 0; i < cboEstado.length; i++) {
		if (cboEstado.options[i].index == arrEnd[3]) {
			cboEstado.selectedIndex = i;
			break;
		}
		
		if (cboEstado.options[i].value == arrEnd[3]) {
			cboEstado.selectedIndex = i;
			break;
		}
	}*/
}
