// Validações.
$(window).load(function () {
	// VALIDAÇÃO POR VISUALIZAÇÃO.
	$('form[validar], form[validar=]').find('input, textarea, select').each(function(index) {
		// Limpa modificações anteriores.
		$(this).blur(function() {
			$(this)
				.removeClass('campoErrado')
				.removeAttr('alt')
				.removeAttr('title')
				.removeAttr('invalido');
		});
		
		// Campo obrigatório.
		if(typeof $(this).attr('obrigatorio') != 'undefined') {
			$(this).after('*');
			$(this).blur(function() {
				if(!($.trim($(this).val()))) {
					var mensagemErro = 'Campo "' + $(this).attr('obrigatorio') + '" obrigatório!';
					$(this)
						.addClass('campoErrado')
						.attr('alt', mensagemErro)
						.attr('title', mensagemErro)
						.attr('invalido', true);
				}
			});
		}

		// Número.
		if(typeof $(this).attr('numero') != 'undefined') {
			$(this).keypress(function(event) {
				if(event.keyCode == '13') {
					return(true);
				} else {
					if(
						(event.keyCode < 48) ||
						(event.keyCode > 57)
					) {
						return(false);
					}
				}
			});
		}
		
		// Data.
		if(typeof $(this).attr('data') != 'undefined') {
			$(this).keypress(function(event) {
				if(event.keyCode == '13') {
					return(true);
				} else {
					if(
						(event.keyCode >= 48) &&
						(event.keyCode <= 57)
					) {
						$(this).val(mascara('##/##/####', $(this).val(), event));
					}
					return(false);
				}
			});
			$(this).blur(function() {
				if($(this).val()) {
					// Cria a máscara novamente (precaução).
					$(this).val(mascara('##/##/####', $(this).val()));
					
					// RegExp validação.
					var regData = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/(19|20)?\d{2}$/;
					if(!regData.test($(this).val())) {
						var mensagemErro = 'Data inválida!';
						$(this)
							.addClass('campoErrado')
							.attr('alt', mensagemErro)
							.attr('title', mensagemErro)
							.attr('invalido', true);
					}
				}
			});
		}
		
		// CEP.
		if(typeof $(this).attr('cep') != 'undefined') {
			$(this).keypress(function(event) {
				if(event.keyCode == '13') {
					return(true);
				} else {
					if(
						(event.keyCode >= 48) &&
						(event.keyCode <= 57)
					) {
						$(this).val(mascara('#####-###', $(this).val(), event));
					}
					return(false);
				}
			});
		}

		// Telefone.
		if(typeof $(this).attr('telefone') != 'undefined') {
			$(this).keypress(function(event) {
				if(event.keyCode == '13') {
					return(true);
				} else {
					if(
						(event.keyCode >= 48) &&
						(event.keyCode <= 57)
					) {
						if($(this).attr('telefone').indexOf('ddi') >= 0) {
							$(this).val(mascara('(##) (##) ####-####', $(this).val(), event));
						} else if($(this).attr('telefone').indexOf('ddd') >= 0) {
							$(this).val(mascara('(##) ####-####', $(this).val(), event));
						} else {
							$(this).val(mascara('####-####', $(this).val(), event));
						}
					}
					return(false);
				}
			});
		}
		
		// E-mail.
		if(typeof $(this).attr('email') != 'undefined') {
			$(this).blur(function() {
				if($(this).val()) {
					// RegExp validação.
					var regEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/
					if(!regEmail.test($(this).val())) {
						var mensagemErro = 'E-mail inválido!';
						$(this)
							.addClass('campoErrado')
							.attr('alt', mensagemErro)
							.attr('title', mensagemErro)
							.attr('invalido', true);
					}
				}
			});
		}

		// CPF.
		if(typeof $(this).attr('cpf') != 'undefined') {
			$(this).keypress(function(event) {
				if(event.keyCode == '13') {
					return(true);
				} else {
					if(
						(event.keyCode >= 48) &&
						(event.keyCode <= 57)
					) {
						$(this).val(mascara('###.###.###-##', $(this).val(), event));
					}
					return(false);
				}
			});
			$(this).blur(function() {
				if($(this).val()) {
					// Cria a máscara novamente (precaução).
					$(this).val(mascara('###.###.###-##', $(this).val(), event));
					
					// Validação.
					if(!validarCPF($(this).val())) {
						var mensagemErro = 'CPF inválido!';
						$(this)
							.addClass('campoErrado')
							.attr('alt', mensagemErro)
							.attr('title', mensagemErro)
							.attr('invalido', true);
					}
				}
			});
		}

		// URL.
		if(typeof $(this).attr('url') != 'undefined') {
			$(this).focus(function() {
				if($(this).val() == '') {
					$(this).val('http://');
				}
			});
			
			$(this).blur(function() {
				if($(this).val()) {
					// RegExp validação.
					var regURL = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
					if(!regURL.test($(this).val())) {
						var mensagemErro = 'URL inválida!';
						$(this)
							.addClass('campoErrado')
							.attr('alt', mensagemErro)
							.attr('title', mensagemErro)
							.attr('invalido', true);
					}
				}
			});
		}

		// Estado.
		if(typeof $(this).attr('estado') != 'undefined') {
			var combo = $(this);
			
			// Limpa o combo.
			$(combo).children().remove();
			
			// Cria um "selecione".
			var optSelEstado = document.createElement('option');
			$(optSelEstado).html('Selecione Estado');
			// ... e o coloca no combo de Estado.
			$(combo).append(optSelEstado);

			// Se possuir uma referência "preenchitiva" para cidade, cria o evento.
			if(typeof $(combo).attr('refCidade') != 'undefined') {
				$(combo).change(function() {
					var estado = $(this).val();
					var HTMLIdCidade = $(combo).attr('refCidade');
					
					var preencheCidade = function(data) {
						// Limpa o combo de cidades.
						$('#' + HTMLIdCidade).children().remove();
						
						var cidades = jQuery.parseJSON(data);
						for (var i in cidades){
							var cidade = cidades[i];

							// Cria um novo option...
							var optCidade = document.createElement('option');
							$(optCidade).val(cidade.id);
							$(optCidade).html(cidade.nome);
							
							// Se o option tiver o mesmo valor do valor padrão do combobox:
							if($('#' + HTMLIdCidade).attr('cidade') == cidade.id) {
								// Seleciona-o!
								$(optCidade).attr('selected', 'selected');
							}
							
							// ... e o coloca no combo de cidade.
							$('#' + HTMLIdCidade).append(optCidade);
						}
					};
					$.post('ajax/cidades.php', {uf: estado}, preencheCidade);
					$.post('../ajax/cidades.php', {uf: estado}, preencheCidade);
					$.post('../../ajax/cidades.php', {uf: estado}, preencheCidade);
				});
			}
			
			// Preenche com os estados do banco.
			var preencheEstado = function(data) {
				var estados = jQuery.parseJSON(data);
				for (var i in estados){
					var estado = estados[i];

					// Cria um novo option para depois ser colocado no combo.
					var optEstado = document.createElement('option');
					$(optEstado).val(estado.id);
					$(optEstado).html(estado.nome);
					
					// Se o option tiver o mesmo valor do valor padrão do combobox:
					if($(combo).attr('estado') == estado.id) {
						// Seleciona-o!
						$(optEstado).attr('selected', 'selected');
						
						// Coloca no combo de estado.
						$(combo).append(optEstado);
						
						// E manda desmenbrar o combo de cidades.
						$(combo).change();
					} else {
						// Coloca no combo de estado.
						$(combo).append(optEstado);
					}
				}
			};
			$.post('ajax/estados.php', preencheEstado);
			$.post('../ajax/estados.php', preencheEstado);
			$.post('../../ajax/estados.php', preencheEstado);
		}

		// Cidade.
		if(typeof $(this).attr('cidade') != 'undefined') {
			var combo = $(this);
			
			// Limpa o combo.
			$(combo).children().remove();
		}

	});
	
	// VALIDAÇÃO POR ENVIO.
	// Para todos os formulários com a propriedade "validar":
	$('form[validar], form[validar=]').each(function(index) {
		$(this).submit(function() {
			var erros = new Array();
			
			// Valida os campos:
			$(this).find('input, textarea, select').each(function(index) {
				// A validação do campo encontra-se na perda do foco.
				$(this).blur();
				// Havendo campo inválido, guarda a informação.
				if($(this).attr('invalido')) {
					erros.push($(this).attr('alt'));
				}
			});
			
			// Confere se houveram erros.
			if(erros.length > 0) {
				alert('Por favor, conferir os seguintes campos:\n\n* ' + erros.join('\n* '));
				return(false);
			} else {
				return(true);
			}
		});
	});
	
	// Todos os "caixaalta" CSS serão mudados para um real caixa alta via js.
	$('.caixaalta').blur(function() {
		$(this).val($(this).val().toUpperCase());
	});
	
});





















































/**
 * Validador de CPF.
 * 
 * @param string cpf CPF com números e símbolos
 * @return boolean
 */
function validarCPF(cpf) {
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	if (!filtro.test(cpf)) {
		window.alert("CPF inválido. Tente novamente.");
		return false;
	}

	var remove = function(str, sub) {
		i = str.indexOf(sub);
		r = "";
		if (i == -1)
			return str;
		r += str.substring(0, i) + remove(str.substring(i + sub.length), sub);
		return r;
	}
	
	cpf = remove(cpf, ".");
	cpf = remove(cpf, "-");

	if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111"
			|| cpf == "22222222222" || cpf == "33333333333"
			|| cpf == "44444444444" || cpf == "55555555555"
			|| cpf == "66666666666" || cpf == "77777777777"
			|| cpf == "88888888888" || cpf == "99999999999") {
		window.alert("CPF inválido. Tente novamente.");
		return false;
	}

	soma = 0;
	for (i = 0; i < 9; i++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(9))) {
		window.alert("CPF inválido. Tente novamente.");
		return false;
	}
	soma = 0;
	for (i = 0; i < 10; i++)
		soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(10))) {
		return false;
	}
	return true;
}

