(function($) {

    var servidorRest = "";
    var validacoes = [];

    jQuery.configurar = function(options) {
        servidorRest = options['servidorRest'];
    };

    jQuery.chamar = function(url, data, success) {
        $.ajax({
            type: "POST",
            url: servidorRest + url + ".do",
            data: data + "&token=" + $("#token").val(),
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            success: function(response) {
                $(validacoes).each(function() {
                    $(this).removeClass("trespErro");
                });
                if ($(response).find("resposta>tipo").text() == "ERRO") {
                    $('#conteudo').load("erro.jsp");
                } else if ($(response).find("resposta>tipo").text() == "EXCECAO") {
                    if ($(response).find("codigoExcecao").text() == "VALIDACAO") {
                        var texto = "";
                        $(response).find("resposta>validacoes").each(function() {
                            texto += $(this).find("mensagem").text() + "\n";
                            var campo = $("input[name=" + $(this).find("campo").text() + "]");
                            validacoes.push(campo);
                            campo.addClass("trespErro");
                        });
                        alert(texto);
                    } else {
                        $('#conteudo').load("erro.jsp");
                        alert("Ocorreu a seguinte excecao: (" + $(response).find("codigoExcecao").text() + ") " + $(response).find("mensagemExcecao").text());
                    }
                } else {
                    success(response);
                }
            }
        });
    }
    // Cria o componente de calendário
    jQuery.fn.calendario = function() {
        this.after("<a href='#' class='calendario'><img class='PopcalTrigger' align='absmiddle' src='images/calendario.png' alt='Calendário' style='border:0;'/></a>");
        this.next("a").click(function() {
            var valor = $(this).prev("input").val();
            if(valor=="__/__/____"){
                $(this).prev("input").val("");
            }
            displayCalendar($(this).prev("input").get(0), 'dd/mm/yyyy', $(this).get(0));
        });
        this.attr("size", "12").mask("99/99/9999");
        return this;
    }
    // Faz com que apenas números sejam digitados
    jQuery.fn.numberInput = function() {
        return this.each(function() {
            $(this).keypress(function(event){
                var tecla = event.keyCode ? event.keyCode : event.charCode ? event.charCode : event.which;
                return (KEYS_ALLOWED[tecla] ? true : false);
            });
        });
    };
    var KEYS_ALLOWED = {
           8 : 'BACKSPACE'
        ,  9 : 'TAB'
		, 13 : 'ENTER'
		, 37 : 'LEFT_ARROW'
		, 39 : 'RIGHT_ARROW'
		, 48 : 'ZERO'
		, 49 : 'ONE'
		, 50 : 'TWO'
		, 51 : 'THREE'
		, 52 : 'FOUR'
		, 53 : 'FIVE'
		, 54 : 'SIX'
		, 55 : 'SEVEN'
		, 56 : 'EIGHT'
		, 57 : 'NINE'
    };

    //Adapta o plugin de Validação do JQuery
    jQuery.fn.validate2 = function(rules, messages, success, map) {
        var options = {
            rules: rules,
            messages: messages,
            onfocusout: false,
            onkeyup: false,
            onclick: false,
            errorLabelContainer: "#error",
            errorPlacement: function() {
            // nenhum lugar
            },
            highlight: function(element, errorClass) {
                if(map){
                    $.each(map, function(prop, val) {
                        if($(element).attr("name") == prop){
                            element = $("#"+val);
                        }
                    });
                }
                var tamanho = 0;
                for( method in $(element).rules() ) {
                    if(method == "requiredMult" || method == "minMult"){
                        tamanho = $("body :input[name="+element.name+"]").length;
                        break;
                    }
                }
                //Aplicando a borda nos campos que possuem o mesmo nome e que estão vazios
                if(tamanho>1){
                    for(var e=0;e<tamanho;e++){
                        var el = $("body :input[name="+element.name+"]:eq("+e+")");
                        if(el.val().length == "" || el.val().length == 0){
                            el.addClass(errorClass);
                            el.fadeOut(function() {
                                $(this).fadeIn();
                            });
                        }
                    }
                } else {
                    $(element).addClass(errorClass);
                    $(element).fadeOut(function() {
                        $(element).fadeIn();
                    });
                }
            },
            unhighlight: function(element, errorClass) {
                if(map){
                    $.each(map, function(prop, val) {
                        if($(element).attr("name") == prop){
                            element = $("#"+val);
                        }
                    });
                }
                var tamanho = 0;
                for( method in $(element).rules() ) {
                    if(method == "requiredMult" || method == "minMult"){
                        tamanho = $("body :input[name="+element.name+"]").length;
                        break;
                    }
                }
                //Retirando a borda dos campos que possuem o mesmo nome e que não estão vazios
                if(tamanho>1){
                    for(var e=0;e<tamanho;e++){
                        var el = $("body :input[name="+element.name+"]:eq("+e+")");
                        if(el.val().length>0){
                            el.removeClass(errorClass);
                        }
                    }
                } else {
                    $(element).removeClass(errorClass);
                }
            },
            showErrors: function(errorMap, errorList) {
                this.defaultShowErrors();
                if ($(errorList).length != 0) {
                    var mensagem = "";
                    var mensagemObrigatorios = "";
                    $(errorList).each(function() {
                        if ($(this).attr("message").substr(0, 1) == "-") {
                            mensagemObrigatorios += $(this).attr("message") + "\n";
                        } else {
                            mensagem += $(this).attr("message") + "\n";
                        }
                    });
                    if (mensagemObrigatorios != "") {
                        mensagemObrigatorios = "Os campos abaixo são obrigatórios: \n" + mensagemObrigatorios + "\n";
                    }
                    alert(mensagemObrigatorios + mensagem);
                }
            }
        };
        if (success) {
            options["submitHandler"] = success;
        }
        this.validate(options);
        return this;
    };

    // Adiciona a validação de datas no plugin
    jQuery.validator.addMethod("dateBR", function(value, element) {
        return this.optional(element) || /^(((0[1-9]|[12]\d|3[01])[\.\-\/](0[13578]|1[02])[\.\-\/]((19|20)\d{2}))|((0[1-9]|[12]\d|30)[\.\-\/](0[13456789]|1[012])[\.\-\/]((19|20)\d{2}))|((0[1-9]|1\d|2[0-8])[\.\-\/]02[\.\-\/]((19|20)\d{2}))|(29[\.\-\/]02[\.\-\/]((19|20)(0[48]|[2468][048]|[13579][26])|(2000))))$/.test(value);
    }, "Data inválida!");

    // Adiciona a validação de vários campos com o mesmo nome
    jQuery.validator.addMethod("requiredMult", function(value, element, param) {
        // check if dependency is met
        if ( !this.depend(param, element) )
            return "dependency-mismatch";
        var tamanho = $("body :input[name="+element.name+"]").length;
        if(tamanho>1){
            var i;
            for(i=0;i<tamanho;i++){
                if($("body :input[name="+element.name+"]:eq("+i+")").val().length == "" || $("body :input[name="+element.name+"]:eq("+i+")").val().length == 0){
                    return false;
                }
            }
            return true;
        } else {
            return ($("body :input[name="+element.name+"]").val().length > 0);
        }
    }, "Os campos são obrigatórios!");

    // Adiciona a validação de valor mínimo para vários campos com o mesmo nome.
    jQuery.validator.addMethod("minMult", function(value, element, param) {
        var tamanho = $("body :input[name="+element.name+"]").length;
        if(tamanho>1){
            var i;
            for(i=0;i<tamanho;i++){
                if($("body :input[name="+element.name+"]:eq("+i+")").val() < param) {
                    return false;
                }
            }
            return true;
        } else {
            return this.optional(element) || value >= param;
        }
    }, "Os campos são obrigatórios!");
})(jQuery);

