/* Minification failed. Returning unminified contents.
(1,18): run-time error CSS1031: Expected selector, found '='
(1,18): run-time error CSS1025: Expected comma or open brace, found '='
(2,18): run-time error CSS1031: Expected selector, found '='
(2,18): run-time error CSS1025: Expected comma or open brace, found '='
(5,1): run-time error CSS1019: Unexpected token, found '$'
(5,2): run-time error CSS1019: Unexpected token, found '('
(5,12): run-time error CSS1031: Expected selector, found '('
(5,12): run-time error CSS1025: Expected comma or open brace, found '('
(163,2): run-time error CSS1019: Unexpected token, found ')'
(166,10): run-time error CSS1031: Expected selector, found 'onAjaxFailure('
(166,10): run-time error CSS1025: Expected comma or open brace, found 'onAjaxFailure('
(198,18): run-time error CSS1031: Expected selector, found 'validateForm('
(198,18): run-time error CSS1025: Expected comma or open brace, found 'validateForm('
(244,18): run-time error CSS1031: Expected selector, found 'validatePayload('
(244,18): run-time error CSS1025: Expected comma or open brace, found 'validatePayload('
(461,10): run-time error CSS1031: Expected selector, found 'isValidCPF('
(461,10): run-time error CSS1025: Expected comma or open brace, found 'isValidCPF('
(494,10): run-time error CSS1031: Expected selector, found 'buildErrorContent('
(494,10): run-time error CSS1025: Expected comma or open brace, found 'buildErrorContent('
(509,10): run-time error CSS1031: Expected selector, found 'showMessageBox('
(509,10): run-time error CSS1025: Expected comma or open brace, found 'showMessageBox('
(558,10): run-time error CSS1031: Expected selector, found 'updateSection('
(558,10): run-time error CSS1025: Expected comma or open brace, found 'updateSection('
(584,10): run-time error CSS1031: Expected selector, found 'getParentDialogRef('
(584,10): run-time error CSS1025: Expected comma or open brace, found 'getParentDialogRef('
(593,10): run-time error CSS1031: Expected selector, found 'closeDialog('
(593,10): run-time error CSS1025: Expected comma or open brace, found 'closeDialog('
(601,10): run-time error CSS1031: Expected selector, found 'updateContainer('
(601,10): run-time error CSS1025: Expected comma or open brace, found 'updateContainer('
(612,10): run-time error CSS1031: Expected selector, found 'updateSearchContainer('
(612,10): run-time error CSS1025: Expected comma or open brace, found 'updateSearchContainer('
(620,10): run-time error CSS1031: Expected selector, found 'updateSearchContainer2('
(620,10): run-time error CSS1025: Expected comma or open brace, found 'updateSearchContainer2('
(627,10): run-time error CSS1031: Expected selector, found 'makeAjaxCall('
(627,10): run-time error CSS1025: Expected comma or open brace, found 'makeAjaxCall('
 */
var arrDialogRef = [];
var curDialogRef = null;

// on load of application
$(function () {

    curDialogRef = $("#ListaGeral");

    $(document).on("click", "a.dialog", function (event) {

        event.preventDefault();

        var currentLinkRef = this;
        var url = $(this).attr("href");
        var title = $(this).attr("title");
        var dialog = $("<div></div>");

        $(dialog)
            .load(url)
            .dialog({
                title: title,
                autoOpen: false,
                resizable: false,
                height: 'auto',
                width: '60%',
                minWidth: '400',
                minHeight: '400',
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {

                    var me = this;

                    // storing reference
                    arrDialogRef.push({
                        Source: curDialogRef,// parent dialog reference
                        Destination: me, // child or open dialog refernce
                        Element: currentLinkRef, // current link reference
                    });

                    curDialogRef = me;
                },
                close: function (event, ui) {

                    // releasing resource of dialog on close event
                    var me = this;
                    $.each(arrDialogRef, function (i, val) {

                        if (val.Destination == me) {
                            curDialogRef = val.Source;
                            arrDialogRef.splice(i, 1);
                            return false;
                        }
                    });

                    $(this).empty().dialog('destroy').remove();
                }
            });

        $(dialog).dialog('open');
    });

    $(document).on("click", "a.dialog2", function (event) {

        event.preventDefault();

        var currentLinkRef = this;
        var url = $(this).attr("href");
        var title = $(this).attr("title");
        var dialog = $("<div></div>");

        $(dialog)
            .load(url)
            .dialog({
                title: title,
                autoOpen: false,
                resizable: false,
                height: 'auto',
                width: '99%',
                minWidth: '600',
                minHeight: '700',
                show: { effect: 'drop', direction: "up" },
                modal: true,
                draggable: true,
                open: function (event, ui) {

                    var me = this;

                    // storing reference
                    arrDialogRef.push({
                        Source: curDialogRef,// parent dialog reference
                        Destination: me, // child or open dialog refernce
                        Element: currentLinkRef, // current link reference
                    });

                    curDialogRef = me;
                },
                close: function (event, ui) {

                    // releasing resource of dialog on close event
                    var me = this;
                    $.each(arrDialogRef, function (i, val) {

                        if (val.Destination == me) {
                            curDialogRef = val.Source;
                            arrDialogRef.splice(i, 1);
                            return false;
                        }
                    });

                    $(this).empty().dialog('destroy').remove();
                }
            });

        $(dialog).dialog('open');
    });

    $(document).on("click", "a.delete", function (event) {

        event.preventDefault();
        var url = $(this).attr("href");

        showMessageBox({
            title: "Pergunta",
            content: "Tem certeza que deseja excluir este registro?",
            btn1text: "Sim",
            btn2text: "Não",
            functionText: "makeAjaxCall",
            parameterList: {
                url: url,
                callback: 'updateSection'
            }
        });
    });

    $(document).on("click", "a.confirma", function (event) {

        event.preventDefault();
        var url = $(this).attr("href");

        showMessageBox({
            title: "Pergunta",
            content: "Confirma o processamento?",
            btn1text: "Sim",
            btn2text: "Não",
            functionText: "makeAjaxCall",
            parameterList: {
                url: url,
                callback: 'updateSection'
            }
        });
    });

    $(document).on("click", "a.marcar", function (event) {
        event.preventDefault();
        var url = $(this).attr("href");
        var par = { url: url, callback: 'updateSection' }
        makeAjaxCall(par);
    });

    updateSection(); // update the section of product list on load
});


function onAjaxFailure(response) {
    console.log(response);

    try {
        var data = $.parseJSON(response.responseJSON);
        var content = "<ul>";

        for (var key in data) {
            content += "<li>" + data[key] + "</li>";
        }

        content += "</ul>";

        showMessageBox({
            title: "Erro",
            content: content,
            btn1text: "Ok",
            btn2text: "Sair"
        });
    } catch (error) {
        console.error("Erro ao processar:", error);

        showMessageBox({
            title: "Erro",
            content: "Ocorreu um erro inesperado. Verifique os dados e tente novamente.",
            btn1text: "Ok",
            btn2text: "Sair"
        });
    }
}


        function validateForm(e) {
            e.preventDefault(); // Previne o envio padrão do formulário

            // Encontre o botão que foi clicado (target)
            var submitButton = e.target;

            // Encontre o formulário dentro da modal, buscando o formulário mais próximo do botão
            var form = submitButton.closest('form');

            // Exibe os valores dos campos no console para depuração
            console.log('Valores do Payload:');
            var inputs = form.querySelectorAll('input, select, textarea');

            /// Itera sobre os campos do formulário
            var formData = {};
            inputs.forEach(function (input) {
                var name = input.name || input.id; // Acessa o nome ou id do campo
                var value = input.type === 'checkbox' ? input.checked : input.value; // Considera se o campo é checkbox
                formData[name] = value;

                // Exibe o nome, o valor e o tipo do campo no console
                console.log(name + ": " + value + " (Tipo: " + input.type + ")");

                // Itera sobre todos os atributos do campo e os imprime
                Array.from(input.attributes).forEach(function (attr) {
                    console.log(" - " + attr.name + ": " + attr.value);
                });
            });

            // Valide o formulário
            var errors = validatePayload(form);

            if (errors.length > 0) {
                showMessageBox({
                    title: "Erro ao validar",
                    content: buildErrorContent(errors),
                    btn1text: "Ok",
                    btn2text: "Corrigir"
                });
            } else {
                // Se válido, submete o formulário via AJAX
                var ajaxForm = $(form).closest("form");
                ajaxForm.submit();
            }
        }

        function validatePayload(form) {
            var errors = [];
            var inputs = form.querySelectorAll("[data-val='true']");

            inputs.forEach(function (input) {
                var inputValue = input.value.trim();

                // Validação 'Required'
                if (input.hasAttribute("data-val-required") && !inputValue) {
                    errors.push(input.getAttribute("data-val-required"));
                }

                // Validação 'StringLength' (mínimo e máximo)
                if (input.hasAttribute("data-val-length")) {
                    var minLength = parseInt(input.getAttribute("data-val-length-min"), 10) || 0;
                    var maxLength = parseInt(input.getAttribute("data-val-length-max"), 10) || Infinity;
                    var valueLength = inputValue.length;

                    if (valueLength < minLength || valueLength > maxLength) {
                        errors.push(input.getAttribute("data-val-length"));
                    }
                }

                //// Validação de Data Futura
                //if (input.getAttribute("data-val-required") && input.type === "date") {
                //    var inputValue = input.value.trim();

                //    // Verifica se o campo está vazio e adiciona erro
                //    if (!inputValue) {
                //        errors.push(input.getAttribute("data-val-required"));  // Mensagem de erro para campo vazio
                //        return; // Se o campo estiver vazio, retorna sem fazer mais nada
                //    }

                //    var inputDate = new Date(inputValue);
                //    var now = new Date();

                //    // Verifica se a data é válida
                //    if (isNaN(inputDate.getTime())) {
                //        //errors.push("Data inválida.");  // Adiciona erro se a data for inválida
                //        return;
                //    }

                //    // Comparando as datas sem as horas, minutos e segundos
                //    inputDate.setHours(0, 0, 0, 0);
                //    now.setHours(0, 0, 0, 0);

                //    // Verifica se a data do input é maior que a data atual
                //    if (inputDate > now) {
                //        errors.push(input.getAttribute("data-val-customvalidationdate") || "Veja se tem alguma data no futuro.");
                //    }
                //}
                // Validação de Data Futura

                // Validação de Data Futura
                if (input.getAttribute("data-val-required") && input.type === "date") {
                    var inputValue = input.value.trim();

                    // Verifica se o campo está vazio e adiciona erro
                    if (!inputValue) {
                        errors.push(input.getAttribute("data-val-required"));  // Mensagem de erro para campo vazio
                        return; // Se o campo estiver vazio, retorna sem fazer mais nada
                    }

                    var inputDate = new Date(inputValue);
                    var now = new Date();

                    // Verifica se a data é válida
                    if (isNaN(inputDate.getTime())) {
                        //errors.push("Data inválida.");  // Adiciona erro se a data for inválida
                        return;
                    }

                    // Comparando as datas sem as horas, minutos e segundos
                    inputDate.setHours(0, 0, 0, 0);
                    now.setHours(0, 0, 0, 0);

                    // Verifica se a data do input é maior que a data atual
                    if (inputDate > now) {

                        var fieldName = input.getAttribute("name");
                        if (!fieldName) {
                            fieldName = input.getAttribute("id") ? input.getAttribute("id") : "Campo sem identificação";
                        }
                        errors.push("O campo " + fieldName + " " + "está no futuro");
                    }
                }
                //Validação de Data Futura fim

                // Validação 'Range'
                if (input.hasAttribute("data-val-range")) {
                    var min = parseFloat(input.getAttribute("data-val-range-min")) || -Infinity;
                    var max = parseFloat(input.getAttribute("data-val-range-max")) || Infinity;
                    var value = parseFloat(inputValue);

                    if (isNaN(value) || value < min || value > max) {
                        errors.push(input.getAttribute("data-val-range"));
                    }
                }

                // Validação de CPF
                if (input.hasAttribute("data-val-customvalidationcpf")) {
                    var cpf = inputValue.replace(/[^0-9]/g, "");
                    if (!isValidCPF(cpf)) {
                        errors.push(input.getAttribute("data-val-customvalidationcpf"));
                    }
                }

                // Validação 'Regex'
                if (input.hasAttribute("data-val-regex") && inputValue) {
                    var pattern = new RegExp(input.getAttribute("data-val-regex-pattern"));
                    if (!pattern.test(inputValue)) {
                        errors.push(input.getAttribute("data-val-regex"));
                    }
                }
            });

            return errors;
        }


//function validatePayload(form) {
//    var errors = [];
//    var inputs = form.querySelectorAll("[data-val='true']");

//    inputs.forEach(function (input) {
//        // Validação 'Required'
//        if (input.getAttribute("data-val-required") && !input.value.trim()) {
//            errors.push(input.getAttribute("data-val-required"));
//        }

//        // Validação 'StringLength' (mínimo e máximo)
//        if (input.getAttribute("data-val-length")) {
//            var minLength = input.getAttribute("data-val-length-min");
//            var maxLength = input.getAttribute("data-val-length-max");
//            var valueLength = input.value.length;

//            if ((minLength && valueLength < minLength) || (maxLength && valueLength > maxLength)) {
//                errors.push(input.getAttribute("data-val-length"));
//            }
//        }


//        // Validação de Data Futura
//        if (input.getAttribute("data-val-required") && input.type === "date") {
//            var inputValue = input.value.trim();

//            // Verifica se o campo está vazio e adiciona erro
//            if (!inputValue) {
//                errors.push(input.getAttribute("data-val-required"));  // Mensagem de erro para campo vazio
//                return; // Se o campo estiver vazio, retorna sem fazer mais nada
//            }

//            var inputDate = new Date(inputValue);
//            var now = new Date();

//            // Verifica se a data é válida
//            if (isNaN(inputDate.getTime())) {
//                //errors.push("Data inválida.");  // Adiciona erro se a data for inválida
//                return;
//            }

//            // Comparando as datas sem as horas, minutos e segundos
//            inputDate.setHours(0, 0, 0, 0);
//            now.setHours(0, 0, 0, 0);

//            // Verifica se a data do input é maior que a data atual
//            if (inputDate > now) {
//                errors.push(input.getAttribute("data-val-customvalidationdate") || "Veja se tem alguma data no futuro.");
//            }
//        }


//        // Validação 'Range'
//        if (input.getAttribute("data-val-range")) {
//            var min = input.getAttribute("data-val-range-min");
//            var max = input.getAttribute("data-val-range-max");
//            var value = parseFloat(input.value);

//            if ((min && value < min) || (max && value > max)) {
//                errors.push(input.getAttribute("data-val-range"));
//            }
//        }

//        // Validação de CPF
//        if (input.getAttribute("data-val-customvalidationcpf")) {
//            var cpf = input.value.replace(/[^0-9]/g, ""); // Remove caracteres não numéricos

//            if (!isValidCPF(cpf)) {
//                errors.push(input.getAttribute("data-val-customvalidationcpf"));
//            }
//        }

//        inputs.forEach(function (input) {
//            // Validação de CPF
//            if (input.getAttribute("data-val-customvalidationcpf")) {
//                var cpf = input.value.replace(/[^0-9]/g, ""); // Remove caracteres não numéricos

//                if (!isValidCPF(cpf)) {
//                    errors.push(input.getAttribute("data-val-customvalidationcpf"));
//                }
//            }
//        });


//        // Validação 'Regex'
//        if (input.getAttribute("data-val-regex") && input.value) {
//            var pattern = new RegExp(input.getAttribute("data-val-regex-pattern"));
//            if (!pattern.test(input.value)) {
//                errors.push(input.getAttribute("data-val-regex"));
//            }
//        }
//    });

//    return errors;
//}

// Função para validar CPF
function isValidCPF(cpf) {
    // Permite CPF vazio
    if (!cpf || cpf.trim() === "") {
        return true;
    }

    if (cpf.length !== 11 || /^(\d)\1+$/.test(cpf)) {
        return false; // CPF inválido se tiver menos de 11 dígitos ou todos iguais
    }

    var sum = 0, mod;

    // Valida o primeiro dígito verificador
    for (var i = 0; i < 9; i++) {
        sum += parseInt(cpf.charAt(i)) * (10 - i);
    }
    mod = 11 - (sum % 11);
    if (mod >= 10) mod = 0;
    if (mod !== parseInt(cpf.charAt(9))) {
        return false;
    }

    // Valida o segundo dígito verificador
    sum = 0;
    for (var i = 0; i < 10; i++) {
        sum += parseInt(cpf.charAt(i)) * (11 - i);
    }
    mod = 11 - (sum % 11);
    if (mod >= 10) mod = 0;

    return mod === parseInt(cpf.charAt(10));
}

function buildErrorContent(errors) {
    // Usa um Set para armazenar erros únicos
    var uniqueErrors = new Set(errors);

    var content = "<ul>";
    uniqueErrors.forEach(function (error) {
        content += "<li>" + error + "</li>";
    });
    content += "</ul>";

    return content;
}



function showMessageBox(params) {

    var btn1css;
    var btn2css;

    if (params.btn1text) {
        btn1css = "showcss";
    } else {
        btn1css = "hidecss";
    }

    if (params.btn2text) {
        btn2css = "showcss";
    } else {
        btn2css = "hidecss";
    }

    $("#lblMessage").html(params.content);

    $("#dialog").dialog({
        resizable: false,
        title: params.title,
        modal: true,
        width: 'auto',
        height: 'auto',
        bgiframe: false,
        hide: { effect: 'scale', duration: 400 },
        buttons: [
            {
                text: params.btn1text,
                "class": btn1css,
                click: function () {
                    if (params.functionText) { window[params.functionText](params.parameterList); } // Call function after clicking on button.
                    $("#dialog").dialog('close');
                }
            },
            {
                text: params.btn2text,
                "class": btn2css,
                click: function () {
                    $("#dialog").dialog('close');
                }
            }
        ]
    });
}



function updateSection() {
    
    var source = null;
    var updateContainerId = "";
    var ref = getParentDialogRef();
    if (ref && ref.Destination) {
        source = ref.Destination;
        updateContainerId = source;
    }
    else if (curDialogRef) {
        source = curDialogRef;
        updateContainerId = $("#gride_geral");
    }

    var url = $(source).find("form").attr("action");

    if (url) {

        $.get(url, function (data) {
            
            $(updateContainerId).html(data);
        });
    }
}


function getParentDialogRef() {
    if (arrDialogRef && arrDialogRef.length > 0) {
        return arrDialogRef[arrDialogRef.length - 1];
    }

    return null;
}


function closeDialog() {

    var ref = getParentDialogRef();
    if (ref) {
        $(ref.Destination).dialog("close");
    }
}

function updateContainer(response) {
    var ref = getParentDialogRef();

    if (ref) {

        $(ref.Element).parent().find("input[type='hidden']").val(response.Id);
        $(ref.Element).parent().find("input[type='text']").val(response.Name);
        closeDialog();
    }
}

function updateSearchContainer(response) {
    var ref = getParentDialogRef();
    if (ref) {
        $(ref.Destination).html(response);
    }
}


function updateSearchContainer2(response) {
    var ref = getParentDialogRef();
    if (ref) {
        $(ref.Destination).html(response);
    }
}

function makeAjaxCall(params) {

    $.ajax({
        type: 'POST',
        url: params.url,
        data: params.parameters,
        dataType: 'json',
        success: function (response) {
            if (response.success) {
                eval(params.callback + '(response)');
            }
        }
    })
}




