"use strict";
(function ($) {
    var _ajax;

    $(document).ready(function () {
        /*
         * reset field when empty selected on taxonomy checkbox
         */
        $(document).on("click", 'input[type="checkbox"]', function (e) {
            let name = $(this).attr("name");
            let val = $(this).val();
            if (val == "") {
                $('input[name="' + name + '"]').prop("checked", false);
            }
        });

        /**
         * this event will run when there is a submit button filter
         */
        $(document).on(
            "click",
            ".whfilter_form .submit-filter, .whfilter_form .reset-filter",
            function (e) {
                e.preventDefault();

                let form = $(this).parents("form");
                let selectedIdForm = form.attr("id");
                let formdata = form.serialize();

                if ($(this).attr("type") == "reset") {
                    document.getElementById(selectedIdForm).reset();
                    formdata = $(
                        `#${selectedIdForm} :input[value!=""][value!="."]`
                    ).serialize();
                }

                //append multiple if exist
                let multiplePerpage = $(
                    `#multiple-post-perpage.${selectedIdForm}`
                ).val();
                if (multiplePerpage) {
                    formdata += "&mutltiple_perpage=" + multiplePerpage;
                }

                //append sortby if exists
                let sortby = $(`#sortby.${selectedIdForm}`).val();
                if (sortby) {
                    let order = $(
                        `.${selectedIdForm}.whfilter-overview [name="order"]`
                    ).val();
                    let order_meta_key = $(
                        `.${selectedIdForm}.whfilter-overview [name="order_meta_key"]`
                    ).val();

                    formdata += "&sortby=" + sortby + "&order=" + order;
                    if (order_meta_key) {
                        formdata += "&order_meta_key=" + order_meta_key;
                    }
                }

                let data = {
                    action: "submit_filter",
                    data: formdata,
                };

                whSubmiFilter(data, selectedIdForm);
            }
        );

        /**
         * this event prevent whent submit form whfilter
         */
        $(document).on("submit", ".whfilter_form", function (e) {
            e.preventDefault();
        });

        /**
         * this event will run when there is a change to the form filter
         */
        $(document).on("change", ".whfilter_form", function (e) {
            e.preventDefault();

            let form = $(this);
            let selectedIdForm = form.attr("id");
            let submit = form.data("auto-submit");
            let formdata = form.serialize();

            //append multiple if exist
            let multiplePerpage = $(
                `#multiple-post-perpage.${selectedIdForm}`
            ).val();
            if (multiplePerpage) {
                formdata += "&mutltiple_perpage=" + multiplePerpage;
            }

            //append sortby if exists
            let sortby = $(`#sortby.${selectedIdForm}`).val();
            if (sortby) {
                let order = $(
                    `.${selectedIdForm}.whfilter-overview [name="order"]`
                ).val();

                let order_meta_key = $(
                    `.${selectedIdForm}.whfilter-overview [name="order_meta_key"]`
                ).val();

                formdata += "&sortby=" + sortby + "&order=" + order;
                if (order_meta_key) {
                    formdata += "&order_meta_key=" + order_meta_key;
                }
            }

            let data = {
                action: "submit_filter",
                data: formdata,
            };

            if (submit == "auto") {
                whSubmiFilter(data, selectedIdForm);
            }
        });

        /**
         * this event code is useful when the filter has a sortby feature and perfoms data changes with a shortcut
         */
        $(document).on("change", "#sortby", function (e) {
            e.preventDefault();

            //get id form in class tag shortby
            let selectedIdForm = $(this).data("sortby");
            let form = $(`#${selectedIdForm}`);

            let sortby = $(this).val();
            let submit = form.data("auto-submit");
            let formdata = form.serialize();

            //append multiple if exist
            let multiplePerpage = $(
                `#multiple-post-perpage.${selectedIdForm}`
            ).val();
            if (multiplePerpage) {
                formdata += "&mutltiple_perpage=" + multiplePerpage;
            }

            //append sortby if exists
            if (sortby) {
                let order = $(
                    `.whfilter-overview.${selectedIdForm} [name="order"]`
                ).val();
                let order_meta_key = $(
                    `.whfilter-overview.${selectedIdForm} [name="order_meta_key"]`
                ).val();

                formdata += "&sortby=" + sortby + "&order=" + order;
                if (order_meta_key) {
                    formdata += "&order_meta_key=" + order_meta_key;
                }
            }

            let data = {
                action: "submit_filter",
                data: formdata,
            };

            if (submit == "auto") {
                whSubmiFilter(data, selectedIdForm);
            }
        });

        /**
         * this event code is useful when the filter sort order
         */
        $(document).on("click", ".sort-order", function (e) {
            e.preventDefault();

            //get id form in class tag shortby
            let selectedIdForm = $(this).data("sortorder");
            let form = $(`#${selectedIdForm}`);
            let order = $(
                `.whfilter-overview.${selectedIdForm} [name="order"]`
            ).val();

            //change icon sort order arrow
            if (order == "ASC") {
                $(`.whfilter-overview.${selectedIdForm} [name="order"]`).val(
                    "DESC"
                );
                $(`.sort-order.${selectedIdForm} span`)
                    .removeClass("icon-arrow-asc")
                    .addClass("icon-arrow-desc");
            } else {
                $(`.whfilter-overview.${selectedIdForm} [name="order"]`).val(
                    "ASC"
                );
                $(`.sort-order.${selectedIdForm} span`)
                    .removeClass("icon-arrow-desc")
                    .addClass("icon-arrow-asc");
            }

            let submit = form.data("auto-submit");
            let formdata = form.serialize();

            //append multiple if exist
            let multiplePerpage = $(
                `#multiple-post-perpage.${selectedIdForm}`
            ).val();
            if (multiplePerpage) {
                formdata += "&mutltiple_perpage=" + multiplePerpage;
            }

            //append sortby if exists
            let sortby = $(`#sortby.${selectedIdForm}`).val();

            if (sortby) {
                let order_meta_key = $(
                    `.whfilter-overview.${selectedIdForm} [name="order_meta_key"]`
                ).val();

                formdata += "&sortby=" + sortby + "&order=" + order;

                if (order_meta_key) {
                    formdata += "&order_meta_key=" + order_meta_key;
                }
            }

            let data = {
                action: "submit_filter",
                data: formdata,
            };

            if (submit == "auto") {
                whSubmiFilter(data, selectedIdForm);
            }
        });

        /**
         * this event will run when there is an action in the pagination sectio
         */
        $(document).on(
            "click",
            ".whfilter-overview button.page-numbers",
            function (e) {
                e.preventDefault();

                let selectedIdForm = $(this)
                    .closest(".ajax-response")
                    .data("listingfilter");

                let form = $(`#${selectedIdForm}.whfilter_form`);
                let formdata = form.serialize();
                let paged = $(this).data("page");

                //append multiple if exist
                let multiplePerpage = $(
                    `#multiple-post-perpage.${selectedIdForm}`
                ).val();
                if (multiplePerpage) {
                    formdata += "&mutltiple_perpage=" + multiplePerpage;
                }

                //append sortby if exists
                let sortby = $(`#sortby.${selectedIdForm}`).val();
                if (sortby) {
                    let order = $(
                        `.whfilter-overview.${selectedIdForm} [name="order"]`
                    ).val();
                    let order_meta_key = $(
                        `.whfilter-overview.${selectedIdForm} [name="order_meta_key"]`
                    ).val();

                    formdata += "&sortby=" + sortby + "&order=" + order;
                    if (order_meta_key) {
                        formdata += "&order_meta_key=" + order_meta_key;
                    }
                }

                let data = {
                    action: "submit_filter",
                    data: formdata,
                    paged: paged,
                };

                whSubmiFilter(data, selectedIdForm);
            }
        );

        /**
         * this event code is useful when the filter has a sortby feature and performs data changes with a shortcut
         */
        $(document).on("change", "#multiple-post-perpage", function (e) {
            e.preventDefault();

            //get id form in class tag shortby
            let selectedIdForm = $(this).data("multipleperpage");
            let form = $(`#${selectedIdForm}`);
            let formdata = form.serialize();
            let multiplePerpage = $(this).val();
            let submit = form.data("auto-submit");
            let sortby = $(`#sortby.${selectedIdForm}`).val();

            //append multiple if exist
            if (multiplePerpage) {
                formdata += "&mutltiple_perpage=" + multiplePerpage;
            }

            //append sortby if exists
            if (sortby) {
                let order = $(
                    `.whfilter-overview.${selectedIdForm} [name="order"]`
                ).val();
                let order_meta_key = $(
                    `.whfilter-overview.${selectedIdForm} [name="order_meta_key"]`
                ).val();

                formdata += "&sortby=" + sortby + "&order=" + order;
                if (order_meta_key) {
                    formdata += "&order_meta_key=" + order_meta_key;
                }
            }

            let data = {
                action: "submit_filter",
                data: formdata,
            };

            if (submit == "auto") {
                whSubmiFilter(data, selectedIdForm);
            }
        });
    });

    /**
     * function to do ajax process (request and response)
     *
     * @param {object} data
     * @param {int} idFormFilter
     */
    function whSubmiFilter(data, idFormFilter) {
        //this for get only number ID whfilter
        data.data += "&form_filter=" + idFormFilter.match(/(\d+)/)[0];

        let ajaxResults = $(`.ajax-response.${idFormFilter}`);
        let formWhFilter = $(`#${idFormFilter}.whfilter_form`);

        if (_ajax === "undefined") {
            _ajax.abort();
        }

        let loading =
            ' <div class="ajaxloading ' +
            idFormFilter +
            '">' +
            ajax.loading +
            "</div>";

        formWhFilter.trigger("whfilter_submit", data);

        _ajax = $.ajax({
            url: ajax.ajaxurl,
            type: "post",
            data: data,
            beforeSend: function () {
                $(document).find(".ajaxloading").remove();
                $(document).find(ajaxResults).before(loading);
            },
            success: function (response) {
                ajaxResults.html("");
                ajaxResults.html(response.html);

                $(`.${idFormFilter} .info-results .result-count`).html(
                    response.info
                );

                formWhFilter.trigger("whfilter_submited", response);

                //page uel changes if the page only has 1 whfilter
                if ($(".whfilter_form").length < 2) {
                    //new url 'newurl'
                    window.history.pushState(response, "", response.newurl);
                }

                //this code for auto scroll
                $("html, body").animate(
                    {
                        scrollTop: eval(formWhFilter.offset().top - 200),
                    },
                    350
                );
            },
            complete: function () {
                $(document).find(`.ajaxloading.${idFormFilter}`).remove();
            },
        });
    }
})(jQuery);
