/**
  *
  * Script para busca por cep com Ajax
  * @author: Edy Segura - edy@segura.pro.br
  *
  */

var Index = {

	init: function() {
		Index.setForm();
		Index.setButton();
		Index.setFastCEP();
	},

	
	setForm: function() {
		var form = document.forms['form2'];
		
		form.onsubmit = function() {
			return false;
		};

	},
	
	
	buscarEndereco: function(form) {
		//remove qualquer coisa q não seja um digito.
		var CEP = form.cep.value.replace(/\D/g, "");
		if (CEP.length == 0){
			
		}else{
		if(CEP.length != 8) {
			document.getElementById("alerta").innerHTML = 'Preencha corretamente seu CEP';
			return form.cep.focus();
		}

		Ajax.request({
			url      : "cep/endereco.php?cep=" + CEP,
			params   : form,
			callback : Index.preencherCampos,
			callerro : Index.limparCampo
		});
		
		Index.disabledCampos(form, true);
		}
	},


	preencherCampos: function(response, form) {
		//eval abaixo resulta em var resultadoCEP = {...}
		try {
			eval(response);
		}
		catch(e) {
			Index.disabledCampos(form, false);
		}
		
		
		form.endereco.value    = unescape(resultadoCEP.logradouro);
		form.cidade.value = unescape(resultadoCEP.cidade);
		
		form.numero.focus();
		document.getElementById("alerta").innerHTML = '';
		Index.disabledCampos(form, false);
		
	},
	
	
	limparCampo: function(httpStatus, message, form) {
		Index.disabledCampos(form, false);
		form.endereco.focus();
	},
	
	
	disabledCampos: function(form, disabled) {
		with(form) {
			endereco.disabled = disabled;
			cidade.disabled = disabled;
			
			endereco.value = (disabled) ? "aguarde, carregando..." : (endereco.value) ? endereco.value : "";
			cidade.value = (disabled) ? "aguarde, carregando..." : (cidade.value) ? cidade.value : "";
		}
	},
	
	
	setFastCEP: function() {
		var spans = document.getElementsByTagName('span');
		
		for(var i=0; i<spans.length; i++) {
			spans[i].onclick = function() {
				Index.fastCEP(this.innerHTML);
			};
		}
		
	},
	
	
	
	fastCEP: function(sCep) {
		var form = document.forms['form2'];
		
		form.reset();
		form.cep.value = sCep;
	}

};

//inicializacao
window.onload = Index.init;

