jQuery(function($){

    function getRandom(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    const galleryItems = $('.spbooking .owl-carousel').attr('data-carousel-items') ? $('.spbooking .owl-carousel').attr('data-carousel-items') : 1;
    
    $('.owl-carousel.ac-gallery, .owl-carousel.tranport-gallery, .owl-carousel.package-gallery, .owl-carousel.room-gallery').owlCarousel({
        dots: false,
        items: galleryItems,
        autoplay: true,
        center: true,
        nav: true,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true 
    });

    $('.top-reviews-carousel.owl-carousel').owlCarousel({
        dots: true,
        items: 1,
        autoplay: true,
        center: true,
        nav: false,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true
    });
    
    $('.owl-carousel.ac-g11').owlCarousel({
        dots: false,
        items: 1,
        autoplay: true,
        center: true,
        nav: true,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true   
    });
    $('.owl-carousel.ac-g12').owlCarousel({
        dots: false,
        items: 1,
        autoplay: true,
        center: true,
        nav: true,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true
    });
    $('.owl-carousel.ac-g13').owlCarousel({
        dots: false,
        items: 1,
        autoplay: true,
        center: true,
        nav: true,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true
    });
    $('.owl-carousel.ac-g14').owlCarousel({
        dots: false,
        items: 1,
        autoplay: true,
        center: true,
        nav: true,
        loop: true,
        autoplayTimeout: getRandom(3000, 6000),
        autoplayHoverPause: true
    });

    // prettyPhoto initiation
    if ($("a[rel^='prettyPhoto']").length > 0) {
        $("a[rel^='prettyPhoto']").prettyPhoto({
            animation_speed:'normal',
            theme:'default', 
            autoplay_slideshow: false,
            autoplay: true, 
            display_control: true,
            fullscreen: true,  
            autohide: true, 
            show_suggested_video: false,
            showinfo: false
        });
    }

    // Price range noUiSlider
    var ranger = document.getElementById('price-range');

    if (ranger !=  null) {
        // has price value
        var minprice = $('#min-price.spbooking-ranger').val();
        var maxprice = $('#max-price.spbooking-ranger').val();
        if (!minprice) {
            var minprice = 0;
        }
        if (!maxprice) {
            var maxprice = 9999;
        }

        acMaxPrice = typeof(acMaxPrice) == 'number' && acMaxPrice > 0 ? acMaxPrice : 9999;
        noUiSlider.create(ranger , {
            connect: true,
            behaviour: 'tap',
            start: [minprice, parseInt(maxprice)],
            tooltips: [true, true],
            step: 10,
            range: {
                'min': [0],
                'max': [parseInt(acMaxPrice)]
            },
            format: {
                to: function (value) {
                    if (gCurrency_position == 'left') {
                        return `${gCurrency}${parseInt(value, 10)}`;
                    } else {
                        return `${parseInt(value, 10)}${gCurrency}`;
                    }
                },
                from: function (value) {
                    return parseInt(value, 10);
                }
            }
        });
        
        ranger.noUiSlider.on('update', function(values, handle) {
            $('#min-price').val(values[0]);
            $('#max-price').val(values[1]);
        });
    }
    

    $('.spbooking-accomodation-listing #accomodation-filtering-form').on('submit', function(e){
        e.preventDefault();

        let data = $(this).serializeArray();
        let query = new URLSearchParams(window.location.search);

        data = typeof(data) == 'object' && data instanceof Array && data.length > 0 ? data : false;
        query = typeof (query) == 'object' && query ? query : false;
        
        let valid_values = [];
        let facilities = [];
        let tags = [];
        data.map((v) => {
            let val = typeof(v.value) == 'string' && v.value.length > 0 ? v.value : false;
            let name = typeof(v.name) == 'string' && v.name.length > 0 ? v.name: false;
            if (name) {
                if (val) {
                    if (name == 'facilities[]') {
                        facilities.push(val);
                    } else if (name == 'tags[]') {
                        tags.push(val);
                    } else {
                        if (query.has(name)) {
                            query.set(name, val);
                        } else {
                            query.append(name, val);
                        }
                    }
                } else {
                    if (query.has(name)) {
                        query.delete(name);
                    }
                }
            }
        });
        
        if (facilities.length > 0) {
            if (query.has('facilities')) {
                query.set('facilities', facilities.join(','));
            } else {
                query.append('facilities', facilities.join(','));
            }
        } else {
            if (query.has('facilities')) {
                query.delete('facilities');
            }
        }

        if (tags.length > 0) {
            if (query.has('tags')) {
                query.set('tags', tags.join(','));
            } else {
                query.append('tags', tags.join(','));
            }
        } else {
            if (query.has('tags')) {
                query.delete('tags');
            }
        }

        window.location.href = rooturl + 'index.php?' + query.toString();
    });
    
    $('.spbooking-accomodation-listing #accomodation-filtering-form .accomodation-reset').on('click', function(e){
        e.preventDefault();
        let reset_url = typeof($(this).data('url')) == 'string' && $(this).data('url').length > 0 ? $(this).data('url') : false;
        if (reset_url) {
            window.location.href = rooturl + 'index.php?' + reset_url;
        }
        return;
    });

    $('.spbooking-view-pakcages .spbooking-packages-filters-form').submit(function (e) {
        e.preventDefault();

        let data = $(this).serializeArray();
        let query = new URLSearchParams(window.location.search);

        data = typeof(data) == 'object' && data instanceof Array && data.length > 0 ? data : false;
        query = typeof (query) == 'object' && query ? query : false;
        
        let facilities = [];
        let tags = [];
        data.map((v) => {
            let val = typeof(v.value) == 'string' && v.value.length > 0 ? v.value : false;
            let name = typeof(v.name) == 'string' && v.name.length > 0 ? v.name: false;
            if (name) {
                if (val) {
                    if (name == 'facilities[]') {
                        facilities.push(val);
                    } else if (name == 'tags[]') {
                        tags.push(val);
                    } else {
                        if (query.has(name)) {
                            query.set(name, val);
                        } else {
                            query.append(name, val);
                        }
                    }
                } else {
                    if (query.has(name)) {
                        query.delete(name);
                    }
                }
            }
        });
        
        if (facilities.length > 0) {
            if (query.has('facilities')) {
                query.set('facilities', facilities.join(','));
            } else {
                query.append('facilities', facilities.join(','));
            }
        } else {
            if (query.has('facilities')) {
                query.delete('facilities');
            }
        }

        if (tags.length > 0) {
            if (query.has('tags')) {
                query.set('tags', tags.join(','));
            } else {
                query.append('tags', tags.join(','));
            }
        } else {
            if (query.has('tags')) {
                query.delete('tags');
            }
        }

        window.location.href = rooturl + 'index.php?' + query.toString();
    });

    //RESET Search
    $('.spbooking-view-pakcages .reset-button').on('click', function (e) {
        e.preventDefault();
        let reset_url = typeof ($(this).data('url')) == 'string' && $(this).data('url').length > 0 ? $(this).data('url') : false;
        if (reset_url) {
            window.location.href = rooturl + 'index.php?' + reset_url;
        }
        return;
    });


    // transports filter
    $('.spbooking-side-filter .spbooking-side-filters-form, .spbooking-top-filter .spbooking-side-filters-form').submit(function (e) {
        e.preventDefault();

        var search_queries = '';
        var searchitem = '&searching=' + 1;
        var rooturl = '';
        var menuid = '';
        var data = $(this).serializeArray();
        var view = 'transports';
        var tags = [];
        var categories = [];

        if (typeof data != 'undefined' && data.length) {
            data.forEach(function (value) {
                let v = value.value;

                if (v) {
                    if (value.name == 'tags[]') {
                        tags.push(v);
                    } else if (value.name == 'categories[]') {
                        categories.push(v);
                    } else if ( value.name != 'rooturl' && value.name != 'menuid' && value.name != 'view' && value.name != 'tags[]' && value.name != 'categories[]' ) {
                        let _query = '&' + value.name + '=' + value.value;
                        search_queries += _query;
                    }
                }

                if (value.name == 'view') {
                    view = v;
                }
                if (value.name == 'rooturl') {
                    rooturl = v;
                }
                if (value.name == 'menuid') {
                    menuid = v;
                }
            });

            if (tags.length > 0) {
                var tags = tags.join(',');
                let _query = '&' + 'tags' + '=' + tags;
                search_queries += _query;
            }

            if (categories.length > 0) {
                var categories = categories.join(',');
                let _query = '&' + 'categories' + '=' + categories;
                search_queries += _query;
            }
        }

        window.location = rooturl + 'index.php?option=com_spbooking&view=' + view + search_queries + searchitem + menuid + '';
        return false;
    });

    // view style switching
    $('.view-style-grid').on('click', function(e) {
        e.preventDefault();
        let query = new URLSearchParams(window.location.search);
        if (query.has('view_style')) {
            if (query.get('view_style') === 'grid') {
                return;
            }
            query.set('view_style', 'grid');
        } else {
            query.append('view_style', 'grid');
        }

        if (!query.has('option')) {
            query.append('option', 'com_spbooking');
        }
        
        if (!query.has('view')) {
            query.append('view', $(this).data('view'));
        }

        if ($(this).data('view') == 'packages') {
            if (!query.has('package_type')) {
                query.append('package_type', $(this).data('ptype'));
            }
        }

        if (!query.has('Itemid')) {
            query.append('Itemid', $(this).data('menuitemid'));
        }

        window.location.href = rooturl + 'index.php?' + query.toString();
    });
    
    $('.view-style-list').on('click', function(e) {
        e.preventDefault();
        let query = new URLSearchParams(window.location.search);
        if (query.has('view_style')) {
            if (query.get('view_style') === 'list') {
                return;
            }
            query.set('view_style', 'list');
        } else {
            query.append('view_style', 'list');
        }

        if (!query.has('option')) {
            query.append('option', 'com_spbooking');
        }
        
        if (!query.has('view')) {
            query.append('view', $(this).data('view'));
        }

        if ($(this).data('view') == 'packages') {
            if (!query.has('package_type')) {
                query.append('package_type', $(this).data('ptype'));
            }
        }
        
        if (!query.has('Itemid')) {
            query.append('Itemid', $(this).data('menuitemid'));
        }
        window.location.href = rooturl + 'index.php?' + query.toString();
    });

    //single date
    $('.spbooking-date-picker').flatpickr({
        mode: "single",
        altInput: true,
        altFormat: 'D, j M Y',
        minDate: "today",
        dateFormat: "Y-m-d"
    });
    
    $('.spbooking-invoice-date-picker').flatpickr({
        mode: "single",
        altInput: true,
        altFormat: 'D, j M Y',
        dateFormat: "Y-m-d"
    });




    // package tour activities
    $('.itenary-nav .nav-link').on('click', function(e) {
        e.preventDefault();
        let trigger = $(this).data('trigger');
        if (!$(this).hasClass('active')) {
            $(this).parents('.itenary-nav').find('.nav-link.active').removeClass('active').addClass('text-mute');
            $(this).addClass('active').removeClass('text-mute');
        }
        $('.spbooking-activity-content.show').removeClass('show');
        if (!$(trigger).hasClass('show')) {
            $(trigger).addClass('show');
        }
    });

    // Global accomodation book now button brings to rooms view

        $('.accomodation-global-booknow').on('click', function (e) {
            e.preventDefault();
            $('html, body').animate({ scrollTop: ($('#available-rooms').offset().top - 200) }, 'slow');
        });



    $('.print-invoice-button').on('click', function(e){
        e.preventDefault();
        $('#print-invoice').printThis({
            importCSS: true,
            importStyle: false,
            // loadCSS: rooturl + "components/com_spbooking/assets/css/printhelper.css",
            
        });
    });

    // icon click to copy
    $('.spbooking-icomoon-icons .icon-wrapper .click-to-copy').on('click', function(e) {
        let icon = $(this).siblings('input.original-icon');
        const el = document.createElement('textarea');
        el.value = icon.val();
        el.setAttribute('readonly', '');
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        document.body.appendChild(el);
        el.select();
        document.execCommand('copy');
        document.body.removeChild(el);

        let msg = $(this).siblings('.copy-msg');
        msg.show();
        setTimeout(() => {
            msg.fadeOut();
        }, 2000);
    });

    //Custom Select box
    if ($(".spbooking-select").length > 0) {
        $(document).on('click', function (e) {
            var selector = $('.spbooking-select');
            if (!selector.is(e.target) && selector.has(e.target).length === 0) {
                selector.find('ul').slideUp();
            }
        });

        $('select.spbooking-select').each(function (event) {
            $(this).hide();
            var $self = $(this);
            var spselect = '<div class="spbooking-select">';
            spselect += '<div class="spbooking-select-result">';
            spselect += '<span class="spbooking-select-text">' + $self.find('option:selected').text() + '</span>';
            spselect += ' <i class="fa fa-caret-down"></i>';
            spselect += '</div>';
            spselect += '<ul class="spbooking-select-dropdown">';

            $self.children().each(function (event) {
                if ($self.val() == $(this).val()) {
                    spselect += '<li class="active" data-val="' + $(this).val() + '">' + $(this).text() + '</li>';
                } else {
                    spselect += '<li data-val="' + $(this).val() + '">' + $(this).text() + '</li>';
                }
            });

            spselect += '</ul>';
            spselect += '</div>';
            $(this).after($(spselect));
        });

        $(document).on('click', '.spbooking-select', function (event) {
            $('.spbooking-select').not(this).find('ul').slideUp();
            $(this).find('ul').slideToggle();
        });

        $(document).on('click', '.spbooking-select ul li', function (event) {
            var $select = $(this).closest('.spbooking-select').prev('select');
            $(this).parent().prev('.spbooking-select-result').find('span').html($(this).text());
            $(this).parent().find('.active').removeClass('active');
            $(this).addClass('active');
            $select.val($(this).data('val'));
            $select.change();
        });
    }
    // End Select

    //payment method select
    $("input[name$='payment-method']").click(function () {
        var paymentMethod = $(this).val();
        $(".spbooking-payment .spbooking-payment-method").hide();
        $(".payment-method-" + paymentMethod).show();
    });
    // END payment

    // Custom Scroller
    if ($(".nicescrol").length>0){
        $(".nicescrol").niceScroll();
    }
});