﻿//------------------------------------------------------------------------
// Web Service CEP, desenvolvido por Bruno Tenório Souza. 
//-------------------------------------------------------------------------

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
        xmlhttp = false;
        }
      }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
      } catch (e) {
      xmlhttp = false;
      }
    }
  return xmlhttp;
  }
var http = getHTTPObject();

function funcaowebservicecep() 
{
	http.open("GET", 'script/javascript/buscarendereco.php?cep='+document.getElementById("cep").value, true);
	http.onreadystatechange = handleHttpResponse;
	http.send(null);

	var arr; //array com os dados retornados
	function handleHttpResponse() 
	{
		if (http.readyState == 4){
			var response = http.responseText;
			eval("var arr = "+response); //cria objeto com o resultado
			document.getElementById("endereco").value = arr.rua;
			document.getElementById("bairro").value = arr.bairro;
			document.getElementById("cidade").value = arr.cidade;
			document.getElementById("estado").value = arr.uf;
			
			if(arr.bairro=="" || arr.rua=="" || arr.cidade=="" || arr.uf==""){
				document.getElementById("cep").value = "";
				document.getElementById("numeroEndereco").value = "";
				document.getElementById("endereco").value = "";
				document.getElementById("bairro").value = "";
				document.getElementById("cidade").value = "";
				document.getElementById("estado").value = "";

				document.getElementById("idcepvalido").value = "false";
				document.getElementById("cep").focus();
				alert("Por favor, preencha o campo \"CEP\" corretamente.\n\n- O CEP digitado não é aceito no sistema dos Correios.")
			}
			else
				document.getElementById("idcepvalido").value = "true";

		    document.getElementById("carregador_pai").style.visibility = "hidden";
			document.getElementById("carregador_pai").style.display = "none";
		}
	}
}
