/**
 * @author Renato renatomorenocz@gmail.com
 * @license Creative Commons http://creativecommons.org/licenses/by/2.0/br/
 * @copyright Oeste Sistemas http://www.oestesistemas.com.br
 */
///////////////////////////////////////////////////////////////////////////////////////////
// Cria Closure
(function($){

    // Definição do plugin
    $.fn.pForm = function(options){
    
        // Pego as informaçãoes do plugin
        // Troca as informações default pelas dos usuarios
        var opts = $.extend({}, $.fn.pForm.defaults, options);
        
        
        // Variavel utilizada para verifica os erros
        error = 0;
        
        
        // Percorro todos elementos encontrados
        return this.each(function(){
        
        
            // Cria uma instancia jquery do elemento
            var $this = $(this);
            
            
            // Evento de submit
            $this.submit(function(event){
            
                // Removo os erros anteriores
                $('.errorPform').remove();
                error = 0;
                
                // Pecorro os metodos de validação	                            
                $this.contents().find(".vlNull").each(function(){
                    $campo = $(this);
                    vlNull($campo);
                });
                
                $this.contents().find(".vlMail").each(function(){
                    $campo = $(this);
                    vlMail($campo);
                });
                
                if (error == 0) {
                
                    // Dados do form
                    data = $this.serialize();
                    
                    
					opts.start();
					
                    // Cria a requisição ajax
                    $.ajax({
                        type: opts.method,
                        url: opts.action,
                        data: data,
                        dataType: opts.type,
                        success: opts.success
                    });
                    
                }
                
                
                // Impede que atualiza a pagina 
                // Mata o evento
                event.preventDefault();
                return false;
            });
            
            
            
            
        });
        
    };
    // Fim     
    
    // Valores Default do plugin          
    $.fn.pForm.defaults = {
        action: '/ajax.php',
        method: 'post',
        type: 'json',
		start: function() {
			alert ('carregando');
		},
        success: function(data, status, xml){
            alert(data);
            return true;
        }
        
    };
    
    
    // Funções Privadas
    
    // Metodo de validação nulo
    function vlNull($campo){
        if ($campo.val() == "") {
            error++;
            mostraError($campo, 'Preenchar o campo');
        }
    };
    
    
    // Metodo de validação Mail
    function vlMail($campo){
        if (!validaEmail($campo.val())) {
            error++;
            mostraError($campo, 'E-mail Inválido');
        }
    };
    
    
    function validaEmail(mail){
        var er = RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
        if (er.test(mail) == false) {
            return false;
        }
        
        return true;
    }
    
    // Função p/ Mostrar as mensagens de error
    function mostraError($campo, msg){
    
        // Tamanho do elemento 
        var wElemento = parseInt($campo.outerWidth());
        
        // Posicao
        var posicao = $campo.offset();
        
		
        // Cria a mensagem error
        $('body').append('<div class="errorPform" id="error' + error + '">' + msg + '</div>');
        
		
        // Posiciona a mensagem de error
        $('#error' + error).css({
            position: 'absolute',
            top: posicao.top - 13 ,
            left: ( posicao.left + 3) 
        });
        
    }
    
    
    // Retorna o elemento
    return this;
    
    
})(jQuery);
//
// Fim do closure
//

