"use strict";
(function ($) {
    $.view_list_hotellocator = function (element, options) {
        let defaults = {
            row_state_template: "",
            data_input:[],
            page_list_service:'',
            list_service:[],
            url_plugin:''
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let list_service = plugin.settings.list_service;
            let rate = plugin.settings.rate;
            let symbol=plugin.settings.symbol;
            $element.find('select.list-location').select2();
            $element.find('select.list-roomtype').select2();
            $element.find('#slider-container-1').slider({
                range: true,
                min: 0,
                max: 500,
                values: [0, 500],
                create: function () {
                    $("#amount_1").val(symbol+' 0'+' - '+symbol+' '+parseFloat((500 * rate)).toFixed(2));
                },
                slide: function (event, ui) {
                    $("#amount_1").val(symbol + parseFloat((ui.values[0] * rate)).toFixed(2) + ' - '+symbol + parseFloat((ui.values[1] * rate)).toFixed(2));
                    var mi = rate*ui.values[0];
                    var mx = rate*ui.values[1];
                    plugin.filterSystem(mi, mx);
                },
                change: function(event, ui) {
                    var mi = rate*ui.values[0];
                    var mx = rate*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.find('.block-filter-price').slideUp();
            $element.find('.list-rating').slideUp();
            $element.find('.block-location-near-me').slideUp();
            $element.find('.wrapper-price-rating2').slideUp();
            $element.find('p.more-option').on('click',function (e) {
                let $block_more_option = $(this).closest('.filter-more');
                $block_more_option.find('.block-filter-price').slideToggle();
                $block_more_option.find('.list-rating').slideToggle();
                $block_more_option.find('.block-location-near-me').slideToggle();
                $block_more_option.find('.wrapper-price-rating2').slideToggle();
            });

            $element.closest('.tour-operator-pro-view').addClass('tour-operator-pro-view');
            $element.find('.nav-tabs > div').on('click', function () {
                $(this).addClass('active');
                $element.find('.nav-tabs > div').not(this).removeClass('active');
            });
            $('.title-load-more').next('.block-filter-load-more').slideUp();
            $('body').on('click','.title-load-more', function() {
                $(this).addClass('active');
                $(this).find("span").toggleClass("icon-minus icon-plush",300);
                $(this).next('.block-filter-load-more').slideToggle("slow");
            })

            $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="key_sort"]').val(key_sort).trigger('change');
                $element.find('input[name="direction"]').val(direction).trigger('change');
                $form.submit();
            });

            $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');
                }
            })

            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');
                    }
                })
            });

            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="room_type_id"]').on('change', filterAjax);
            $element.find('select[name="location_id"]').on('change', filterAjax);
            $element.find('input[name="category_id[]"]').on('change', filterAjax);
            $element.find('input[name="service_id[]"]').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('.form-search-hotels .btn-plus').on('click', filterAjax);
            $element.find('input[name="price_search"]').on('change', filterAjax);
            $element.find('input[name="amenity_id"]').on('change', filterAjax);
            $element.find('.form-search-hotels input.input-field').on('change', filterAjax);
            $element.find('.form-search-hotels input[name="rating[]"]').on('change', filterAjax);
            $element.find('.form-search-hotels input[name="room_type_id[]"]').on('change', filterAjax);

            let url_plugin = plugin.settings.url_plugin;
            $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': `${wpbookinghotel_root_url}${wpbookinghotel_api_task}/?task=hotels.ajax_get_list_hotel`,
                'infowindowTemplatePath': `${wpbookinghotel_root_url}/wp-content/plugins/${plugin.settings.url_plugin}/frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/infowindow-description.html`,
                'listTemplatePath': `${wpbookinghotel_root_url}/wp-content/plugins/${plugin.settings.url_plugin}/frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/location-list-description.html`,
                'gridTemplatePath': `${wpbookinghotel_root_url}/wp-content/plugins/${plugin.settings.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.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_hotellocator = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_list_hotellocator')) {
                let plugin = new $.view_list_hotellocator(this, options);
                $(this).data('view_list_hotellocator', plugin);
            }
        });
    }
})(jQuery);
