//*************************************************************
//
// Função desenvolvida por Adriano de Sousa Rocha
// arochax@hotmail.com
//
// Descricao: Formata e Valida a digitação de um CEP em um INPUT
//
// Exemplo de utilização: (12345-678)
//
// <INPUT onkeypress="return FormatarCEP(this);"
//        onblur="return ValidarCEP(this);">
//
//*************************************************************


function FormatarCEP(Campo) {
	if ("8,13,48,49,50,51,52,53,54,55,56,57".indexOf(event.keyCode) == -1) {
		event.keyCode = 0 ;
		return false ;
	}
	else {

		if (event.keyCode == 13) {
			if (ValidarCEP(Campo) != true) { 
				event.keyCode = 0 ;
				return false ;
			}
		}
	    
	    if (Campo.value.length >= 9) {
			Campo.value = "";
		}

		switch (Campo.value.length)
		{
			case 4:
				Campo.value = Campo.value + String.fromCharCode(event.keyCode) + "-";
				event.keyCode = 0;
				break;
		    case 5:
				Campo.value = Campo.value +	"-";
				break;
		}
	}
	return true ;
}


function ValidarCEP(Campo) {

	var dado = Campo.value;
	var bolOk = true;
		
	if(dado.length == 0) return true;
	if(dado.length != 9) bolOk = false;
	
	if (bolOk == false) {
		Campo.value = "";
		alert('CEP invalido. Digite novamente.');
		Campo.focus();
	}
	return true;
}
