"use strict";
(function ($) {
    $.view_list_servicelocator = function (element, options) {
        let defaults = {
            row_state_template: "",
            data_input:[],
            page_list_service:'',
            list_service:[],
            format_currency:''
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let list_service = plugin.settings.list_service;
            let format_currency = plugin.settings.format_currency;
            $element.find('select.list-location').select2();
            $element.find('select.list-employee').select2();
            $element.find('.ul-list-service').slideUp();
            $element.find('#slider-container-1').slider({
                range: true,
                min: 0,
                max: 1099,
                values: [0, 1099],
                create: function () {
                    $("#amount_1").val(format_currency+ "0 - "+ format_currency+ "1099");
                },
                slide: function (event, ui) {
                    $("#amount_1").val(format_currency + ui.values[0] + " - "+ format_currency + ui.values[1]);
                    var mi = ui.values[0];
                    var mx = ui.values[1];
                    plugin.filterSystem(mi, mx);
                },
                change: function(event, ui) {
                    var mi = ui.values[0];
                    var mx = ui.values[1];
                    let price_value=[];
                    price_value.push(mi);
                    price_value.push(mx);
                    $element.find(`input[name="price_search"]`).val(JSON.stringify(price_value)).trigger('change');
                }
            });

            $element.closest('.wpbooking-pro-view').addClass('wpbooking-pro-view-locator');
            $element.find('.nav-tabs > div').on('click', function () {
                $(this).addClass('active');
                $element.find('.nav-tabs > div').not(this).removeClass('active');
            });

            $element.find('.sort-display a').on('click',function (e) {
                let $form = $(this).closest('form[name="filter-form"]')
                let key_sort=$(this).data('key_sort');
                let direction=$(this).data('direction');
                $element.find('input[name="sort"]').val(key_sort).trigger('change');
                $element.find('input[name="direction"]').val(direction).trigger('change');
                $form.submit();
            });
            let $select_sort_item = $element.find('.sort-display a.select-sort-item');

            $element.find('.sort-by-price .dropdown').on('click', function () {
                $(this).find('i').addClass('active');
                if($(this).hasClass('open') === false) {
                    $(this).find('i').removeClass('active');
                }
            });

            $element.find('input[name="direction"]').on('change', function () {
                let val = $(this).val();
                $.each($select_sort_item, function (index, item) {
                    let direction = $(item).data('direction');
                    if(val === direction) {
                        $(item).addClass('active');
                        let text = $(item).text();
                        $element.find('span.select-by-default').text(text);
                    } else {
                        $(item).removeClass('active');
                    }
                })
            });

            $element.find('input.input-near-me').on('change', function () {
                if($(this).is(":checked")) {
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                            var latitude = position.coords.latitude;
                            var longitude = position.coords.longitude;
                            $element.find('input[name="latitude"]').val(latitude).trigger('change');
                            $element.find('input[name="longitude"]').val(longitude).trigger('change');
                        }, function () {
                            $element.find('input[name="latitude"]').val('').trigger('change');
                            $element.find('input[name="longitude"]').val('').trigger('change');
                        })
                    } else {
                        alert("Sorry, your browser does not support HTML5 geolocation.");
                    }
                } else {
                    $element.find('input[name="latitude"]').val('').trigger('change');
                    $element.find('input[name="longitude"]').val('').trigger('change');
                }
            })

            var filterAjax = plugin.debounce(function () {
                let $form = $(this).closest('form[name="filter-form"]');
                $form.submit();
            }, 1000);
            $element.find('input[name="keyword"]').on('keyup',filterAjax);

            $element.find('select[name="employee"]').on('change', filterAjax);
            $element.find('select[name="location_id"]').on('change', filterAjax);

            $element.find('input[name="category[]"]').on('change', filterAjax);
            $element.find('input[name="total_rating_avg"]').on('change', filterAjax);
            $element.find('input[name="latitude"]').on('change', filterAjax);
            $element.find('input[name="longitude"]').on('change', filterAjax);
            $element.find('input[name="rating[]"]').on('change', filterAjax);
            $element.find('input[name="price_search"]').on('change', filterAjax);
            $element.find('input[name="vendor[]"]').on('change', filterAjax);




            $element.find('#bh-sl-map-container').storeLocator({
                ajaxData:function (e) {
                    var output = plugin.convert_data_form();
                    let dataObj = {};
                    $(output).each(function(i, field){
                        dataObj[field.name] = field.value;
                    });
                    return dataObj;
                },
                'querystringParams' : true,
                'fullMapStart': true,
                'pagination': true,
                'storeLimit': list_service.length,
                // The following paths are set because this example is in a subdirectory
                'dataLocation': `${wpbookingpro_root_url}${wpbookingpro_api_task}/?task=services.ajax_get_list_service`,
                'infowindowTemplatePath': `${wpbookingpro_root_url_plugin}frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/infowindow-description.html`,
                'listTemplatePath': `${wpbookingpro_root_url_plugin}frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/location-list-description.html`,
                'gridTemplatePath': `${wpbookingpro_root_url_plugin}frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/location-grid-description.html`,
            });

        };

        plugin.debounce = function(func, wait) {
            var timeout;

            return function() {
                var context = this,
                    args = arguments;

                var executeFunction = function() {
                    func.apply(context, args);
                };

                clearTimeout(timeout);
                timeout = setTimeout(executeFunction, wait);
            };
        };
        plugin.convert_data_form = function() {
            var dataArray = $element.find('.form-search-service').serializeArray();
            var output = [];
            dataArray.forEach(function(item) {
                var existing = output.filter(function(v, i) {
                    return v.name == item.name;
                });
                if (existing.length) {
                    var existingIndex = output.indexOf(existing[0]);
                    output[existingIndex].value = output[existingIndex].value.concat(item.value);
                } else {
                    if (typeof item.value == 'string')
                        item.value = [item.value];
                    output.push(item);
                }
            });
            return output;
        };

        plugin.filter_ajax = function(dataObj) {
            $.ajax({
                url: wpbookingpro_root_url+wpbookingpro_api_task,
                type: 'POST',
                dataType: 'json',
                data: {
                    dataObj: JSON.stringify(dataObj),
                    task: "services.get_list_services_filter",
                    page_detail_service: plugin.settings.page_detail_service
                },
                beforeSend: function() {
                    $('body').loadingModal();
                },
                success: function(res) {
                },
                error: function(xhr) { // if error occured

                },
                complete: function() {
                    $('body').loadingModal('destroy');

                },
            })
        };
        plugin.filterSystem = function (minPrice, maxPrice) {
            $("#computers div.system").hide().filter(function () {
                var price = parseInt($(this).data("price"), 10);
                return price >= minPrice && price <= maxPrice;
            }).show();
        }

        plugin.example_function = function () {
        }
        plugin.init();
    }
    $.fn.view_list_servicelocator = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_list_servicelocator')) {
                let plugin = new $.view_list_servicelocator(this, options);
                $(this).data('view_list_servicelocator', plugin);
            }
        });
    }
})(jQuery);
