/**
 * Métodos para manipulaçao de formulários.
 * Método deve ser chamado com o $ para que nao haja conflito com outros frameworks utilizados. 
 * Lembrar que o $ é caracter especial no PHP e deve ser escapado quando estiver entre aspas duplas.
 */

var $Form = function() {
	var validando = function validando(form) {		
		var $this, value, label, spanError, labelSpan1, type, text, errors=0, fields=new Array(), spans=new Array();
		
		$j(form).children().filter(':visible').children('div, :input').filter(':visible').each(function(i) {
			$this = $j(this);
			
			if($this[0].tagName == 'DIV') {
				$this.children('input, textarea, select').each(function(k) {
					fields[k] = $j(this);
				});
			} else {
				fields[i] = $this;
			}
		});
		
		for(var i=0; i<fields.length; i++) {			
			$this = fields[i];
			
			if(typeof($this) == 'undefined') { continue; }			
			
			$tag = $this[0].tagName.toLowerCase();
			
			label = $this.prev();
			labelSpan1 = label.children(':first');
			
			if(!$this.attr('disabled') && labelSpan1.hasClass('required')) {
				value = $this.val();
				
				if($tag != 'select' && $tag != 'textarea') {
					type = $this.attr('type').toLowerCase();	
				} else if($tag == 'textarea') {
					type = 'textarea';
				} else if($tag == 'select') {
					type = 'select';
				}
				
				vType = label.attr('class');
				text = labelSpan1.siblings(':first').html();				
				spanError = $this.next();
				
				function error(title) {
					spanError.attr('title', title).css({visibility:'visible'});
					//$this.removeClass().addClass('invalid');
					$this.addClass('invalid');
					errors++;
				}
				
				$this.removeClass('invalid');
				spanError.attr('title', '').css({visibility:'hidden'});
				
				if(type == 'text' || type == 'password' || type == 'textarea') {
					if(isEmpty(value)) {				
						error(text +' é de preenchimento obrigatório.');
					}
					if(typeof(vType) != 'undefined' && vType != '') {
						if(vType.indexOf('phone') != -1) {
							if(!isPhoneNumber(value)) {
								error(value +' não é um número de telefone válido.');
							}
						} else if(vType.indexOf('alpha') != -1) {
							if(!isAlpha(value)){
								error(text +' pode conter somente caracters de A-Z a-z.');
							}
						} else if(vType.indexOf('numeric') != -1) {
							if(!isNumeric(value)){
								error(text +' pode conter somente números.');
							}
						} else if(vType.indexOf('email') != -1) {
							if(!isEmail(value)){
								error(value +' não é um e-mail válido.');
							}
						} else if(vType.indexOf('date') != -1) {
							if(!isDate(value)){
								error(value +' não é uma data válida.');
							}
						}
					}
				} else if(type == 'select') {
					if($this[0].options.length >0) {
						if(isEmpty($this[0].options[$this[0].selectedIndex].value)){
							error(text +' precisa ter um item selecionado.');
						}
					}
				} else if(type == 'file') {
					if(isEmpty(value)){
						error(text +' necessita de um caminho válido para enviar um arquivo.');
					}
				}
			}
		};
		
		return errors == 0;
	};
		
	/* Métodos públicos */
	return {
		/**
		 * Pode ser chamado para validaçao de qualquer formulário que siga os padroes do método HTML::form().
		 * @example 
		 * $Form.validate(formulario) - retorna true(válido) ou false(inválido)
		 * 
		 * ********** ONDE O FORM ESTIVER COM VERSÃO ANTIGA, PASSAR PARA NOVA CITADA ACIMA **********
		 * Caso o formulário nao siga a nova padronizaçao o exemplo abaixo deve ser seguido.
		 * @example
		 * Form.validar(formulario) - retorna true(válido) ou false(inválido)
		 */
		validar:function(form) {
			return validando(form);
		},		
		validate:function(form) {
			return validando(form);
		}
	}
}();