/** secao de uso interno **/
var isIE = (navigator.appVersion.indexOf("MSIE") > -1);
var infoPadrao;

function getNomeFuncao(prefixo, nome){return prefixo + nome.charAt(0).toUpperCase() + nome.substring(1);}
function getEventHandler(name){var handler = eval("typeof(" + name + ")"); return (handler == "undefined") ? function(){} : isIE ? new Function(name + "(event);") : eval(name);}
function getCharPressed(e){return isIE ? e.keyCode : e.charCode;}
function getEventTarget(e){return isIE ? e.srcElement : e.target;}
function getSelectedText(input){return isIE ? document.selection.createRange().text : input.value.substring(input.selectionStart, input.selectionEnd);}

function setMensagem(msg, msgClass){
	if (document.getElementById("mensagens") != null && document.getElementById("mensagens").childNodes.length != 0){
		with(document.getElementById("mensagens")){
			firstChild.nodeValue = msg;
			if(msgClass != null){className = msgClass;}
		}
	}
}

/**
 * Eventos
 */
function validarForm(form){
	var erro = null;

	with(form){
		for(var i = elements.length; i-- > 0;){
			if(elements[i].validar != null && !elements[i].validar()){
				erro = elements[i];
				erro.className = "erro";
			}
		}
	}
	
	if(erro != null){
		erro.focus();
		alert("Por favor, corrija os erros do formulário antes de prosseguir.");
		return false;
	}
	if(form.onbeforesubmit){
		if(form.onbeforesubmit() === false){
			return false;
		}
	};
	return true;
}

function validarInput(){
	return ((this.errorMsg = this.validarHandler()) == null);
}

function focusMaxLength(input, proximo, code){
	//apenas alfanumerico e se nao houver texto selecionado	
	if((input.value.length + 1) > input.maxLength && code > 47 && code < 123 && getSelectedText(input).length == 0){proximo.focus();}
}

function inputKeyUp(e){
	var input = getEventTarget(e);
	if(input.errorMsg != null){
		if(input.validar()){
			setMensagem(input.getAttribute("info"), "msgFocus");
			input.className = "focus";
		} else {
			setMensagem(input.errorMsg, "msgErro");
		}
	}
	var proximo = input.getAttribute("proximo");
	if(proximo != null){
		focusMaxLength(input, input.form[proximo], e.keyCode)
	}
}

function inputKeyPress(e){
	if(e.keyCode == 13){return;}
	var input = getEventTarget(e);
	input.keyPressHandler(e);
}

function inputFocus(){
	if(this.errorMsg == null){
		setMensagem(this.getAttribute("info"), "msgFocus");
		switch(this.type){case "radio": case "checkbox": break; default: this.className = "focus";}
	} else {
		setMensagem(this.errorMsg, "msgErro");
	}
}

function inputBlur(){
	this.className = (this.validar() ? "campos" : "erro");
	setMensagem(infoPadrao);	
}

function processarForm(form){
	form.onsubmit = new Function("return validarForm(this)");
	var beforesubmit = form.getAttribute("onbeforesubmit");
	if(beforesubmit != null){form.onbeforesubmit = new Function(beforesubmit);}	
	for(var i = 0, elements = ["input", "textarea"]; i < elements.length; i++){
		for(var j = 0, inputs = form.getElementsByTagName(elements[i]); j < inputs.length; j++){
			var input = inputs[j];
			switch(i == 0 ? input.getAttribute("type") : "textarea"){
				case "button": case "submit": case "hidden": case "image": case "checkbox": case "radio":
					break;
				default:
					input.onfocus = inputFocus;
					input.onblur = inputBlur;
					input.validar = validarInput;
					var validacao = input.getAttribute("validacao");
					var proximo = input.getAttribute("proximo");
					if(validacao == null){
						input.validarHandler = function(){};
					} else {
						input.onkeypress = getEventHandler("inputKeyPress");
						input.keyPressHandler = getEventHandler(getNomeFuncao("mascarar", validacao));
						input.validar = validarInput;
						input.validarHandler = eval(getNomeFuncao("validar", validacao));
					}
					if(proximo != null){
						input.onkeyup = getEventHandler("inputKeyUp");
					}
			}
		}
	}
}

/**
 * Máscaras
 */
function mascararChaveSISBB(e){
	var input = getEventTarget(e);
	if(isIE) {
		var code = getCharPressed(e);
		var alfa = /[ACEFX]/;
		var typed = String.fromCharCode(code).toUpperCase();
		var length = input.value.length;
		var selection = getSelectedText(input);
		var allowAlfa = (selection.length == 0 ? length == 0 : alfa.test(selection));
		e.keyCode = ((allowAlfa && alfa.test(typed)) || (!allowAlfa && /\d/.test(typed))) ? typed.charCodeAt(0) : 0;
	} else {
		input.value = input.value.toUpperCase();
	}
}

function mascararSenhaSISBB(e){
	/*
	if(isIE && /\D/.test(String.fromCharCode(e.keyCode))){
		e.keyCode = 0;
	}
	*/
}

/**
 * Validações
 */
function validarChaveSISBB(){
	return (/[ACEFX]\d{7}/.test(this.value) ? null : "Chave inválida");
}

function validarSenhaSISBB(){
	/*
	if(/\D/.test(this.value)){
		return "A senha deve conter apenas números";
	}
	*/
	if(this.value.length < 8){
		return "A senha deve ter oito dígitos";
	}
	return null;
}

/** interface **/
function parseForm(focusInput, frm) {
	var contador = 0;
	for(var i = 0, f = document.getElementsByTagName("form"); i < f.length; processarForm(f[i++])){contador++;}
	frm = frm != null ? frm : 0;
	infoPadrao = "";
	//infoPadrao = document.getElementById("mensagens").firstChild.nodeValue;
	
	if (contador > 0){
		//Muda o foco para o primeiro campo de entrada (input) do formulario que o contem a função no onLoad	
		for(var i = 0; focusInput && i < document.forms[frm].elements.length; i++) {
			switch(document.forms[frm].elements[i].type) {	
				case "hidden": break;
				case "checkbox": break;
				case "radiobutton": break;
				default: document.forms[frm].elements[i].focus(); return;
			}
		}
	}
}
