/*=========================================
CLASSES PARA VALIDAÇÃO:  
obrigatorio   => verifica se está vazio
email         => verifica se a sintaxe corresponde a um e-mail
==========================================*/
	
$.fn.prepararForm = function(options) {	
	$this = $(this);	
	
	var div_erro         = (options.div_erro == undefined)         ? 'msg-erro' 			 : options.div_erro;
	var div_retorno      = (options.div_retorno == undefined) 	   ? undefined				 : options.div_retorno;        
	var erro_obrigatorio = (options.erro_obrigatorio == undefined) ? '* Campos obrigatórios' : options.erro_obrigatorio;
	var erro_email       = (options.erro_email == undefined)       ? 'E-mail incorreto'      : options.erro_email;
	var form_reset       = (options.form_reset == undefined) 	   ? false 					 : options.form_reset;
	funcao_verificao     = (typeof options.funcao_verificao == 'function') ? options.funcao_verificao : undefined;
	funcao_enviando      = (typeof options.funcao_enviando == 'function')  ? options.funcao_enviando  : undefined;
	funcao_sucesso       = (typeof options.funcao_sucesso == 'function')   ? options.funcao_sucesso   : undefined;
	
	$this.submit(function() {
		$('#'+div_erro).fadeOut();
		if(!verificarObrigatorio($this)){		
			$('#'+div_erro).html('<span>'+erro_obrigatorio+'</span>');
			$('#'+div_erro).fadeIn();
		} else if(!verificarEmail($this)){		
			$('#'+div_erro).html('<span>'+erro_email+'</span>');
			$('#'+div_erro).fadeIn();
		} else if((funcao_verificao != undefined) && (funcao_verificao() !== true)){
			$('#'+div_erro).html('<span>'+funcao_verificao()+'</span>');
			$('#'+div_erro).fadeIn();
		} else {
			if(funcao_enviando != undefined) funcao_enviando();
        	$(this).ajaxSubmit({resetForm: form_reset, success: funcao_sucesso, target: div_retorno}); 
		}
        return false; 
    }); 
	
	verificarObrigatorio = function(_form){
		var ver = true;
		$('.obrigatorio', _form).each(function(i, val){		
			if(($('.obrigatorio:eq('+i+')', _form).val() == '') || ($('.obrigatorio:eq('+i+')', _form).val() == $('.obrigatorio:eq('+i+')', _form).attr('ref'))) 
				ver = false;
		})
		return ver;
	}
	
	verificarEmail = function(_form){
		var ver = true;
		var reEmail = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		$('.email', _form).each(function(i, val){		
			if(!reEmail.test($('.email:eq('+i+')', _form).val())) ver = false;
		})
		return ver;
	}
	
	
}
