$(document).ready(function() {

    // $(".loaderchart").hide();

    $("input[name='country[]']").on("click", function(e) {
        $('#actualiza-data').empty();
        var currentid = $(this).attr('value');
        //console.log(available_dates);
        $(JSON.parse(available_dates)).each(function() {
            var form = "";
            if ($(this)[0].idPais == currentid) {
                if ($(this)[0].formulario == "1SR") {
                    form = "el Banco Central";
                } else if ($(this)[0].formulario == "2SR") {
                    form = "Otras Sociedades de Depósito";
                } else if ($(this)[0].formulario == "4SR") {
                    form = "Otras sociedades Financieras";
                }
                var msg = "<p>La información correspondiente a " + form + " para " + $(this)[0].pais + " esta actualizada a " + $(this)[0].custom1 + " del " + $(this)[0].anno + "</p>";
                $('#actualiza-data').append(msg);
            }
        });
    });


    $('#extra-per-first').val('');
    $('#extra-per-last').val('');

    $('.extra_years_esea').empty();
    $('.extra_years_esea').append('<option value="">-- Selecciona un año --</option>');
    for (var i = 1990; i <= new Date().getFullYear(); i++) {
        $('.extra_years_esea').append('<option value="' + i + '">' + i + '</option>');
    }

    // $('#pills-fecha-tab').click(function() {
    //     $('#extra-year-first').val("");
    //     $('#extra-mouth-first').val("");
    //     $('#extra-year-last').val("");
    //     $('#extra-mouth-last').val("");  
    // });

});

var dat_cat = $('#parameters h2').data('parent');
var scid = $('.js-scid').data('scid');

$('input[type=checkbox]').click(function() {

    if ($(this).prop("checked")) {
        appendSelected(this);
    } else {
        var text = $(this).parent().find("label").text();
        var options = $(this).parent().parent().parent().parent().find(".options-wrapper").find(".options").toArray();
        $.each(options, function(index, value) {
            var text_tofind = $(value).find("p").text();
            if (text == text_tofind) {
                $(value).remove();
            }
        });
    }
});

function appendSelected(el) {
    var that = el;
    var name = $(that).attr('name');
    var text = $(that).parent().find("label").text();
    if (name.includes('country')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck-tabs'>X</a></div>";
        $('.options-country-wrapper').append(html);
    } else if (name.includes('dates')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
        $('.options-fe-wrapper').append(html);
    } else if (name.includes('var')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
        $('.options-var-wrapper').append(html);
    } else if (name.includes('units')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
        $('.options-unit-wrapper').append(html);
    } else if (name.includes('refs')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
        $('.options-ref-wrapper').append(html);
    } else if (name.includes('fits')) {
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
        $('.options-ajust-wrapper').append(html);
    }
}


$(".js-remove-all").click(function() {
    var inputs = $(this).parent().parent().find('input[type=checkbox]');
    $.each(inputs, function(index, value) {
        $(value).prop("checked", false);
    });
    $($(this).parent().parent().find('.options-wrapper')).empty();
});


$(".js-remove-all-tabs").click(function() {
    var inputs = $(this).parent().parent().find('input[type=checkbox]');
    $.each(inputs, function(index, value) {
        $(value).prop("checked", false);
    });
    $(this).parent().parent().parent().parent().find('.options-wrapper').empty();
});

$(".js-take-all-tabs").click(function() {
    $($(this).parent().parent().find('.options-wrapper')).empty();
    var inputs = $(this).parent().parent().find('input[type=checkbox]');
    inputs.toArray();
    $.each(inputs, function(index, value) {
        $(value).prop("checked", true);
        var text = $(value).parent().find("label").text();
        var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck-tabs'>X</a></div>";
        var dad = $(value).parent().parent().parent().parent().find(".options-wrapper");
        $(dad).append(html);
    });
});

$(".js-take-all").click(function() {
    $($(this).parent().parent().find('.options-wrapper')).empty();
    var inputs = $(this).parent().parent().find('input[type=checkbox]');
    inputs.toArray();
    $.each(inputs, function(index, value) {
        var text = $(value).parent().find("label").text();
        if (text != "PIB anual en constantes-variación | SV-DO" && text != "PIB anual en constantes | SV-DO") {
            $(value).prop("checked", true);
            var html = "<div class='options'><p>" + text + "</p><a class='js-uncheck'>X</a></div>";
            var dad = $(value).parent().parent().parent().find(".options-wrapper");
            $(dad).append(html);
        }
    });
});

$("body").on("click", ".js-uncheck", function() {
    var that = this;
    var inputs = $(this).parent().parent().parent().find(".box-content").find('input[type=checkbox]').toArray();
    var name = $(this).parent().find('p').text();
    var that = $(this);
    $.each(inputs, function(index, value) {
        var search = $(value).parent().find("label").text();
        if (search == name) {
            $(value).prop("checked", false);
            $(that).parent().remove();
        }
    });
});

$("body").on("click", ".js-uncheck-tabs", function() {
    var that = this;
    var inputs = $(that).parent().parent().parent().find('.tab-content').find(".tab-pane").first().find('input[type=checkbox]').toArray();
    var name = $(this).parent().find('p').text();
    var that = $(this);
    $.each(inputs, function(index, value) {
        var search = $(value).parent().find("label").text();
        if (search == name) {
            $(value).prop("checked", false);
            $(that).parent().remove();
        }
    });
});

$("#send").click(function(e) {
    var atLeastOneChecked = false;
    var atLeastOneChecked_var = false;
    var atLeastOneChecked_per = false;
    var atLeastOneChecked_un = false;
    var atLeastOneChecked_ref = false;
    var atLeastOneChecked_aju = false;
    var atLeastOneChecked_years = false;
    var atLeastOneChecked_mouths = false;
    var atLeastOneChecked_peri = false;

    e.preventDefault();

    var inputs = $('#params-form input[type=checkbox]').toArray();
    var inputs_radio = $('#params-form input[type=radio]').toArray();

    $.each(inputs, function(index, value) {
        if ($(value).prop("checked") == false) {
            $(value).parent().find("label").css('color', 'red');
        } else if ($(value).attr('name') == "country[]") {
            atLeastOneChecked = true;
        } else if ($(value).attr('name') == "var[]") {
            atLeastOneChecked_var = true;
        } else if ($(value).attr('name') == "dates[]") {
            atLeastOneChecked_per = true;
        } else if ($(value).attr('name') == "units[]") {
            atLeastOneChecked_un = true;
        } else if ($(value).attr('name') == "refs[]") {
            atLeastOneChecked_ref = true;
        } else if ($(value).attr('name') == "fits[]") {
            atLeastOneChecked_aju = true;
        } else if ($(value).attr('name') == "emfayears[]") {
            atLeastOneChecked_years = true;
        } else if ($(value).attr('name') == "mouths[]") {
            atLeastOneChecked_mouths = true;
        } else if ($(value).attr('name') == "peri[]") {
            atLeastOneChecked_peri = true;
        }
    });

    $.each(inputs_radio, function(index, value) {
        if ($(value).prop("checked") == false) {
            $(value).parent().find("label").css('color', 'red');
        } else if ($(value).attr('name') == "country[]") {
            atLeastOneChecked = true;
        } else if ($(value).attr('name') == "var[]") {
            atLeastOneChecked_var = true;
        } else if ($(value).attr('name') == "dates[]") {
            atLeastOneChecked_per = true;
        } else if ($(value).attr('name') == "units[]") {
            atLeastOneChecked_un = true;
        } else if ($(value).attr('name') == "refs[]") {
            atLeastOneChecked_ref = true;
        } else if ($(value).attr('name') == "fits[]") {
            atLeastOneChecked_aju = true;
        }
    });

    //emfa
    if ($('#send').hasClass("emfa")) {
        var page_target = $('#send').data("emfa");
        var activepage = $('#send').data("active");
        if (atLeastOneChecked) {
            $("input:radio[name*='country[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        if (atLeastOneChecked_var) {
            $("input:radio[name*='var[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        if (atLeastOneChecked_years) {
            $("input:checkbox[name*='emfayears[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        if (atLeastOneChecked_mouths) {
            $("input:checkbox[name*='mouths[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        if (atLeastOneChecked_peri) {
            $("input:checkbox[name*='peri[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        //here
        if (atLeastOneChecked && atLeastOneChecked_var && atLeastOneChecked_years && atLeastOneChecked_mouths || atLeastOneChecked_peri) {

            var vars = [];
            $("input[name='var[]']:checked").each(function(i, e) {
                vars.push($(this).val());
            });

            var countries = [];
            $("input[name='country[]']:checked").each(function(i, e) {
                countries.push($(this).val());
            });

            var emfaYears = [];
            $("input[name='emfayears[]']:checked").each(function(i, e) {
                emfaYears.push($(this).val());
            });

            var emfaMouths = [];
            $("input[name='mouths[]']:checked").each(function(i, e) {
                emfaMouths.push($(this).val());
            });

            var peris = [];
            $("input[name='peri[]']:checked").each(function(i, e) {
                peris.push($(this).val());
            });

            var years_final = emfaYears.join().replace(/,/g, '-');
            var mouths_final = emfaMouths.join().replace(/,/g, '-');
            $('.loader_years_load').fadeIn();
            window.location.href = page_target + "?country=" + countries[0] + "&idChart=" + vars[0] + "&years=" + years_final + "&mouths=" + mouths_final + "&peris=" + peris.join().replace(/,/g, '-') + "&active=" + activepage;
        }
    } else if ($('#send').hasClass("esea")) {
        if ($('#send').hasClass("esea-test")) {

            var countries = [];
            $("input[name='country[]']:checked").each(function(i, e) {
                countries.push($(this).val());
            });

            var first_year = $('#extra-year-first').val();
            var page_target = $('#send').data("restpage");
            var active = $('#send').data("active");
            var subject = $('#send').data("subject");
            var son = $('#parameters h2').text();
            var chartid = $('#send').data("chartid");
            var epID = $('#send').data("epid");
            console.log("here");

            var trimestre = $("input[name='piitri']:checked").val();

            window.location.href = page_target + "?country=" + countries[0] + "&active=" + active + "&son=" + son + "&finaldates=" + first_year + '/' + trimestre + "&subject=" + subject + "&chartid=" + chartid + "&epID=" + epID;



        }
        // if (atLeastOneChecked_years) {
        //   $("input:checkbox[name*='emfayears[]']").each(function() {
        //     $(this).parent().find('label').css('color','#53575c');
        //   });
        // }
        // if (atLeastOneChecked_mouths) {
        //   $("input:checkbox[name*='mouths[]']").each(function() {
        //     $(this).parent().find('label').css('color','#53575c');
        //   });
        // }
        // if (atLeastOneChecked_peri) {
        //   $("input:checkbox[name*='peri[]']").each(function() {
        //     $(this).parent().find('label').css('color','#53575c');
        //   });
        // }

        if (atLeastOneChecked) {
            $("input:radio[name*='country[]']").each(function() {
                $(this).parent().find('label').css('color', '#53575c');
            });
        }
        atLeastOneChecked_per = false;

        var first_year = $('#extra-year-first').val();
        var last_year = $('#extra-year-last').val();

        var first_per = $('#extra-per-first').val();
        var last_per = $('#extra-per-last').val();


        var firstString = "";
        var secondString = "";
        var thirdString = "";
        var finalString = "";

        console.log($('#extra-per-last').data('mouth'));
        if ($('#extra-per-last').data('mouth') == undefined) {
            // TRIMESTRES (I, II, III, IV) - Convertir a formato dd-mm-yyyy/dd-mm-yyyy
            // Trimestre I = Enero-Marzo, II = Abril-Junio, III = Julio-Sept, IV = Oct-Dic
            var trimestreMap = {
                1: { inicio: '01-01', fin: '31-03' },
                2: { inicio: '01-04', fin: '30-06' },
                3: { inicio: '01-07', fin: '30-09' },
                4: { inicio: '01-10', fin: '31-12' }
            };
            
            if (parseInt(first_year) == parseInt(last_year)) {
                // Mismo año: desde inicio del primer trimestre hasta fin del último trimestre
                var fechaInicio = `${trimestreMap[first_per].inicio}-${first_year}`;
                var fechaFin = `${trimestreMap[last_per].fin}-${first_year}`;
                finalString = `${fechaInicio}/${fechaFin}`;
            } else {
                // Años diferentes: desde inicio del primer trimestre del primer año hasta fin del último trimestre del último año
                var fechaInicio = `${trimestreMap[first_per].inicio}-${first_year}`;
                var fechaFin = `${trimestreMap[last_per].fin}-${last_year}`;
                finalString = `${fechaInicio}/${fechaFin}`;
            }
        } else {
            // FORMATO API v2: dd-mm-yyyy/dd-mm-yyyy (fechaInicio/fechaFin)
            // Construir fechas en formato correcto
            if (parseInt(first_year) == parseInt(last_year)) {
                // Mismo año: usar primer día del primer mes y último día del último mes
                var firstMonth = parseInt(first_per).toString().padStart(2, '0');
                var lastMonth = parseInt(last_per).toString().padStart(2, '0');
                var lastDay = new Date(parseInt(first_year), parseInt(last_per), 0).getDate(); // Último día del mes
                
                finalString = `01-${firstMonth}-${first_year}/${lastDay}-${lastMonth}-${first_year}`;
            } else {
                // Años diferentes: desde primer día del primer mes del primer año hasta último día del último mes del último año
                var firstMonth = parseInt(first_per).toString().padStart(2, '0');
                var lastMonth = parseInt(last_per).toString().padStart(2, '0');
                var lastDay = new Date(parseInt(last_year), parseInt(last_per), 0).getDate();
                
                finalString = `01-${firstMonth}-${first_year}/${lastDay}-${lastMonth}-${last_year}`;
            }
        }
        console.log(finalString);

        // for (var i = parseInt(first_year); i <= parseInt(last_year); i++) {
        //   firstString = firstString + i + "-";
        // }

        // for (var x = parseInt(first_per); x <= parseInt(last_per); x++) {
        //   secondString = secondString + x + "-";
        // }
        // if($('#extra-per-last').data('mouth') == undefined) {

        //   var s0 = secondString.replace(1,"I");
        //   var st1 = s0.replace(2,"II");
        //   var s2 = st1.replace(3,"III");
        //   var s3 = s2.replace(4,"IV");
        //   finalString = firstString + "/" + s3;
        // }else {
        //   finalString = firstString + "/" + secondString;
        // }

        // console.log(finalString);

        if (finalString != "") {
            atLeastOneChecked_per = true;
        }

        if (atLeastOneChecked && atLeastOneChecked_per) {
            // atLeastOneChecked_years && atLeastOneChecked_mouths || atLeastOneChecked_peri

            var countries = [];
            $("input[name='country[]']:checked").each(function(i, e) {
                countries.push($(this).val());
            });

            // var emfaYears = [];
            // $("input[name='emfayears[]']:checked" ).each(function(i, e) {
            //     emfaYears.push($(this).val());
            // });

            // var emfaMouths = [];
            // $("input[name='mouths[]']:checked" ).each(function(i, e) {
            //     emfaMouths.push($(this).val());
            // });

            // var peris = [];
            // $("input[name='peri[]']:checked" ).each(function(i, e) {
            //     peris.push($(this).val());
            // });

            var finaldates = finalString;
            var page_target = $('#send').data("restpage");
            var active = $('#send').data("active");
            var subject = $('#send').data("subject");
            var son = $('#parameters h2').text();
            var chartid = $('#send').data("chartid");
            var epID = $('#send').data("epid");
            window.location.href = page_target + "?country=" + countries[0] + "&active=" + active + "&son=" + son + "&finaldates=" + finaldates + "&subject=" + subject + "&chartid=" + chartid + "&epID=" + epID;
        }
    } else {
        check(atLeastOneChecked, atLeastOneChecked_var, atLeastOneChecked_per, atLeastOneChecked_un, atLeastOneChecked_ref, atLeastOneChecked_aju);
    }
});

function check(atLeastOneChecked, atLeastOneChecked_var, atLeastOneChecked_per, atLeastOneChecked_un, atLeastOneChecked_ref, atLeastOneChecked_aju) {
    if (atLeastOneChecked) {
        $("input:checkbox[name*='country[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
        });
    }
    if (atLeastOneChecked_var) {
        $("input:checkbox[name*='var[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
        });
    }


    var first_year = $('#extra-year-first').val();
    var first_mouth = $('#extra-mouth-first').val();
    var last_year = $('#extra-year-last').val();
    var last_mouth = $('#extra-mouth-last').val();
    var first_per = $('#extra-per-first').val();
    var last_per = $('#extra-per-last').val();
    var perID = $("#per0").val();
    // Obtén la pestaña activa
var activeTab = document.querySelector('#pills-tab1 .nav-link.active');

var range = false;

// Verifica si la pestaña activa es "Por Rango"
if (activeTab && activeTab.id === 'IPC-more-tab2') {
    // Verifica las condiciones para el rango
    if (first_year != "" && first_year != null && first_mouth != "" && last_year != "" && last_mouth != "" || 
        first_year != "" && last_year != "" && first_per != "" && last_per != "" || 
        first_year != "" && last_year != "" && perID == "A") {
        range = true;
    }
} else {
    // Si la pestaña activa no es "Por Rango", asumimos que es "Por Fechas"
    range = false;
}
    if (atLeastOneChecked_per) {
        $("input:checkbox[name*='dates[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
            atLeastOneChecked_per = true;
        });
    }

    if (range) {
        var perID = $("#per0").val();
        console.log(perID);
        if (perID == "M") {
            var firstYear = parseInt($('#extra-year-first').val());
            var firstMonth = parseInt($('#extra-mouth-first').val()) || 0; 
            var lastYear = parseInt($('#extra-year-last').val());
            var lastMonth = parseInt($('#extra-mouth-last').val()) || 0;
            
            //var first_year = $('#extra-year-first').val();
            //var first_mouth = $('#extra-mouth-first').val();
            //var last_year = $('#extra-year-last').val();
            //var last_mouth = $('#extra-mouth-last').val();
            
            var firstString = "";
            var secondString = "";
            var thirdString = "";
            if (firstYear > lastYear || (firstYear === lastYear && firstMonth > lastMonth)) {

                $('.js-msg p').removeClass('d-none');
            } else {
                if (parseInt(first_year) == parseInt(last_year)) {
                    finalString = "";
                    for (var i = parseInt(first_mouth); i <= parseInt(last_mouth); i++) {
                        finalString = finalString + parseInt(first_year) + i + "-";
                    }
                    atLeastOneChecked_per = true;
                } else {
                    for (var i = parseInt(first_mouth); i <= 12; i++) {
                        firstString = firstString + parseInt(first_year) + i + "-";
                    }

                    for (var x = 1; x <= parseInt(last_mouth); x++) {
                        secondString = secondString + parseInt(last_year) + x + "-";
                    }

                    for (var y = parseInt(first_year) + 1; y <= parseInt(last_year) - 1; y++) {
                        for (var j = 1; j <= 12; j++) {
                            thirdString = thirdString + y.toString() + j.toString() + "-";
                        }
                    }
                    var finalString = firstString + thirdString + secondString;
                    console.log(finalString);
                    atLeastOneChecked_per = true;
                }
            }
        } else if (perID == "Q") {
            if (firstYear > lastYear || (firstYear === lastYear && firstMonth > lastMonth)) {

                $('.js-msg p').removeClass('d-none');
            } else {
                var first_year = $('#extra-year-first').val();
                var last_year = $('#extra-year-last').val();

                var first_per = $('#extra-per-first').val();
                var last_per = $('#extra-per-last').val();



                var firstString = "";
                var secondString = "";
                var thirdString = "";

                for (var i = parseInt(first_per); i <= 4; i++) {
                    if (i == 1) {
                        firstString = firstString + parseInt(first_year) + "I" + "-";
                    } else if (i == 2) {
                        firstString = firstString + parseInt(first_year) + "II" + "-";
                    } else if (i == 3) {
                        firstString = firstString + parseInt(first_year) + "III" + "-";
                    } else if (i == 4) {
                        firstString = firstString + parseInt(first_year) + "IV" + "-";
                    }

                }

                for (var x = 1; x <= parseInt(last_per); x++) {
                    if (x == 1) {
                        secondString = secondString + parseInt(last_year) + "I" + "-";
                    } else if (x == 2) {
                        secondString = secondString + parseInt(last_year) + "II" + "-";
                    } else if (x == 3) {
                        secondString = secondString + parseInt(last_year) + "III" + "-";
                    } else if (x == 4) {
                        secondString = secondString + parseInt(last_year) + "IV" + "-";
                    }
                }

                for (var y = parseInt(first_year) + 1; y <= parseInt(last_year) - 1; y++) {
                    for (var j = 1; j <= 4; j++) {

                        if (j == 1) {
                            thirdString = thirdString + y.toString() + "I" + "-";
                        } else if (j == 2) {
                            thirdString = thirdString + y.toString() + "II" + "-";
                        } else if (j == 3) {
                            thirdString = thirdString + y.toString() + "III" + "-";
                        } else if (j == 4) {
                            thirdString = thirdString + y.toString() + "IV" + "-";
                        }


                    }
                }

                var finalString = firstString + thirdString + secondString;
                console.log(finalString);
                atLeastOneChecked_per = true;
            }
        } else if (perID == "A") {
            if (firstYear > lastYear || (firstYear === lastYear && firstMonth > lastMonth)) {

                $('.js-msg p').removeClass('d-none');
            } else {
                var first_year = $('#extra-year-first').val();
                var last_year = $('#extra-year-last').val();
                var thirdString = "";
                for (var y = parseInt(first_year); y <= parseInt(last_year); y++) {
                    thirdString = thirdString + y.toString() + "XII" + "-";
                }
                var finalString = thirdString;
                console.log(finalString);
                atLeastOneChecked_per = true;
            }
        } else if (perID == "D") {
            var firstYear = parseInt($('#extra-year-first').val());
            var firstMonth = parseInt($('#extra-mouth-first').val()) || 0; 
            var lastYear = parseInt($('#extra-year-last').val());
            var lastMonth = parseInt($('#extra-mouth-last').val()) || 0;
            
            //var first_year = $('#extra-year-first').val();
            //var first_mouth = $('#extra-mouth-first').val();
            //var last_year = $('#extra-year-last').val();
            //var last_mouth = $('#extra-mouth-last').val();
            var first_day = "01"; // Día de inicio, puedes ajustarlo según tus necesidades
            var last_day = "28"; // Día de fin, puedes ajustarlo según tus necesidades
            var finalString = "";
            
            if (firstYear > lastYear || (firstYear === lastYear && firstMonth > lastMonth)) {

                $('.js-msg p').removeClass('d-none');
            } else {
                // Asegurarse de que el mes y el día tengan el formato correcto (dos dígitos)
                var formattedFirstMonth = parseInt(first_mouth).toString().padStart(2, '0');
                var formattedLastMonth = parseInt(last_mouth).toString().padStart(2, '0');
                var formattedFirstDay = first_day.padStart(2, '0');
                var formattedLastDay = last_day.padStart(2, '0');
            
                // Formatear las fechas de inicio y fin
                var fechaInicio = `${formattedFirstDay}-${formattedFirstMonth}-${first_year}`;
                var fechaFin = `${formattedLastDay}-${formattedLastMonth}-${last_year}`;
            
                // Generar la cadena final
                finalString = `${fechaInicio}/${fechaFin}`;
                
                console.log(finalString);
                atLeastOneChecked_per = true;
            }
            console.log("here");
        }
    }

    if (atLeastOneChecked_un) {
        $("input:checkbox[name*='units[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
        });
    }
    if (atLeastOneChecked_ref) {
        $("input:checkbox[name*='refs[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
        });
    }
    if (atLeastOneChecked_aju) {
        $("input:checkbox[name*='fits[]']").each(function() {
            $(this).parent().find('label').css('color', '#53575c');
        });
    }
    if (atLeastOneChecked && atLeastOneChecked_var && atLeastOneChecked_per && atLeastOneChecked_un && atLeastOneChecked_ref && atLeastOneChecked_aju) {
        var vars = [];
        $("input[name='var[]']:checked").each(function(i, e) {
            vars.push($(this).val());
        });
        var countries = [];
        $("input[name='country[]']:checked").each(function(i, e) {
            countries.push($(this).val());
        });
        var pers = [];
        $("input[name='per[]']:checked").each(function(i, e) {
            pers.push($(this).val());
        });
        var dates = [];
        $("input[name='dates[]']:checked").each(function(i, e) {
            dates.push($(this).val());
        });
        var units = [];
        $("input[name='units[]']:checked").each(function(i, e) {
            units.push($(this).val());
        });
        var refs = [];
        $("input[name='refs[]']:checked").each(function(i, e) {
            refs.push($(this).val());
        });
        var fits = [];
        $("input[name='fits[]']:checked").each(function(i, e) {
            fits.push($(this).val());
        });

        var all_vars = [];
        $("input[name='var[]']:checked").each(function(i, e) {
            all_vars.push($(this).data("varname"));
        });
        varsString = "";
        for (var i = 0; i < all_vars.length; i++) {
            if (i != 0) {
                varsString = varsString + "*" + all_vars[i];
            } else {
                varsString = all_vars[i];
            }
        }

        
        
        // Arreglo de IDs a verificar
        var idsAVerificar = [
            "54",
            "55",
            "56"
        ];
        
        
        // Verificar si alguna variable está en el arreglo de IDs
        var encontrado = false;
        
        for (var i = 0; i < vars.length; i++) {
            if (idsAVerificar.includes(vars[i])) {
                encontrado = true;
                break;
            }
        }
        
        // Si se encontró alguna coincidencia
        if (encontrado && !range) {
            console.log("Se encontró al menos una variable que está en el arreglo de IDs a verificar.");
            var dates_final = dates.join().replace(/,/g, '-');
            if (dates.length === 1) {
                fechaInicio = dates[0];
                fechaFin = dates[0];
            } else {
                // Ordenar las fechas cronológicamente
                dates.sort(function(a, b) {
                    return new Date(a) - new Date(b);
                });
        
                fechaInicio = dates[0];
                fechaFin = dates[dates.length - 1];
            }
            var dates_final = `${fechaInicio}/${fechaFin}`;
            
        } else {
            console.log("No se encontró ninguna variable en el arreglo de IDs a verificar.");
            var dates_final = dates.join().replace(/,/g, '-');
        }


        var subjectID = $('#send').data("subjectid");
        var rangedates = false;
        if (finalString != "" && finalString != undefined && !finalString.includes("NaN") && dates_final == "") {
            if ($('.js-current-son').data('son') == "Producto Interno Bruto anual") {
                if (countries.length == 2) {
                    if (countries.join().replace(/,/g, '-').includes("13") && countries.join().replace(/,/g, '-').includes("52")) {
                        vars[vars.indexOf('364')] = '371';
                        vars[vars.indexOf('365')] = '381';
                    } else if (countries.join().replace(/,/g, '-').includes("13") || countries.join().replace(/,/g, '-').includes("52")) {
                        if (vars.join().replace(/,/g, '-').includes("364")) {
                            vars.push("371");
                        }
                        if (vars.join().replace(/,/g, '-').includes("365")) {
                            vars.push("381");
                        }
                    }
                } else {
                    if (countries.join().replace(/,/g, '-').includes("13") || countries.join().replace(/,/g, '-').includes("52")) {
                        if (vars.join().replace(/,/g, '-').includes("364")) {
                            vars.push("371");
                        }
                        if (vars.join().replace(/,/g, '-').includes("365")) {
                            vars.push("381");
                        }
                    }
                }
            }
            var url = subjectID + '/' + fits.join().replace(/,/g, '-') + '/' + countries.join().replace(/,/g, '-') + '/' + vars.join().replace(/,/g, '-') + '/' + refs.join().replace(/,/g, '-') + '/' + units.join().replace(/,/g, '-') + '/' + pers.join().replace(/,/g, '-') + '/' + finalString;
            rangedates = true;
        } else {
            var url = subjectID + '/' + fits.join().replace(/,/g, '-') + '/' + countries.join().replace(/,/g, '-') + '/' + vars.join().replace(/,/g, '-') + '/' + refs.join().replace(/,/g, '-') + '/' + units.join().replace(/,/g, '-') + '/' + pers.join().replace(/,/g, '-') + '/' + dates_final;
        }
        var page_target = $('#send').data("restpage");
        var scid = $('.js-ids').data('scid');
        var cid = $('.js-ids').data('cid');
        var scsid = $('.js-ids1').parent().parent().find("li.active").find("a").data('scsid');
        var currentson = $('.js-current-son').data('son');
        var perID = $("#per0").val();

        $('.loader_years_load').fadeIn();
        console.log("here debug...");
        if ($('#cbox1').is(":checked")) {
            page_target = 'https://www.secmca.org/jsonpage/';
            window.location.href = page_target + "?parent=" + dat_cat + "&scid=" + scid + "&cid=" + cid + "&scsid=" + scsid + "&son=" + currentson + "&jsonview=true&url=" + url + "&all_vars=" + varsString;
        } else {
            window.location.href = page_target + "?parent=" + dat_cat + "&scid=" + scid + "&cid=" + cid + "&scsid=" + scsid + "&son=" + currentson + "&url=" + url + "&all_vars=" + varsString;
        }


        // if(perID == "38") {
        //     if(rangedates){
        //      if(countries.length < 3) {
        //        if(finalString.split("-").length <= 32) {
        //            $('.loader_years_load').fadeIn();  
        //            window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //          }else {
        //             $('.toolong').fadeIn(); 
        //             setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }else {
        //        if(vars.length < 15 && finalString.split("-").length <= 7) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }else {
        //      if(countries.length < 3) {
        //        if(dates_final.split("-").length <= 32) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }else {
        //        if(vars.length < 15 && dates_final.split("-").length <= 5) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }
        // }else if(perID == "36") {
        //    if(rangedates){
        //      if(countries.length == 1) {
        //        if(finalString.split("-").length <= 130) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }else {
        //        if(vars.length <= 15 && finalString.split("-").length <= 25) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }else {
        //      if(countries.length == 1) {
        //        if(dates_final.split("-").length <= 400) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }else {
        //        if(vars.length <= 15 && dates_final.split("-").length <= 73) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }
        // }else {
        //     if(rangedates){
        //      if(countries.length == 1) {
        //        if($('.js-current-son').text() == "Costa Rica, IMAE por actividades" || $('.js-current-son').text() == "El Salvador, IMAE por actividades" || $('.js-current-son').text() == "Guatemala, IMAE por actividades" || $('.js-current-son').text() == "Honduras, IMAE por actividades" || $('.js-current-son').text() == "Nicaragua, IMAE por actividades") {
        //          if(vars.length <= 49 && finalString.split("-").length <= 73) {
        //            $('.loader_years_load').fadeIn();  
        //            window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //          }else {
        //            $('.toolong').fadeIn(); 
        //          }
        //        }else {
        //          if(finalString.split("-").length <= 400) {
        //            $('.loader_years_load').fadeIn();  
        //            window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //          }else {
        //            $('.toolong').fadeIn(); 
        //          }
        //        }
        //      }else {
        //        if(vars.length <= 15 && finalString.split("-").length <= 73) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }else {
        //      if(countries.length == 1) {
        //        if($('.js-current-son').text() == "Costa Rica, IMAE por actividades" || $('.js-current-son').text() == "El Salvador, IMAE por actividades" || $('.js-current-son').text() == "Guatemala, IMAE por actividades" || $('.js-current-son').text() == "Honduras, IMAE por actividades" || $('.js-current-son').text() == "Nicaragua, IMAE por actividades") {
        //          if(vars.length <= 49 && dates_final.split("-").length <= 73) {
        //            $('.loader_years_load').fadeIn();  
        //            window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //          }else {
        //            $('.toolong').fadeIn(); 
        //          }
        //        }else {
        //          if(dates_final.split("-").length <= 400) {
        //            $('.loader_years_load').fadeIn();  
        //            window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //          }else {
        //            $('.toolong').fadeIn(); 
        //          }
        //        }
        //      }else {
        //        if(vars.length <= 53 && dates_final.split("-").length <= 73) {
        //          $('.loader_years_load').fadeIn();  
        //          window.location.href = page_target+"?parent="+dat_cat+"&scid="+scid+"&cid="+cid+"&scsid="+scsid+"&son="+currentson+"&url="+url+"&all_vars="+varsString;
        //        }else {
        //           $('.toolong').fadeIn(); 
        //           setTimeout(function(){ $('.toolong').fadeOut();  }, 3000); 
        //        }
        //      }
        //    }
        // }
    }
}

$(".graphic-blue-box").click(
    function() {
        $(this).addClass("graphic-blue-box-opening");
        $(this).toggleClass("graphic-blue-box-exp");
        $('.white-box').toggleClass("white-box-opening");
        $('.white-box').toggleClass("white-box-exp");
        console.log("hey");
    }
    // $('.boxx').css('overflow','visible');
    //  $(this).addClass("graphic-blue-box-opening");
    //  $(this).addClass("graphic-blue-box-exp");
    //    setTimeout(function(){
    //      $('.white-box').addClass("white-box-opening");
    //      setTimeout(function(){
    //         $('.white-box').addClass("white-box-exp");
    //       }, 500);
    //  }, 500);
);

// $( ".white-box" ).mouseleave(
//   function() {
//     $('.boxx').css('overflow','hidden');
//     $('.white-box').removeClass("white-box-exp");
//     $('.white-box').removeClass("white-box-opening");
//     $('.graphic-blue-box').removeClass("graphic-blue-box-opening");
//     $('.graphic-blue-box').removeClass("graphic-blue-box-exp");
//   }
// );


$("#js-downland ul li").click(function(e) {
    e.preventDefault();
    if ($(this).attr('id') == "txt") {
        $('.table-results').tableExport({
            type: 'txt',
            preventInjection: false
        });
    } else if ($(this).attr('id') == "csv") {
        $('.table-results').tableExport({
            type: 'csv',
            preventInjection: false
        });
    } else if ($(this).attr('id') == "xls2") {
       console.log("here");
       exportTableToExcelWithFormat('tabl','tableExport.xlsx');
    } else {
        $('.table-results').tableExport({
            type: 'excel',
            preventInjection: false
        });
    }
});


function exportTableToExcelWithFormat(tableId, filename = 'table.xlsx') {
    const table = document.getElementById(tableId);

    if (!table) {
        console.error(`No se encontró la tabla con el ID: ${tableId}`);
        return;
    }

    // Crear manualmente el array de datos y las combinaciones
    const worksheetData = [];
    const merges = [];
    const rows = Array.from(table.rows);

    rows.forEach((row, rowIndex) => {
        const rowData = [];
        let colOffset = 0; // Controla el desplazamiento de columnas debido a celdas combinadas

        Array.from(row.cells).forEach((cell, cellIndex) => {
            // Ajusta el índice de la columna si hay celdas combinadas previas
            const effectiveIndex = cellIndex + colOffset;

            // Rellena celdas vacías en caso necesario
            while (rowData.length < effectiveIndex) {
                rowData.push(null);
            }

            // Añade el contenido de la celda
            rowData.push(cell.innerText);

            // Detectar combinaciones (colspan y rowspan)
            const colSpan = cell.colSpan || 1;
            const rowSpan = cell.rowSpan || 1;

            if (colSpan > 1 || rowSpan > 1) {
                const startCell = { r: rowIndex, c: effectiveIndex };
                const endCell = { r: rowIndex + rowSpan - 1, c: effectiveIndex + colSpan - 1 };

                // Validar que las coordenadas no se solapen y sean válidas
                if (
                    endCell.r < rows.length &&
                    endCell.c < rowData.length + colSpan &&
                    !merges.some(
                        merge =>
                            (merge.s.r <= startCell.r && merge.e.r >= endCell.r) &&
                            (merge.s.c <= startCell.c && merge.e.c >= endCell.c)
                    )
                ) {
                    merges.push({ s: startCell, e: endCell });
                }
            }

            // Aumenta el desplazamiento de columnas si hay un colspan
            colOffset += colSpan - 1;
        });

        worksheetData.push(rowData);
    });

    // Crear la hoja de cálculo manualmente
    const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

    // Aplicar las combinaciones válidas
    worksheet['!merges'] = merges;

    // Crear y guardar el archivo Excel
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, filename);
}


$(".js-hover-dropdown ul li").hover(function() {
    $(this).toggleClass("active");
});

$('.js-share-box-wrapper').mouseenter(function() {
    $('.share-box').css('display', 'block');
    $('.js-arrowToex').addClass("ex");
    $('.js-arrowToex').text("x");
});

$('.js-arrowToex').click(function() {
    $('.share-box').css('display', 'none');
    $('.js-arrowToex').removeClass("ex");
    $('.js-arrowToex').text("");
});

$('.share-box').mouseleave(function() {
    $(this).css('display', 'none');
    $('.share-box').css('display', 'none');
    $('.js-arrowToex').text("");
    $('.js-arrowToex').removeClass("ex");
});


// var el = $('.table-results tbody tr').first();
// $('.table-results tbody tr').first().remove();

$(document).ready(function() {
    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };
    var country = getUrlParameter('country');
    var curryear = getUrlParameter('finaldates');
    console.log(country);
    if (curryeararr) {
        var curryeararr = curryear.split('/');
        $('.js-curryear').text(curryeararr[0]);
    }



    if (country == 3) {
        $('.js-country').text("Costa Rica");
    } else if (country == 13) {
        $('.js-country').text("El Salvador");
    } else if (country == 50) {
        $('.js-country').text("Guatemala");
    } else if (country == 17) {
        $('.js-country').text("Honduras");
    } else if (country == 4) {
        $('.js-country').text("Nicaragua");
    } else if (country == 52) {
        $('.js-country').text("Republica Dominicana");
    } else if (country == 161) {
        $('.js-country').text("Panamá");
    } else if (country == 95) {
        $('.js-country').text("Centroamérica");
    } else if (country == 56) {
        $('.js-country').text("CentroAmerica y Republica Dominicana");
    } else if (country == 78) {
        $('.js-country').text("CentroAmerica, Panamá y Republica Dominicana");
    } else if (country == 2014) {
        $('.js-country').text("Belice");
    }


    var coudata = $('.js-country').data('country');
    console.log("degug");
    if (coudata != "") {
        if (coudata == 3) {
            $('.js-country').text("Costa Rica");
        } else if (coudata == 13) {
            $('.js-country').text("El Salvador");
        } else if (coudata == 50) {
            $('.js-country').text("Guatemala");
        } else if (coudata == 17) {
            $('.js-country').text("Honduras");
        } else if (coudata == 4) {
            $('.js-country').text("Nicaragua");
        } else if (coudata == 52) {
            $('.js-country').text("Republica Dominicana");
        } else if (coudata == 161) {
            $('.js-country').text("Panamá");
        } else if (coudata == 95) {
            $('.js-country').text("Centroamérica");
        } else if (coudata == 56) {
            $('.js-country').text("CentroAmerica y Republica Dominicana");
        } else if (coudata == 78) {
            $('.js-country').text("CentroAmerica, Panamá y Republica Dominicana");
        } else if (country == 2014) {
            $('.js-country').text("Belice");
        }
    }
    // var desc = $(".date");
    // var temp = [];
    // var uniqueNames = [];
    // $.each(desc, function( index, value ) {
    //   var res = value.innerText.split(";");
    //   lastitem = value;

    //   $.each(res, function(i, el){
    //       if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
    //       value.innerText = el;
    //   });
    // });

});
//   var res = value.innerText.split(";");
//   if(res.length == 1){
//     var firsttime = false;
//   }else {
//     firsttime = true;
//   }
//   var lastword = res[0];
//   for (var i = 0; i < res.length; i++) {
//    if(res[i] == lastword){
//       res[i] = " ";
//     }
//     var finalres = res; 
//   }
//   value.innerText = finalres;
//value.innerText = res.pop();

//     $('.table-results').dynatable({
//       features: {
//       paginate: false,
//       sort: false,
//       pushState: false,
//       search: true,
//       recordCount: true,
//       perPageSelect: true
//     },
//     inputs: {
//     paginationPrev: 'Anterior',
//     paginationNext: 'Siguiente',
//     perPageText: 'Mostrar: ',
//     recordCountText: 'Showing of'
//   },
//   params: {
//   records: 'registros',
// },
//   });
// $('.js-hidden-before').css('display','none');
// $('.table-results thead').append(el);
// Datepicker.locales.es = {
//   days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"],
//   daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"],
//   daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"],
//   months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
//   monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
//   today: "Hoy",
//   monthsTitle: "Meses",
//   clear: "Borrar",
//   weekStart: 1,
//   format: "dd/mm/yyyy"
// };
//   const elem = document.getElementById('range');
//   const dateRangePicker = new DateRangePicker(elem, {
//        language: 'es',
//         showDaysOfWeek: true,

//   });


function copyLink() {
    var copyText = document.getElementById("myInput");
    copyText.select();
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy");
    alert("Copiado con exito! : " + copyText.value);
}

$('.js-cuadro').click(function() {
    if ($(this).find("a").hasClass('active-mode')) {
        $(this).find("a").removeClass('active-mode');
        $(this).find("a").addClass("noactive-mode");
        $('.js-chart').find("a").addClass("active-mode");
        $('.js-chart').find("a").removeClass("noactive-mode");
    } else {
        $(this).find("a").addClass('active-mode');
        $(this).find("a").removeClass("noactive-mode");
        $('.js-chart').find("a").removeClass("active-mode");
        $('.js-chart').find("a").addClass("noactive-mode");
    }
});

$('.js-chart').click(function() {
    if ($(this).find("a").hasClass('active-mode')) {
        $(this).find("a").removeClass('active-mode');
        $(this).find("a").addClass("noactive-mode");
        $('.js-cuadro').find("a").addClass("active-mode");
        $('.js-cuadro').find("a").removeClass("noactive-mode");
    } else {
        $(this).find("a").addClass('active-mode');
        $(this).find("a").removeClass("noactive-mode");
        $('.js-cuadro').find("a").removeClass("active-mode");
        $('.js-cuadro').find("a").addClass("noactive-mode");
    }
});


$('.radio-variables').click(function() {
    var vars = [];
    var countries = [];
    var req_vars;
    var req_country;
    $("input[name='var[]']:checked").each(function(i, e) {
        vars.push($(this).val());
    });
    $("input[name='country[]']:checked").each(function(i, e) {
        countries.push($(this).val());
    });
    if (vars != null) {
        req_vars = vars.join().replace(/,/g, '-');
    }
    if (countries != null) {
        req_country = countries.join().replace(/,/g, '-');
    }
    $('.js-custom-years').empty();
    $('.js-custom-years1').css('display', 'none');
    if (req_vars.length > 0 && req_country.length > 0) {
        if ($('.js-current-son').data('son') == "Producto Interno Bruto anual") {
            var salvador = "13";
            var dominicana = "52";

            if (req_country.includes(salvador) || req_country.includes(dominicana)) {
                if (req_vars.includes('364')) {
                    req_vars += "-371";
                }
                if (req_vars.includes('365')) {
                    req_vars += "-381";
                }
            }
        }
        $.ajax({
    url: ajax_object.ajaxurl,
    type: 'POST',
    data: {
        action: 'scm_get_url',
        'vars': req_vars,
        'countries': req_country
    },
    beforeSend: function() {
        $('.loader_years').show();
    },
    complete: function() {
        $('.loader_years').hide();
    },
    success: function(data) {
    var response = decodeEntities(data);
    if (response != "No se encontraron datos" && !response.includes("HTTP Status 404")) {
        $('.js-custom-years1').css('display', 'block');
        var obj = JSON.parse(response);
        var fragment = document.createDocumentFragment();
        var extraFragment = document.createDocumentFragment();
        var addedYears = new Set(); // Usamos un Set para almacenar los años únicos
        
        $('.js-custom-years').empty();
        $('.extra_years').empty();
        $('.extra_years').append('<option value="">-- Selecciona un año --</option>');
        
        console.log("llegaron las fechas!");
        
        $.each(obj, function (index, value) {
    index = index + 1;
    var perID = $("#per0").val();
    var req_vars_array = [54, 55, 56]; // Lista de valores a verificar

    if (perID == "A") {
        if (value["dscPeriodo"] == "XII" || "Periodo Anual") {
            console.log("debug 1");
            var div = $("<div class='custom-control custom-checkbox'>" +
                "<input type='checkbox' class='custom-control-input radio-aju' id='date" + index + 
                "' name='dates[]' value=" + value["datoConsulta"] + ">" +
                "<label class='custom-control-label' for='date" + index + "'>" + value["anno"] + 
                "</label></div>")[0];
            fragment.appendChild(div);

            if (!addedYears.has(value["anno"])) {
                extraFragment.appendChild($('<option value="' + value["anno"] + '">' + value["anno"] + '</option>')[0]);
                addedYears.add(value["anno"]);
            }
        }
    } else {
        // Verificamos si req_vars está en req_vars_array
        if (req_vars_array.includes(parseInt(req_vars))) {
            // Solo cargamos `extraFragment`
            if (!addedYears.has(value["anno"])) {
                extraFragment.appendChild($('<option value="' + value["anno"] + '">' + value["anno"] + '</option>')[0]);
                addedYears.add(value["anno"]);
            }
        } else {
            // Cargamos tanto `fragment` como `extraFragment`
            var div = $("<div class='custom-control custom-checkbox'>" +
                "<input type='checkbox' class='custom-control-input radio-aju' id='date" + index + 
                "' name='dates[]' value=" + value["datoConsulta"] + ">" +
                "<label class='custom-control-label' for='date" + index + "'>" + value["anno"] + 
                "-" + value["dscPeriodo"] + "</label></div>")[0];
            fragment.appendChild(div);

            if (!addedYears.has(value["anno"])) {
                extraFragment.appendChild($('<option value="' + value["anno"] + '">' + value["anno"] + '</option>')[0]);
                addedYears.add(value["anno"]);
            }
        }
    }
});


        $('.js-custom-years').append(fragment);
        $('.extra_years').append(extraFragment);

        var $finalyear = $('#IPC-more-tab2').data("limyear");
        if ($finalyear == "") {
            $finalyear = new Date().getFullYear();
        }

        var $contains = parseInt($finalyear) - 5;
        $('#extra-year-last>option:last').attr('selected', true);

        if ($("#extra-year-first option:contains(" + $contains + ")").length > 0) {
            $("#extra-year-first option:contains(" + $contains + ")").attr('selected', 'selected');
        } else {
            $("#extra-year-first option:contains(" + $finalyear + ")").attr('selected', 'selected');
        }

        $('#extra-per-first>option:eq(1)').attr('selected', true);
        $('#extra-per-last>option:eq(4)').attr('selected', true);

        var perID = $("#per0").val();

        if (perID == "Q") {
            $('#extra-mouth-first').css('display', 'none');
            $('#extra-mouth-last').css('display', 'none');
        } else if (perID == "A") {
            $('#extra-mouth-first').css('display', 'none');
            $('#extra-mouth-last').css('display', 'none');
            $('#extra-per-first').css('display', 'none');
            $('#extra-per-last').css('display', 'none');
        } else {
            $('#extra-per-first').css('display', 'none');
            $('#extra-per-last').css('display', 'none');
        }
        $('.js-custom-years1').fadeIn();

    } else {
        $('.js-custom-years').text(response);
    }
}

});

    }
});

$('.js-all-ajax').click(function() {
    var vars = [];
    var countries = [];
    var req_vars;
    var req_country;
    $("input[name='var[]']:checked").each(function(i, e) {
        vars.push($(this).val());
    });
    $("input[name='country[]']:checked").each(function(i, e) {
        countries.push($(this).val());
    });
    if (vars != null) {
        req_vars = vars.join().replace(/,/g, '-');
    }
    if (countries != null) {
        req_country = countries.join().replace(/,/g, '-');
    }
    $('.js-custom-years').empty();

    if ($('.js-current-son').data('son') == "Producto Interno Bruto anual") {
        var salvador = "13";
        var dominicana = "52";

        if (req_country.includes(salvador) || req_country.includes(dominicana)) {
            if (req_vars.includes('364')) {
                req_vars += "-371";
            }
            if (req_vars.includes('365')) {
                req_vars += "-381";
            }
        }
    }

    $.ajax({
    url: ajax_object.ajaxurl,
    type: 'POST',
    data: {
        action: 'scm_get_url',
        'vars': req_vars,
        'countries': req_country
    },
    beforeSend: function() {
        $('.loader_years').show();
    },
    complete: function() {
        $('.loader_years').hide();
    },
    success: function(data) {
        var response = decodeEntities(data);
        if (response != "No se encontraron datos" && response.indexOf("HTTP Status 404") === -1) {
            var obj = JSON.parse(response);
            
            // Usar DocumentFragment para optimizar las inserciones al DOM
            var fragment = document.createDocumentFragment();

            // Limpiar el contenedor antes de agregar nuevos elementos
            $('.js-custom-years').empty();

            $.each(obj, function(index, value) {
                index = index + 1;
                var perID = $("#per0").val();
                var checkboxHtml = "";

                if (perID == "A" && (value["dscPeriodo"] === "XII" || value["dscPeriodo"] === "Periodo Anual")) {
                    console.log("debug 3");
                    checkboxHtml = "<div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input radio-aju' id='date" + index + "' name='dates[]' value='" + value["datoConsulta"] + "'><label class='custom-control-label' for='date" + index + "'>" + value["anno"] + "</label></div>";
                } else {
                    console.log("debug 4");
                    checkboxHtml = "<div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input radio-aju' id='date" + index + "' name='dates[]' value='" + value["datoConsulta"] + "'><label class='custom-control-label' for='date" + index + "'>" + value["anno"] + "-" + value["dscPeriodo"] + "</label></div>";
                }

                // Convertir string HTML en elementos DOM y agregarlos al fragment
                var tempDiv = document.createElement('div');
                tempDiv.innerHTML = checkboxHtml;
                fragment.appendChild(tempDiv.firstChild);
            });

            // Insertar todos los elementos al DOM en una sola operación
            $('.js-custom-years').append(fragment);

            // Manejar los años adicionales
            $finalyear = $('#IPC-more-tab2').data("limyear") || new Date().getFullYear();
            var extraFragment = document.createDocumentFragment();

            // Limpiar opciones actuales
            $('.extra_years').empty();
            $('.extra_years').append('<option value="">-- Selecciona un año --</option>');

            for (var i = obj[Object.keys(obj)[0]].anno; i <= parseInt(obj[Object.keys(obj)[Object.keys(obj).length - 1]].anno); i++) {
                var option = document.createElement('option');
                option.value = i;
                option.text = i;
                extraFragment.appendChild(option);
            }

            $('.extra_years').append(extraFragment);

            // Selección de años
            var $contains = parseInt($finalyear) - 5;
            $('#extra-year-last>option:last').attr('selected', true);

            if ($("#extra-year-first option:contains(" + $contains + ")").length > 0) {
                $("#extra-year-first option:contains(" + $contains + ")").attr('selected', 'selected');
            } else {
                $("#extra-year-first option:contains(" + $finalyear + ")").attr('selected', 'selected');
            }

            // Mostrar y ocultar secciones según el periodo
            var perID = $("#per0").val();
            if (perID == "Q" || perID == "A") {
                $('#extra-per-first>option:eq(1)').attr('selected', true);
        $('#extra-per-last>option:eq(4)').attr('selected', true);
                $('#extra-mouth-first, #extra-mouth-last').css('display', 'none');
                if (perID == "A") {
                    $('#extra-per-first, #extra-per-last').css('display', 'none');
                }
            } else {
                $('#extra-per-first, #extra-per-last').css('display', 'none');
            }

            $('.js-custom-years1').fadeIn();

        } else {
            $('.js-custom-years').text(response);
        }
    }
});

});


$(document).ready(function() {
    // //search absolute
    // $('.table-wrapper').find("div").css("position","absolute");

    // $('.vars-label').each(function( index ) {
    //   var finalte = $( this ).text().split("-")[1];
    //   $( this ).text(finalte);
    // });

    $("#js-search-vars").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $(".results-search .custom-control").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });


    $("#pills-chart-tab").on("click", function() {
        setTimeout(function() {
            var ticks = mychart.scales["y-axis-0"].ticks;
            var maxheight = mychart.scales["y-axis-0"].maxHeight;
            maxheight = maxheight + 19;
            $('.js-ticks').css('height', maxheight);
            // $('.js-ticks').css('left',left);
            if ($('.ticks').children().length == 0) {
                $.each(ticks, function(key, value) {
                    console.log(key + ": " + value);
                    $('.js-ticks').append("<div class='tick-s'><span>" + value + "</span></div>");
                });
            }
        }, 500);
    });
    $('.js-kabel').on("click", function() {
        $('.ticks').empty();
        var ticks = mychart.scales["y-axis-0"].ticks;
        var maxheight = mychart.scales["y-axis-0"].maxHeight;
        maxheight = maxheight + 19;
        $('.js-ticks').css('height', maxheight);
        if ($('.ticks').children().length == 0) {
            $.each(ticks, function(key, value) {
                // console.log( key + ": " + value );
                $('.js-ticks').append("<div class='tick-s'><span>" + value + "</span></div>");
            });
        }
    });

    $('.js-color-bar').on('change', function() {
        var colorval = $(this).val();
        var undex = $(this).parent().find('span').attr('id').split("-");
        if (mychart.config.type == "bar") {
            mychart.data.datasets[undex[1]].backgroundColor = colorval;
            mychart.data.datasets[undex[1]].borderColor = colorval;
            mychart.update();
        } else {
            mychart.data.datasets[undex[1]].borderColor = colorval;
            mychart.update();
        }
    });

    var vars = [];
    var countries = [];
    var req_vars;
    var req_country;
    $("input[name='var[]']:checked").each(function(i, e) {
        vars.push($(this).val());
    });
    $("input[name='country[]']:checked").each(function(i, e) {
        countries.push($(this).val());
    });
    if (vars != null) {
        req_vars = vars.join().replace(/,/g, '-');
    }
    if (countries != null) {
        req_country = countries.join().replace(/,/g, '-');
    }
    if (vars.length > 0 && req_country.length > 0) {
        if ($('.js-current-son').data('son') == "Producto Interno Bruto anual") {
            var salvador = "13";
            var dominicana = "52";

            if (req_country.includes(salvador) || req_country.includes(dominicana)) {
                if (req_vars.includes('364')) {
                    req_vars += "-371";
                }
                if (req_vars.includes('365')) {
                    req_vars += "-381";
                }
            }
        }

        $.ajax({
            url: ajax_object.ajaxurl,
            type: 'POST',
            data: {
                action: 'scm_get_url',
                'vars': req_vars,
                'countries': req_country
            },
            beforeSend: function() {
                $('.loader_years').show();
            },
            complete: function() {
                $('.loader_years').hide();
            },
            success: function(data) {
                var response = decodeEntities(data);
                if (response != "No se encontraron datos") {
                    var obj = JSON.parse(response);
                    $('.js-custom-years').empty();
                    $.each(obj, function(index, value) {
                        index = index + 1;
                        var perID = $("#per0").val();
                        if (perID == "A") {
                            if (value["dscPeriodo"] == "XII" && "Periodo Anual") {
                                console.log("debug 5");
                                $('.js-custom-years').append(
                                    $("<div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input radio-aju' id='date" + index + "' name='dates[]' value=" + value["datoConsulta"] + "><label class='custom-control-label' for='date" + index + "'>" + value["anno"] + "</label></div>")
                                );
                            }
                        } else {
                            console.log("debug 6");
                            $('.js-custom-years').append(
                                $("<div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input radio-aju' id='date" + index + "' name='dates[]' value=" + value["datoConsulta"] + "><label class='custom-control-label' for='date" + index + "'>" + value["anno"] + "-" + value["dscPeriodo"] + "</label></div>")
                            );
                        }
                    });


                    $finalyear = $('#IPC-more-tab2').data("limyear");
                    if ($finalyear == "") {
                        $finalyear = new Date().getFullYear();
                    }
                    $('.extra_years').empty();
                    $('.extra_years').append('<option value="">-- Selecciona un año --</option>');
                    for (var i = obj[Object.keys(obj)[0]].anno; i <= parseInt(obj[Object.keys(obj)[Object.keys(obj).length - 1]].anno); i++) {
                        console.log(obj[Object.keys(obj)[0]]['dscPeriodo']);
                        if (obj[Object.keys(obj)[0]]['dscPeriodo'] == "XII" || "Periodo Anual") {
                            // $('.extra_years').append('<option value="'+i+'">'+i+'</option>');   
                        }
                    }

                    Object.keys(obj).forEach(function(key) {

                        if (obj[key]["dscPeriodo"] == "XII") {
                            $('.extra_years').append('<option value="' + obj[key]["anno"] + '">' + obj[key]["anno"] + '</option>');
                        }

                    });
                 var $contains = parseInt($finalyear) - 5;
$('#extra-year-last>option:last').attr('selected', true);

// Verificar si $contains existe en #extra-year-first
if ($("#extra-year-first option:contains(" + $contains + ")").length > 0) {
    $("#extra-year-first option:contains(" + $contains + ")").attr('selected', 'selected');
} else {
    // Asignar el mismo año ($finalyear) si $contains no existe
    $("#extra-year-first option:contains(" + $finalyear + ")").attr('selected', 'selected');
}

                    // $('#extra-year-first>option:eq(26)').attr('selected', true);

                    $('#extra-per-first>option:eq(1)').attr('selected', true);
                    $('#extra-per-last>option:eq(4)').attr('selected', true);

                    var perID = $("#per0").val();

                    //trimestral
                    if (perID == "Q") {
                        $('#extra-mouth-first').css('display', 'none');
                        $('#extra-mouth-last').css('display', 'none');
                    } else if (perID == "A") {
                        $('#extra-mouth-first').css('display', 'none');
                        $('#extra-mouth-last').css('display', 'none');
                        $('#extra-per-first').css('display', 'none');
                        $('#extra-per-last').css('display', 'none');
                    } else {
                        $('#extra-per-first').css('display', 'none');
                        $('#extra-per-last').css('display', 'none');
                    }
                    $('.js-custom-years1').fadeIn();

                } else {
                    $('.js-custom-years').text(response);
                }
            }
        });
    }

    $(".hBack").on("click", function(e) {
        e.preventDefault();
        window.history.back();
    });
    $(".js-showtab").on("click", function() {
        $('#pills-chart').addClass("show active");
        $('#pills-table1').removeClass("show active");
        if ($('#pills-table1-tab').hasClass("active-mode")) {
            $('#pills-table1-tab').removeClass("active-mode");
            $('#pills-table1-tab').addClass("noactive-mode");
            $("#pills-chart-tab").addClass("active-mode");
            $('#pills-chart-tab').removeClass("noactive-mode");
        }
    });
    $("#pills-table1-tab").on("click", function() {
        // $('#pills-chart').addClass("show active");
        if ($('#pills-chart').hasClass("show")) {
            $('#pills-chart').removeClass("show");
            $('#pills-table1').addClass("show");
            $('#pills-table1').addClass("active");
            $('#pills-chart').removeClass("active");
        }
    });
    //add emfa years
    for (var i = 2001; i <= new Date().getFullYear(); i++) {
        $('.js-custom-emfa-years').append(
            $("<div class='custom-control custom-checkbox'><input type='checkbox' class='custom-control-input emfa-years' id='year" + i + "' name='emfayears[]' value=" + i + "><label class='custom-control-label' for='year" + i + "'>" + i + "</label></div>")
        );
    }
    // var tds = $('td');
    // $.each( tds, function( key, value ) {
    //   if($(value).text() == "undefined") {
    //     $(value).remove();
    //   }
    // });
    $(document).ready(function() {
        $('table.search-table').tableSearch({
            searchText: 'Buscar ',
            searchPlaceHolder: ''
        });
    });
    // $('#downloadPNG').click(function() {
    //   // var png64 = document.getElementById('chart').toDataURL('image/jpeg', 1.0);
    //   // $('#downloadPNG').attr('href', png64);
    //   // var canvas = $("canvas").get(0);
    //   // var dataURL = canvas.toDataURL('image/png', 1.0);

    //     var c=document.getElementById("chart");
    //   var ctx=c.getContext("2d");
    //   ctx.fillStyle="#FF0000";

    //   var url = c.toDataURL('image/jpeg', 1);
    //   // var v = 0
    //   // for(var i = 0; i < 100; i++ ){

    //   //     v += 1;
    //   //     x = parseFloat((v).toFixed(2))
    //   //     var test = c.toDataURL('image/jpeg', x);

    //   //     if(test == url){
    //   //         console.log('The default value is: ' + x);
    //   //     }
    //   // }


    //   $('#downloadPNG').attr('href', url);
    // });
});

var decodeEntities = (function() {
    // this prevents any overhead from creating the object each time
    var element = document.createElement('div');

    function decodeHTMLEntities(str) {
        if (str && typeof str === 'string') {
            // strip script/html tags
            str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
            str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
            element.innerHTML = str;
            str = element.textContent;
            element.textContent = '';
        }

        return str;
    }

    return decodeHTMLEntities;
})();

var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
        base64 = function(s) {
            return window.btoa(unescape(encodeURIComponent(s)))
        },
        format = function(s, c) {
            return s.replace(/{(\w+)}/g, function(m, p) {
                return c[p];
            })
        }
    return function(table, name) {
        if (!table.nodeType) table = document.getElementById(table)
        var ctx = {
            worksheet: name || 'Worksheet',
            table: table.innerHTML
        }
        //window.location.href = uri + base64(format(template, ctx))
        var link = document.createElement("a");
        link.download = "table.xls";
        link.href = uri + base64(format(template, ctx));
        link.click();
    }
})()