"use strict";
(function ($) {
    $.view_list_servicelocator = function (element, options) {
        let defaults = {
            row_state_template: "",
            data_input:[],
            page_list_service:'',
            list_service:[]
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let list_service = plugin.settings.list_service;
            $element.find('select.list-location').select2();
            $element.find('select.list-employee').select2();
            $element.find('.ul-list-service').slideUp();

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

            $('.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('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('.form-search-hotels input[name="keyword_address"]').on('keyup', filterAjax);
            $element.find('.form-search-hotels input#check-in').on('change', filterAjax);
            $element.find('.form-search-hotels input[name="check_in"]').on('change', filterAjax);
            $element.find('.form-search-hotels input#check-out').on('change', filterAjax);
            $element.find('.form-search-hotels input[name="check_out"]').on('change', filterAjax);
            $element.find('.form-search-hotels .btn-minius').on('click', filterAjax);
            $element.find('.form-search-hotels .btn-plus').on('click', 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);
            $('body').on('click','.nav-tabs li', function(event) {
                event.preventDefault();
                let layout = $(this).data('layout');
                $element.find('input[name="tab"]').val(layout);
            });
            $('body').on('click','.nav-tabs li', filterAjax);
            let limit=parseInt(plugin.settings.limit);
            $element.find('input[name="limit1"]').val(limit);
            let page = parseInt(plugin.settings.page);
            let start = parseInt(plugin.settings.start);
            $element.find('#pagination-hotels-ajax').on('click', function() {
                let input_limit = parseInt($element.find('input[name="limit1"]').val());
                let input_page = page;
                let input_start = parseInt($element.find('input[name="start"]').val());
                input_start = parseInt(input_start)+limit;
                $element.find('input[name="start"]').val(input_start);
                input_limit = parseInt(input_limit)+limit;
                $element.find('input[name="limit1"]').val(input_limit);
                input_page = parseInt(input_page)+page;
                $element.find('input[name="page"]').val(input_page);
            });
            $element.find('#pagination-hotels-ajax').on('click', filterAjax);   
            $element.find('.sort-display a').click(function(){
                let sort=$(this).data('key_sort');
                let direction=$(this).data('direction');
                $element.find('input[name="key_sort"]').val(sort);
                $element.find('input[name="start"]').val(0);
                $element.find('input[name="direction"]').val(direction);
                $element.find('.sort-by-block .dropdown').removeClass('open');
            });      
            $element.find('.sort-display a').click(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': plugin.settings.store_limit,
                // '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/wpbookinghotel/frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/infowindow-description.html`,
                'listTemplatePath': `${wpbookinghotel_root_url}/wp-content/plugins/wpbookinghotel/frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/location-list-description.html`,
                'gridTemplatePath': `${wpbookinghotel_root_url}/wp-content/plugins/wpbookinghotel/frontend/resources/store_locator/assets/js/plugins/storeLocator/templates/location-grid-description.html`,
            });
            $('body').on('click','.heart',function(e){
                let $hotel_item = $(this).closest('.wishlist-item');
                let hotel_id = $hotel_item.data('hotel_id');
                let user_id = $('.view-list-servicelocator').data('user_id');
                let $wishlist_icon = $(this);
                if(user_id=="" && user_id==0){
                    if ( $('.alert-warning').length == 0){
                        $("body").append('<div class="alert alert-warning" role="alert" style="display: inline-block;position: fixed;right: 60px;top: 30px;z-index:999;" >Please login to use the feature!<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="margin-left: 30px"><span aria-hidden="true">&times;</span></button></div>');
                        setTimeout(function(){
                            $('.alert-warning').remove();
                        },1500)
                    }
                    return;
                }
                let data = {
                    task: "wishlist.change_wishlist",
                    state: 1,
                    hotel_id: hotel_id,
                    user_id: user_id,
                };
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: wpbookinghotel_root_url + wpbookinghotel_api_task,
                    data: data,
                    beforeSend: function () {
                        $wishlist_icon.toggleClass("active");
                        $wishlist_icon.find('i').removeClass("fa-heart").addClass("fa-spinner fa-spin");
                    },
                    error: function (xhr) {

                    },
                    complete: function () {
                        $wishlist_icon.find('i').addClass("fa-heart").removeClass("fa-spinner fa-spin");
                    },
                    success: function (response) {
                        response = JSON.parse(response);
                    }
                });
            })
            var scrollMap = plugin.debounce(function () {
                var $sticky = $element.find('#bh-sl-map');
                if ($sticky.length > 0) {
                    $($sticky).stick_in_parent()
                        .on('sticky_kit:bottom', function(e) {
                            $($sticky).removeClass('custom-sticky');
                        })
                        .on('sticky_kit:unbottom', function(e) {
                            $($sticky).addClass('custom-sticky');
                        });

                    $(window).on('resize', function () {
                        $($sticky).trigger('sticky_kit:detach');
                    });
                }
            }, 250);
            $(window).scroll(scrollMap);
        };

        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.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);
