// acrescenta as funções do form no onLoad da página //
$(document).ready(function() {
	$('input').inputMask();
	$('textarea').limited();
});
$.fn.mySubmit = function() {
	this.submit(function() {
		return validateForm(this);
	});
	return this;
}

function inputFocus(form) {
	setFocus = false;
	if($(form).attr('focus') != 'no') {
		$(form).find('input,select,textarea').filter(':enabled').each(function() {
			if(!setFocus) {
				switch(this.getAttribute('type')) {
					case 'hidden':
					case 'submit':
						break;
					default:
						setFocus = true;
						this.focus();
						return;
				}
			}
		});
	}
}

// acrescenta máscara nos campos dos formulário //
$.fn.inputMask = function() {
	this.keypress(function(event) {
		switch(this.getAttribute('param')) {
			case 'date':
				return maskDate(event, this);
				break
			case 'numb':
			case 'cpf':
			case 'cnpj':
			case 'cpfcnpj':
				return maskNumber(event, this, this.getAttribute('mask'));
				break
			case 'deci':
				return maskFloat(event, this);
				break
		}
	});
}

// acrescenta limite nos campos textarea //
$.fn.limited = function() {
	this.keyup(function() {
		if(this.getAttribute('param') == 'limited')
			textLimit(this, this.getAttribute('maxlength'), this.getAttribute('target'));
	});
	this.change(function() {
		if(this.getAttribute('param') == 'limited')
			textLimit(this, this.getAttribute('maxlength'), this.getAttribute('target'));
	});
}


// valida formulário //
validateForm = function(form) {
	valida = true;
	$(form)
		.find('input, select, textarea')
		.filter(':enabled')
		.each(function() {
			if(valida) {
				if(this.getAttribute('required')) {
					if(this.getAttribute('type') == 'radio' || this.getAttribute('type') == 'checkbox') {
						if(!isChecked($(form).find('input[@name="' + this.name + '"]'), this.getAttribute('validationmsg'))) {
							valida = false;
							this.focus();
							return;
						}
					}
					else if(isEmpty(this.value, this.getAttribute('validationmsg'))) {
						valida = false;
						this.focus();
						return;
					}
				}
				switch(this.getAttribute('param')) {
					case 'date':
						if(!isDate(this.value)) {
							alert('Data Inválida!');
							valida = false;
							this.focus();
						}
						break;
					case 'email':
						if(!isMail(this.value)) {
							alert('E-mail Inválido!');
							valida = false;
							this.focus();
						}
						break;
					case 'cpf':
						if(!isCPF(this.value)) {
							alert('CPF Inválido!');
							valida = false;
							this.focus();
						}
						break;
					case 'cnpj':
						if(!isCNPJ(this.value)) {
							alert('CNPJ Inválido!');
							valida = false;
							this.focus();
						}
						break;
					case 'cpfcnpj':
						if(!isCPF(this.value) && !isCNPJ(this.value)) {
							alert('CPF / CNPJ Inválido!');
							valida = false;
							this.focus();
						}
						break;
				}
				if(field1 = this.getAttribute('compare')) {
					if(!compareStr($(form).find('input[@name="' + field1 + '"]')[0].value, this.value, this.getAttribute('validationmsg'))) {
						valida = false;
						this.focus();
						return;
					}
				}
				if(validate = this.getAttribute('validate')) {
					eval('valida = ' + validate + '("' + this.value + '");');
					if(!valida) {
						if(this.getAttribute('validationmsg') != '')
							alert(this.getAttribute('validationmsg'));
						this.focus();
						return;
					}
				}
			}
		});
	return valida;
}

// verifica se uma string está vazia ou só com espaços //
isEmpty = function(str, msg) {
	if($.trim(str) != '')
		return false;
	if(msg != '')
		alert(msg);
	return true;
}

// verifica se um campo tipo checkbox ou radio de um formulário foi marcado //
function isChecked(field, msg) {
	if(field.length) {
		for(i = 0; i < field.length; i++) {
			if(field[i].checked)
				return true;
		}
	}
	else if(field.checked)
		return true;
	if(msg != '')
		alert(msg);
	return false;
}

// verifica se uma string é uma data (dd/mm/aaaa) //
isDate = function(str) {
	if(str.length == 10) {
		dia = parseInt(str.substr(0, 2), 10);
		mes = parseInt(str.substr(3, 2), 10);
		ano = parseInt(str.substr(6, 4), 10);
		if(dia > 0 && dia < 32 && mes > 0 && mes < 13 && ano > 999 && ano < 10000) {
			if(mes == 2 && dia > 28) {
				if(ano % 4)
					return false;
				else if(dia > 29)
					return false;
			}
			switch(mes) {
				case 4:
				case 6:
				case 9:
				case 11:
					if(dia > 30)
						return false;
					break;
			}
		}
		else
			return false;
	}
	else if(str.length)
		return false;
	return true;
}

// verifica se uma string é um e-mail válido //
isMail = function(str) {
	if(str.length)
		return(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str));
	return true;
}

// verifica se uma string é um CPF válido //
isCPF = function(str) {
	var i, j, soma;
	if(str.length) {
		if(str.length != 11)
			return false;
		j = true;
		for(i = 0; i < 9; i++) {
			if(parseInt(str.charAt(i), 10) != parseInt(str.charAt(i + 1), 10)) {
				j = false;
				break;
			}
		}
		if(j)
			return false;
		for(j = 0; j < 2; j++) {
			soma = 0;
			for(i = 0; i < 9 + j; i++)
				soma += parseInt(str.charAt(i), 10) * (10 + j - i);
			soma = 11 - (soma % 11);
			if(soma > 9)
				soma = 0;
			if(soma != parseInt(str.charAt(9 + j), 10))
				return false;
		}
	}
	return true;
}

// verifica se uma string é um CNPJ válido //
isCNPJ = function(str) {
	var i, j, k, soma;
	if(str.length) {
		if(str.length != 14)
			return false;
		for(k = 0; k < 2; k++) {
			soma = 0;
			j = 5 + k;
			for(i = 0; i < 12 + k; i++) {
				soma += parseInt(str.charAt(i), 10) * j;
				if(j > 2)
					j--;
				else
					j = 9;
			}
			soma = 11 - soma % 11;
			if(soma > 9)
				soma = 0;
			if(soma != parseInt(str.charAt(12 + k)))
				return false;
		}
	}
	return true;
}

// compara duas strings //
compareStr = function(str1, str2, msg) {
	if(str1 != str2) {
		if(msg != '')
			alert(msg);
		return false;
	}
	return true;
}

// substitui todas as ocorrências de um char por replace numa string //
substitui = function(chr, rpl, str) {
	while(str.search(chr) >= 0)
		str = str.replace(chr, rpl);
	return str;
}

// limita campo textarea [change][keyup]
function textLimit(campo, tam, count) {
	if(campo.value.length >= tam)
		campo.value = campo.value.substr(0, tam);
	$('#' + count).html(campo.value.length + '');
}