function updateShowMoreLess(elt) {
    let input = jQuery("[name='" + jQuery(elt).prev().attr('name').replace('_less]', '_less_nb_values]') + "']");
    if (jQuery(elt).attr('checked')) {
        input.css({'display': 'block'});
    } else {
        input.css({'display': 'none'});
    }
}

function updateFromAttribute(elt) {
    elt = jQuery(elt);
    if (elt.val() == "final_price") {
        jQuery(elt.parents('tr')[0]).find('.show-more-less, input[type=text], .show-layer-filter, .show-result-count, .no-follow').css({'display': 'none'});
    } else {
        if (elt.val() == "rating" || elt.val() == "categories") {
            jQuery(elt.parents('tr')[0]).find('.show-more-less, input[type=text], .show-layer-filter, .no-follow').css({'display': 'none'});
        } else {
            jQuery(elt.parents('tr')[0]).find('.show-more-less, input[type=text], .show-layer-filter, .show-result-count, .no-follow').css({'display': 'block'});
            updateShowMoreLess(jQuery(elt.parents('tr')[0]).find('.show-more-less'));
        }
    }
}

require(["jquery", "Magento_Ui/js/modal/alert", "Magento_Ui/js/modal/confirm"], function ($, alert, confirm) {
    $(function () {
        $(document).ready(function () {
            // TEST SERVER
            $("#es_test_servers").on("click", function () {
                $.ajax({
                    url: $("#es_test_servers").attr("callback_url"),
                    data: {
                        servers: $("#wyomind_elasticsearchcore_configuration_servers").val()
                    },
                    type: "POST",
                    showLoader: true,
                    success: function (data) {
                        var html = "";
                        data.each(function (host_data) {
                            html += "<h3>" + host_data.host + "</h3>";
                            if (host_data.error !== undefined) {
                                html += "<span class='error'>ERROR</span><br/><br/>" + host_data.error;
                            } else {
                                html += "<span class='success'>SUCCESS</span><br/><br/>";
                                html += "<b>Name</b> : " + host_data.data.name + "<br/>";
                                html += "<b>Cluster name</b> : " + host_data.data.cluster_name + "<br/>";
                                html += "<b>Elasticsearch version</b> : " + host_data.data.version.number + "<br/>";
                            }
                            html += "<br/><br/>";
                        });
                        alert({
                            title: "",
                            content: html
                        });
                    }
                });
            });


            // FILTERABLES ATTRIBUTES - LayeredNavigation
            var sortables = {"category": ["top", "left", "right", "mobile"], "search": ["top", "left", "right", "mobile"]};

            updateIndexes = function (target) {

                var index = 1;
                _.each($((target)).find("tr"), function (tr) {
                    $(tr).find("input[id$=_position]").val(index++);
                    if ($(tr).find("input[id$=_show_more_less_nb_values]").length && $(tr).find("input[id$=_show_more_less_nb_values]").val() == "") {
                        $(tr).find("input[id$=_show_more_less_nb_values]").val(5);
                    }
                });
            };

            _.each(sortables, function (positions, type) {
                _.each(positions, function (position) {
                    if ($("#wyomind_elasticsearchlayerednavigation_settings_display_" + type + "_layer_" + position + "_attributes").length === 1) {
                        var table = $("table#wyomind_elasticsearchlayerednavigation_settings_display_" + type + "_layer_" + position + "_attributes");
                        var tbody = table.find("tbody");

                        // sortable list
                        tbody.sortable({
                            connectWith: "li",
                            stop: function (event, ui) {
                                updateIndexes(event.target);
                            }
                        });

                        tbody.find('input[type=checkbox]').each(function (i, cbx) {
                            $(cbx).prev().css({'display': 'none'});
                            $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                            if ($(cbx).hasClass('show-more-less')) {
                                updateShowMoreLess(cbx);
                            }
                        });

                        tbody.find('select[name$=\\[attribute_code\\]]').each(function (i, slt) {
                            updateFromAttribute(slt);
                        });

                        $(document).on('change', 'select[name$=\\[attribute_code\\]]', function (evt) {
                            updateFromAttribute(evt.target);
                        });

                        // adding new row to the list
                        //var observable = "#" + tbody.attr("id").replace("addRow_", "addToEndBtn_");
                        // $(observable).on("click", function () {
                        //     setTimeout(function () {
                        //         updateIndexes(tbody);
                        //     }, 300);
                        // });
                        $(document).on('click', "#" + tbody.attr("id") + " button[id^=addAfterBtn_], #" + table.attr("id") + " button[id^=addToEndBtn_]", function () {
                            setTimeout(function () {
                                updateIndexes(tbody);
                                tbody.find('input[type=checkbox]').each(function (i, cbx) {
                                    $(cbx).prev().css({'display': 'none'});
                                    $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                                    if ($(cbx).hasClass('show-more-less')) {
                                        updateShowMoreLess(cbx);
                                    }
                                });
                            }, 100);
                        });
                    } else {
                        /* Mage 2.1 */
                        if ($("#row_wyomind_elasticsearchlayerednavigation_settings_display_" + type + "_layer_" + position + "_attributes table").length === 1) {
                            var tbody = $("#row_wyomind_elasticsearchlayerednavigation_settings_display_" + type + "_layer_" + position + "_attributes table tbody");

                            // sortable list
                            tbody.sortable({
                                connectWith: "li",
                                stop: function (event, ui) {
                                    updateIndexes(event.target);
                                }
                            });

                            tbody.find('input[type=checkbox]').each(function (i, cbx) {
                                $(cbx).prev().css({'display': 'none'});
                                $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                                if ($(cbx).hasClass('show-more-less')) {
                                    updateShowMoreLess(cbx);
                                }
                            });

                            tbody.find('select[name$=\\[attribute_code\\]]').each(function (i, slt) {
                                updateFromAttribute(slt);
                            });

                            $(document).on('change', 'select[name$=\\[attribute_code\\]]', function (evt) {
                                updateFromAttribute(evt.target);
                            });

                            // adding new row to the list
                            var observable = "#" + tbody.attr("id").replace("addRow_", "addToEndBtn_");
                            observable += ", #" + tbody.attr("id") + " button";

                            $(observable).on("click", function () {
                                setTimeout(function () {
                                    updateIndexes(tbody);
                                }, 300);
                            });
                        }
                    }
                });
            });

            // FILTERABLES ATTRIBUTES - MultifacetedAutocomplete
            if ($("#wyomind_elasticsearchmultifacetedautocomplete_settings_display_layer_attributes").length === 1) {

                var table = $("#wyomind_elasticsearchmultifacetedautocomplete_settings_display_layer_attributes");
                var tbody = $("#wyomind_elasticsearchmultifacetedautocomplete_settings_display_layer_attributes tbody");

                // sortable list
                tbody.sortable({
                    connectWith: "li",
                    stop: function (event, ui) {
                        updateIndexes(event.target);
                    }
                });

                tbody.find('input[type=checkbox]').each(function (i, cbx) {
                    $(cbx).prev().css({'display': 'none'});
                    $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                    if ($(cbx).hasClass('show-more-less')) {
                        updateShowMoreLess(cbx);
                    }
                });

                tbody.find('select[name$=\\[attribute_code\\]]').each(function (i, slt) {
                    updateFromAttribute(slt);
                });

                $(document).on('change', 'select[name$=\\[attribute_code\\]]', function (evt) {
                    updateFromAttribute(evt.target);
                });

                // adding new row to the list
                var observable = "#" + tbody.attr("id").replace("addRow_", "addToEndBtn_");
                observable += ", #" + tbody.attr("id") + " button";

                $(observable).on("click", function () {
                    setTimeout(function () {
                        updateIndexes(tbody);
                    }, 300);
                });

                $(document).on('click', "#" + tbody.attr("id") + " button[id^=addAfterBtn_], #" + table.attr("id") + " button[id^=addToEndBtn_]", function () {
                    setTimeout(function () {
                        updateIndexes(tbody);
                        tbody.find('input[type=checkbox]').each(function (i, cbx) {
                            $(cbx).prev().css({'display': 'none'});
                            $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                            if ($(cbx).hasClass('show-more-less')) {
                                updateShowMoreLess(cbx);
                            }
                        });
                    }, 100);
                });
            } else {
                /* Mage 2.1 */
                if ($("#row_wyomind_elasticsearchmultifacetedautocomplete_settings_display_layer_attributes table").length === 1) {
                    var tbody = $("#row_wyomind_elasticsearchmultifacetedautocomplete_settings_display_layer_attributes table tbody");

                    // sortable list
                    tbody.sortable({
                        connectWith: "li",
                        stop: function (event, ui) {
                            updateIndexes(event.target);
                        }
                    });

                    tbody.find('input[type=checkbox]').each(function (i, cbx) {
                        $(cbx).prev().css({'display': 'none'});
                        $(cbx).prop('checked', $(cbx).prev().val() == 1 ? true : false);
                        if ($(cbx).hasClass('show-more-less')) {
                            updateShowMoreLess(cbx);
                        }
                    });

                    tbody.find('select[name$=\\[attribute_code\\]]').each(function (i, slt) {
                        updateFromAttribute(slt);
                    });

                    $(document).on('change', 'select[name$=\\[attribute_code\\]]', function (evt) {
                        updateFromAttribute(evt.target);
                    });

                    // adding new row to the list
                    var observable = "#" + tbody.attr("id").replace("addRow_", "addToEndBtn_");
                    observable += ", #" + tbody.attr("id") + " button";

                    $(observable).on("click", function () {
                        setTimeout(function () {
                            updateIndexes(tbody);
                        }, 300);
                    });
                }
            }
        });
    });
});