var function_handler = '';
var function_data = {};
var function_extra = '';
var ext_year_default = '';
var ext_year_reverse = '';

function cdp_get_savedVehicles() {
    savedVehicles = {};
    if (typeof (Storage) !== "undefined") {
        // Code for localStorage/sessionStorage.
    } else {
        // Sorry! No Web Storage support.
        cObjs = Cookies.getJSON();
    }

    jQuery.each(
        cObjs,
        function (key, value) {
            if (key.indexOf('vehicleSave_') != -1) {
                savedVehicles[key.replace('vehicleSave_', '')] = value;
            }
        }
    )
    return savedVehicles;
    // console.dir(cObjs);
}

function cdp_object_count(data) {
    var count = 0
    jQuery.each(
        data,
        function (index, value) {
            count++;
        }
    );
    return count;
}

function cdp_data_save(type, data) {
    if (typeof (Storage) !== "undefined") {
        // Code for localStorage/sessionStorage.
        storageName = type + 'Vehicles';
        storageData = localStorage.getItem(storageName);
        if (storageData) {

        } else {
            // localStorage.setItem("lastname", "Smith");
            nData = {};
            nData[data['vin']] = data;
        }
    } else {
        // Sorry! No Web Storage support.
        Cookies.set('CDPvehicleSave_' + vID, infoS, {expires: 30});
    }
}

jQuery(document).ready(
    function () {

        if (typeof Cookies !== 'undefined') {
            /****
             Vehicle Save
             ***/
            jQuery('#saved-vehicle-container').click(
                function () {
                    saveCount = parseInt(jQuery('#saved-vehicle-count').text());
                    if (saveCount > 0) {
                        window.open('/inventory/saved-vehicles', '_blank');
                    }
                }
            )

            jQuery('#inventory-wrapper').on(
                'click',
                '.inventory-vehicle-save',
                function (e) {
                    parentS = jQuery(e.target).parents('.vehicle-container');
                    vID = jQuery(parentS).attr('id');
                    saveCount = parseInt(jQuery('#saved-vehicle-count').text());
                    saveBox = jQuery(parentS).find('.inventory-vehicle-save');
                    vehicleS = infoS = {};
                    infoS['vin'] = vID;
                    jQuery(parentS).find('.vehicle-save').each(
                        function () {
                            if (jQuery(this).attr('data-name') == 'image') {
                                infoS[jQuery(this).attr('data-name')] = jQuery(this).attr('src');
                            } else if (jQuery(this).attr('data-name') == 'link') {
                                infoS[jQuery(this).attr('data-name')] = jQuery(this).attr('href');
                            } else {
                                infoS[jQuery(this).attr('data-name')] = jQuery(this).text();
                            }
                        }
                    );

                    if (jQuery(saveBox).hasClass('checked')) {
                        jQuery(saveBox).removeClass('checked');
                        jQuery(saveBox).find('.save-text').text('Save Vehicle');
                        jQuery(saveBox).find('.save-checkbox').text('');
                        Cookies.remove('CDPvehicleSave_' + vID);
                        saveCount--;
                    } else {
                        jQuery(saveBox).addClass('checked');
                        jQuery(saveBox).find('.save-text').text('Vehicle Saved');
                        jQuery(saveBox).find('.save-checkbox').text('X');

                        cdp_data_save('save', infoS);
                        Cookies.set('CDPvehicleSave_' + vID, infoS, {expires: 30});
                        saveCount++;
                    }

                    if (saveCount == 0) {
                        jQuery('#saved-vehicle-count-container').addClass('empty').removeClass('saved');
                    } else {
                        jQuery('#saved-vehicle-count-container').addClass('saved').removeClass('empty');
                    }
                    jQuery('#saved-vehicle-count').text(saveCount);
                }
            );

            /***
             Vehicle Compare
             ***/
            if (jQuery('#compare-button').length) {

                jQuery('.compare-item').hover(
                    function () {
                        jQuery(this).find('.compare-sub').slideDown();
                    },
                    function () {
                        jQuery(this).find('.compare-sub').slideUp();
                    }
                );
            }

            jQuery('#compare-button').click(
                function () {
                    compareCount = parseInt(jQuery('#compare-vehicle-count').text());
                    if (compareCount > 1) {
                        window.open('/inventory/compare-vehicles', '_blank');
                    } else {
                        jQuery('#compare-under-count').slideDown().delay(2000).slideUp();
                    }
                }
            )

            jQuery('#inventory-wrapper').on(
                'click',
                '.inventory-vehicle-compare',
                function (e) {
                    parentS = jQuery(e.target).parents('.vehicle-container');
                    vID = jQuery(parentS).attr('id');
                    compareCount = parseInt(jQuery('#compare-vehicle-count').text());
                    compareBox = jQuery(parentS).find('.inventory-vehicle-compare');
                    vehicleS = infoS = {};

                    if (compareCount < 5) {
                        jQuery(parentS).find('.vehicle-save').each(
                            function () { // Compare saves same data as Save Cookie
                                if (jQuery(this).attr('data-name') == 'image') {
                                    infoS[jQuery(this).attr('data-name')] = jQuery(this).attr('src');
                                } else if (jQuery(this).attr('data-name') == 'link') {
                                    infoS[jQuery(this).attr('data-name')] = jQuery(this).attr('href');
                                } else {
                                    infoS[jQuery(this).attr('data-name')] = jQuery(this).text();
                                }
                            }
                        );

                        if (jQuery(compareBox).hasClass('checked')) {
                            jQuery(compareBox).removeClass('checked');
                            jQuery(compareBox).find('.compare-text').text('Compare Vehicle');
                            jQuery(compareBox).find('.compare-checkbox').text('');
                            Cookies.remove('CDPvehicleCompare_' + vID);
                            compareCount--;
                            jQuery('.compare-' + vID).addClass('empty').removeClass('.compare-' + vID).children().remove(); // Remove Compare Image
                        } else {
                            jQuery(compareBox).addClass('checked');
                            jQuery(compareBox).find('.compare-text').text('Remove Compare');
                            jQuery(compareBox).find('.compare-checkbox').text('X');
                            // console.dir(infoS);
                            Cookies.set('CDPvehicleCompare_' + vID, infoS, {expires: 1});
                            compareCount++;
                            outPut = '<div class="compare-main"><img src="' + infoS['image'] + '" /></div>';
                            outPut += '<div class="compare-sub" style="display: none;">';
                            outPut += '<span class="compare-saleclass">' + infoS['saleclass'] + '</span>';
                            outPut += '<span class="compare-year">' + infoS['year'] + '</span>';
                            outPut += '</br><span class="compare-make">' + infoS['make'] + '</span>';
                            outPut += '<span class="compare-model">' + infoS['model'] + '</span>';
                            outPut += '</br><span class="compare-trim">' + infoS['trim'] + '</span>';
                            outPut += '</div>';
                            outPut += '<div class="compare-remove" data-key="' + vID + '">Remove [X]</div>';
                            jQuery('#compare-vehicle-container .compare-item.empty').first().removeClass('empty').addClass('item-' + compareCount + ' compare-' + vID).append(outPut);
                        }

                        if (compareCount == 0) {
                            jQuery('#compare-vehicle-container').addClass('empty').removeClass('visible');
                        } else {
                            jQuery('#compare-vehicle-container').addClass('visible').removeClass('empty');
                        }
                        jQuery('#compare-vehicle-count').text(compareCount);
                    } else {
                        jQuery('#compare-over-count').slideDown().delay(2000).slideUp();
                    }

                }
            );

            jQuery('#compare-vehicle-container').on(
                'click',
                '.compare-remove',
                function (e) {
                    vID = jQuery(e.target).attr('data-key');
                    compareCount = parseInt(jQuery('#compare-vehicle-count').text());
                    Cookies.remove('CDPvehicleCompare_' + vID);
                    jQuery('#' + vID).find('.compare-text').text('Compare Vehicle');
                    jQuery('#' + vID).find('.compare-checkbox').text('');
                    jQuery('#' + vID).find('.inventory-vehicle-compare').removeClass('checked');
                    jQuery('.compare-' + vID).removeClass('compare-' + vID).addClass('empty').children().remove();
                    compareCount--;
                    if (compareCount == 0) {
                        jQuery('#compare-vehicle-container').addClass('empty').removeClass('visible');
                    } else {
                        jQuery('#compare-vehicle-container').addClass('visible').removeClass('empty');
                    }
                    jQuery('#compare-vehicle-count').text(compareCount);
                }
            );
        }

        jQuery('#inventory-listing').removeClass('hide');

        // if (jQuery('#inventory-sidebar-mobile-search').length) {
        //     // jQuery('#inventory-sidebar-mobile-search').css({'top':+jQuery('#inventory-top-container').offset().top+'px', 'left':'0px'});
        // }

        // jQuery('#inventory-sidebar-mobile-search').click(
        //     function (e) {
        //
        //         if (!jQuery(e.target).hasClass('running')) {
        //             if (jQuery(e.target).hasClass('open')) {
        //                 jQuery(e.target).addClass('running');
        //                 jQuery(e.target).css({'display': 'none'});
        //                 //jQuery('#list-filters-container').removeAttr('style');
        //                 jQuery('#list-filters-container').animate(
        //                     {left: '-1000px'},
        //                     200,
        //                     function () {
        //                         jQuery('div#list-filters-container.sidebar-flamingo').removeClass('mobile');
        //                         jQuery('#inventory-sidebar-mobile-search').removeClass('open');
        //                         jQuery('#inventory-sidebar-mobile-search').text('Search');
        //                         jQuery('#inventory-sidebar-mobile-search').removeClass('running');
        //
        //                     }
        //                 )
        //                 jQuery(e.target).css({'display': 'block', 'left': '0px', 'right': 'inherit'});
        //                 if (!jQuery(e.target).hasClass('scroll')) {
        //                     jQuery('#inventory-sidebar-mobile-search').css({'position': 'relative', 'top': 'inherit'});
        //                 }
        //             } else {
        //                 jQuery(e.target).addClass('running');
        //                 //jQuery('#side-search-container').removeAttr('style');
        //                 jQuery('div#list-filters-container.sidebar-flamingo').addClass('mobile');
        //                 jQuery('#list-filters-container').css({'height': +(window.innerHeight - 50) + 'px'});
        //                 jQuery('#list-filters-container').animate(
        //                     {left: '0px'},
        //                     500,
        //                     function () {
        //                         jQuery('#inventory-sidebar-mobile-search').removeClass('running');
        //                         jQuery(e.target).css({'display': 'block', 'left': 'inherit', 'right': '0px'});
        //                         jQuery(e.target).addClass('open');
        //                         jQuery(e.target).html('C</br>l</br>o</br>s</br>e</br></br>S</br>e</br>a</br>r</br>c</br>h');
        //                     }
        //                 );
        //                 jQuery('#inventory-sidebar-mobile-search').css({'position': 'fixed', 'top': '0px'});
        //             }
        //         }
        //
        //     }
        // );

        // reset search
        jQuery('#listing-clear-search').click(
            function () {
                function_handler = 'update';
                function_extra = 'clear';
                get_all_input_params();
                keys_to_keep = ['saleclass']
                if (function_data.hasOwnProperty('certified')) {
                    delete function_data['certified'];
                }
                if (function_data.hasOwnProperty('saleclass')) {
                    if (function_data['saleclass'] === 'certified') {
                        function_data['saleclass'] = 'Used'
                    }
                }
                let fn_keys = Object.keys(function_data);
                let remove_keys = fn_keys.filter(x => !keys_to_keep.includes(x));
                for (let index in remove_keys) {
                    let key = remove_keys[index];
                    delete function_data[key]
                }
                extender_update_parameters(function_data)
                extender_ajax_handler();
                jQuery('.search-content.from, .search-content.to').find('option:eq(0)').prop('selected', true);
                jQuery('.range-slider').each(function () {
                    let name = jQuery(this).attr('data-name');
                    let pre = '';
                    if (name === 'price') {
                        pre = '$'
                    }
                    let min = jQuery(this).slider('option', 'min');
                    let max = jQuery(this).slider('option', 'max');
                    jQuery(this).slider('option', 'values', [min, max]);
                    jQuery('#' + name + '-range-values').val(pre + min + ' - ' + pre + max);
                });
                jQuery('.dropdown-item input[type="checkbox"]:checked').each(function () {
                    jQuery(this).prop('checked', false);
                });
                jQuery('.select-text').text('Features');
            }
        );

        jQuery('#cardealerpress-inventory').on(
            'keypress',
            '.input-search',
            function (e) {
                if (e.which == 13 || e.keyCode == 13) {
                    jQuery(e.target).blur();
                }
            }
        );

        jQuery('#list-filters-container div.text-search-button').click(
            function () {
                jQuery('input.text-input').change();
            }
        );

        jQuery('span.dropdown-box-close').click(
            function (e) {
                jQuery(e.target).parents('.search-item.open').removeClass('open').children('.search-item-dropdown').slideUp('fast');
            }
        );

        jQuery('#search-item-container').on(
            'click',
            'li.data-item',
            function (e) {
                tag = jQuery(e.target).parent().attr('data-tag');
                value = jQuery(e.target).attr('data-value');
                jQuery('input.input-' + tag).attr('value', value).focus().change();
                jQuery('input.input-' + tag).siblings('input').delay(3000).focus();
            }
        );

        jQuery('#side-search-item-container').on(
            'click',
            'li.data-item',
            function (e) {
                tag = jQuery(e.target).parent().attr('data-tag');
                value = jQuery(e.target).attr('data-value');
                jQuery('input.input-' + tag).attr('value', value).focus().change().siblings('input').focus();
            }
        );

        jQuery('input.data-list').focus(
            function (e) {
                tag = jQuery(e.target).attr('data-name');
                if (tag == 'year_to' || tag == 'year_from') {
                    ext_reverse_list_year(tag);
                }
                jQuery(e.target).addClass('active').siblings('ul').attr('data-tag', tag).addClass(tag);
            }
        );

        jQuery('input.data-list').focusout(
            function (e) {
                tag = jQuery(e.target).attr('name');
                jQuery(e.target).removeClass('active').siblings('ul').removeClass(tag);
            }
        );

        function ext_reverse_list_year(tag) {
            if (ext_year_default.length == 0) {
                ext_year_default = jQuery('#year-range-list li');
            }
            if (ext_year_reverse.length == 0) {
                var list = document.getElementById('year-range-list');
                var i = list.childNodes.length;
                while (i--) {
                    list.appendChild(list.childNodes[i]);
                }
                ext_year_reverse = jQuery('#year-range-list li');
            }

            if (tag == 'year_from') {
                jQuery('#year-range-list').append(ext_year_reverse);
            } else {
                jQuery('#year-range-list').append(ext_year_default);
            }
            jQuery('#year-range-list').addClass(tag);
        }

        function get_query() {
            var url = window.location.search;
            var qs = url.substring(url.indexOf('?') + 1).split('&');
            if (url.length) {
                for (var i = 0, result = {}; i < qs.length; i++) {
                    qs[i] = qs[i].split('=');
                    result[qs[i][0]] = decodeURIComponent(qs[i][1]);
                }
                return result;
            } else {
                return [];
            }
        }

        function merge_with_existing_params(data) {
            let params = get_query();
            if (!params.length) {
                function_data = jQuery.extend({}, params, function_data);
            }
        }

        function filter_geo_params() {
            if (function_data['geo_state'] == 0 && function_data['geo_city']) {
                function_data['geo_city'] = 0
            }
        }

        function get_all_input_params() {
            jQuery('.input-action').each(
                function (e) {
                    function_data[jQuery(this).attr('name')] = jQuery(this).val();
                    if (function_data['make'] === '0') {
                        function_data['make'] = 'all';
                    }
                }
            )
            merge_with_existing_params(function_data);
            filter_geo_params();
            function_data = removeEmpty(function_data);
            // extender_update_parameters( function_data )
        }

        function removeEmpty(obj) {
            return Object.fromEntries(
                Object.entries(obj).filter(
                    ([_, v]) => v != null && v !== '0' && v !== '' && v !== 'Model' && v !== 'Trim' && v !== 'undefined'
                )
            );
        }

        jQuery('.input-action').change(
            function (e) {
                function_handler = 'update';
                function_data[jQuery(e.target).attr('name')] = jQuery(e.target).val();
                // Leaving this here for now.
                // get_all_input_params();
                extender_ajax_handler();
                function_data = {};
                function_extra = '';
            }
        );


        jQuery(".range-slider").slider({
            slide: function (event, ui) {
                let name = jQuery(this).attr('data-name');
                let from = ui.values[0];
                let to = ui.values[1];
                function_handler = 'update';
                function_data[name + '_from'] = from;
                function_data[name + '_to'] = to;
                extender_ajax_handler();
                function_data = {};
                function_extra = '';
            }
        });

        jQuery('span.input-action').click(
            function (e) {
                function_handler = 'update';
                function_data[jQuery(e.target).attr('name')] = jQuery(e.target).val();
                extender_ajax_handler();
                function_data = {};
            }
        );

        jQuery('#search-tag-container').on(
            'click',
            '.remove-action',
            function (e) {
                let name = jQuery(this).attr('data-name');
                if (name === 'tags') {
                    const checked_names = jQuery('input[type="checkbox"]:checked').map(function () {
                        return this.name;
                    }).get();
                    jQuery('.dropdown-item input[type="checkbox"]:checked').each(function () {
                        jQuery(this).prop('checked', false);
                    });
                    jQuery('.select-text').text('Select Options'); // reset tag selections
                }
                jQuery(this).remove(); // remove from Filters list
                remove_from_search_data(name); // remove from inventory-search-data
                removeUrlParameter(name); // remove from url
                function_handler = 'remove';
                function_data[0] = name;
                extender_clear_data(function_data[0]);
                extender_ajax_handler();
                //function_data = {'tags': checked_names};
                function_data = {};
            }
        );

        function remove_from_search_data(key) {
            jQuery('#inventory-search-data').children().each(
                function () {
                    if (jQuery(this).attr('data-key') === key) {
                        jQuery(this).remove();
                    }
                }
            );
        }

        function removeUrlParameter(parameterName) {
            const url = new URL(window.location.href); // Get the current URL
            const params = url.searchParams; // Access the URLSearchParams object

            // Check if the parameter exists and delete it
            if (params.has(parameterName)) {
                params.delete(parameterName);
                // Update the URL in the browser's history without reloading the page
                window.history.replaceState({}, document.title, url.toString());
            }
        }

        jQuery('#inventory-vehicles-container').on(
            'click',
            '.price-form',
            function (e) {
                jQuery('#form-active').remove();
                function_handler = 'form';
                function_data['vin'] = jQuery(this).attr('data-key');
                var form_data = {};
                jQuery('#' + function_data['vin'] + ' .form-value').each(
                    function () {
                        form_data[jQuery(this).attr('data-name')] = jQuery(this).text();
                    }
                );
                function_data['hooks'] = form_data;
                extender_ajax_handler();
                jQuery('html, body').animate({scrollTop: jQuery('#' + jQuery(this).attr('data-key')).offset().top}, 1000);
                // jQuery(document).scrollTop( , 2000 );
                function_data = {};
            }
        );

        jQuery('#inventory-vehicles-container').on(
            'click',
            '#form-close',
            function (e) {
                jQuery(e.target).parent().remove();
            }
        );

        jQuery('.inventory-pagination-container').on(
            'click',
            '.input-page-action',
            function (e) {
                if (jQuery(this).parents('.inventory-pagination-container.pagination-anchor').length) {
                    jQuery(document).scrollTop(jQuery('#pagination-anchor').offset().top);
                }
                let control = jQuery(e.target).attr('data-name');
                let element = jQuery(e.target).parents('.pagination-container').find('.pagination-current');
                let page = element.attr('value');
                let input_min = element.attr('min');
                let input_max = element.attr('max');
                if (control == 'next') {
                    page++;
                } else {
                    page--;
                }
                if (page >= input_min && page <= input_max) {
                    jQuery('.input-page-action').attr('value', page);
                    jQuery(e.target).parents('.pagination-container').find('.pagination-current').change();
                }
            }
        );

        jQuery('.inventory-pagination-container').on(
            'change',
            'input.input-page-action',
            function (e) {
                if (jQuery(this).parents('.inventory-pagination-container.pagination-anchor').length) {
                    jQuery(document).scrollTop(jQuery('#pagination-anchor').offset().top);
                }
                function_handler = 'page';
                function_data['page'] = jQuery(this).val();
                jQuery('.input-page-action').attr('value', jQuery(this).attr('value'));
                if (jQuery('.inventory-vehicle-page.page-' + function_data['page']).length) {
                    jQuery('.inventory-vehicle-page.active').removeClass('active');
                    jQuery('.inventory-vehicle-page.page-' + function_data['page']).addClass('active');
                    function_handler = 'pageURL';
                    // get_all_input_params()
                    extender_ajax_handler();
                } else {
                    // get_all_input_params();
                    extender_ajax_handler();
                }
                function_data = {};
            }
        );

        jQuery('.search-action .search-item-label').click(
            function () {
                jQuery(this).parent().siblings('.open').removeClass('open').children('.search-item-dropdown').not('.mobile.ignore-slide').slideUp('fast');
                if (jQuery(this).parent().hasClass('open')) {
                    jQuery(this).siblings('.search-item-dropdown').not('.mobile.ignore-slide').slideUp('fast');
                    jQuery(this).parent().removeClass('open');
                } else {
                    jQuery(this).parent().addClass('open');
                    jQuery(this).siblings('.search-item-dropdown').not('.mobile.ignore-slide').slideDown('800');
                    jQuery(this).parent().find('input:first-child').focus();
                }
            }
        );

        jQuery('.search-action .side-search-item-label').click(
            function () {
                if (jQuery(this).parent().hasClass('open')) {
                    jQuery(this).siblings('.side-search-item-dropdown').not('.mobile.ignore-slide').slideUp('fast');
                    jQuery(this).parent().removeClass('open');
                } else {
                    jQuery(this).parent().addClass('open');
                    jQuery(this).siblings('.side-search-item-dropdown').not('.mobile.ignore-slide').slideDown('800');
                    jQuery(this).parent().find('input:first-child').focus();
                }
            }
        );

        jQuery('#search-mobile-banner').click(
            function () {
                if (jQuery(this).hasClass('mobile-show')) {
                    jQuery('#search-mobile-banner').removeClass('mobile-show');
                    jQuery('#list-filters-container').slideUp('fast');
                    jQuery('#search-mobile-banner .filter-label').text('Filters');
                } else {
                    jQuery('#search-mobile-banner').addClass('mobile-show');
                    jQuery('#list-filters-container').slideDown('800');
                }
            }
        );

        jQuery('#search-mobile-button').click(
            function () {
                jQuery('#search-item-container').children().removeClass('mobile-show').not('.ignore-slide').slideUp('fast');
                jQuery('#top-search-container').removeClass('unfixed');
            }
        );

        jQuery('.tab-name').click(
            function (e) {
                if (!jQuery(e.target).hasClass('active')) {
                    var content_id = jQuery(e.target).attr('id') + '-content';
                    jQuery(e.target).siblings('.active').removeClass('active');
                    jQuery('#' + content_id).siblings('.active').removeClass('active');
                    jQuery(e.target).addClass('active');
                    jQuery('#' + content_id).addClass('active');
                }
            }
        );

        jQuery('.tab-mobile-button').click(
            function (e) {
                if (jQuery(e.target).hasClass('active')) {
                    jQuery(e.target).children('span').addClass('open').removeClass('close');
                    jQuery(e.target).removeClass('active');
                    jQuery(e.target).siblings('.tab-content-inner').removeClass('active');
                } else {
                    jQuery(e.target).children('span').addClass('close').removeClass('open');
                    jQuery(e.target).addClass('active');
                    jQuery(e.target).siblings('.tab-content-inner').addClass('active');
                    jQuery('html, body').animate({scrollTop: jQuery(e.target).offset().top}, 2000);
                }
            }
        );

        // Collapse Toggle
        jQuery('.collapse-toggle').click(
            function () {
                toggle = jQuery(this).attr('data-name');
                if (jQuery('.collapse-divider.' + toggle).hasClass('opened')) {
                    jQuery('.collapse-divider.' + toggle).removeClass('opened').slideUp('slow');
                } else {
                    jQuery('.collapse-divider.' + toggle).addClass('opened').slideDown('slow');
                }
            }
        );

        jQuery(document).click(
            function (e) {
                var container = jQuery('#search-item-container');
                if (!container.is(e.target) && container.has(e.target).length === 0) {
                    container.find('.open').removeClass('open').children('.search-item-dropdown').slideUp('fast');
                }
            }
        );

        window.onscroll = extender_scroll_Handler;

        if (jQuery('#inventory-detail').length) {

            var secondarySlider = new Splide(
                '#secondary-slider',
                {
                    fixedWidth: 120,
                    height: 80,
                    gap: 10,
                    rewind: true,
                    cover: true,
                    pagination: false,
                    arrows: false,
                    isNavigation: true,
                    focus: 'center',
                    autoplay: true,
                    breakpoints: {
                        '600': {
                            fixedWidth: 66,
                            height: 40,
                        }
                    }
                }
            ).mount();
            var primarySlider = new Splide(
                '#primary-slider',
                {
                    type: 'loop',
                    width: '100%',
                    heightRation: 0.8,
                    pagination: false,
                    cover: true,
                    arrows: true,
                    loop: true,
                }
            );

            primarySlider.sync(secondarySlider).mount();
            var slideIndex = 1;
            showSlides(slideIndex);
        } // end detail
    }
);

// lightbox detail page
function openModal() {
    if (window.innerWidth > 600) {
        document.getElementById("detailLightBox").style.display = "block";
        document.getElementById("detailLightBox-background").style.display = "block";
    }
}

function closeModal() {
    document.getElementById("detailLightBox").style.display = "none";
    document.getElementById("detailLightBox-background").style.display = "none";
}

function plusSlides(n) {
    showSlides(slideIndex += n);
}

function currentSlide(n) {
    showSlides(slideIndex = n);
}

function showSlides(n) {
    var i;
    var slides = document.getElementsByClassName("lightBoxSlides");
    if (n == 1) {
        slideIndex = 1
    }
    if (n > slides.length) {
        slideIndex = 1
    }
    if (n < 1) {
        slideIndex = slides.length
    }
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    for (i = 0; i < slides.length; i++) {
        slides[i].className = slides[i].className.replace(" active", "");
    }
    slides[slideIndex - 1].style.display = "block";
    slides[slideIndex - 1].className += " active";
}

// Clear Fields
function extender_clear_data(class_name) {
    if (jQuery('.input-' + class_name).attr('type') == 'radio') {
        jQuery('.input-' + class_name).attr('checked', false);
    } else {
        //jQuery('.input-' + class_name).attr('value', '');
        jQuery('.input-' + class_name).prop('checked', false);
    }
}

// Get Parameters
function extender_get_parameters() {
    var data = {};
    jQuery('#inventory-search-data').children().each(
        function () {
            data[jQuery(this).attr('data-key')] = jQuery(this).attr('data-value');
        }
    );
    return data;
}

// Update Parameters.
function extender_update_parameters(parameters) {
    jQuery('#inventory-search-data').children().remove();
    jQuery.each(
        parameters,
        function (key, value) {
            jQuery('#inventory-search-data').append('<div data-key="' + key + '" data-value ="' + value + '"></div>')
        }
    )
}

function extender_append_inventory_search_data_parameters(parameters) {
    jQuery.each(
        parameters,
        function (key, value) {
            jQuery('#inventory-search-data').append('<div data-key="' + key + '" data-value ="' + value + '"></div>')
        }
    )
}

// Repopulate Dropdowns
function extender_repopulate_dropdowns(new_data) {
    let drop_down_data = new_data['content']['dropdown_data'];
    jQuery('#list-filters-container select').each(
        function () {
            if (!jQuery(this).hasClass('ignore')) {
                jQuery(this).children().remove();
                jQuery(this).prop('disabled', true);
            }
        }
    )
    jQuery.each(
        drop_down_data,
        function (key, values) {
            jQuery('.input-action.select-' + key).empty();
            let list = '<option value="0">All ' + capitalize_each_word(key.replace(/_/, " ")) + '</option>';
            jQuery.each(
                values['data'],
                function (id, item) {
                    if (values['needle'] == item) {
                        selected = 'selected';
                    } else {
                        selected = '';
                    }
                    if (values['dataCount'] && values['dataCount'][item]) {
                        count = '(' + values['dataCount'][item] + ')';
                    } else {
                        count = '';
                    }
                    if (item !== '') {
                        list += '<option value="' + item + '" ' + selected + '>' + item + ' ' + count + '</option>';
                    }
                }
            )
            jQuery('.input-action.select-' + key).append(list);
            jQuery('.input-action.select-' + key).prop('disabled', false);
        }
    )
}

function extender_repopulate_sliders(new_data) {
    const drop_down_data = new_data['content']['dropdown_data'];
    const possible_sliders = ['price', 'year', 'odometer'];
    const cleaned_keys = Object.keys(new_data.parameters).map(key =>
        key.replace(/(_from|_to)$/, '')
    );
    const unique_params = [...new Set(cleaned_keys)];
    const final_params = unique_params.filter(name =>
        possible_sliders.includes(name)
    );
    const update_sliders = possible_sliders.filter(
        slider => !final_params.includes(slider)
    );
    // update the sliders that weren't changed
    jQuery.each(update_sliders, function (key, value) {
        if (jQuery(`#${value}-range-slider`).length) {
            let data_to = drop_down_data[value + '_to']?.data || [];
            let data_from = drop_down_data[value + '_from']?.data || [];
            let pre = (value === 'price') ? '$' : '';
            let min, max;
            if (data_to.length === 1 || data_from.length === 1) {
                min = data_from.length ? data_from[0] : 0;
                max = data_to.length ? data_to[0] : min;
            } else {
                min = data_from.length ? data_from[0] : 0;
                max = data_from.length > 1 ? data_from[data_from.length - 1] : min;
            }
            jQuery(`#${value}-range-values`).val(`${pre}${min} - ${pre}${max}`);
            jQuery(`#${value}-range-slider`).slider('values', [min, max]);
        }
    });
    // update the slider that was changed
    jQuery.each(
        final_params,
        function (key, value) {
            let min = drop_down_data[value + '_from']?.needle || [];
            let max = drop_down_data[value + '_to']?.needle || [];
            let pre = (value === 'price') ? '$' : '';
            if (max.length === 0 || min.length === 0) {
                let data_from = drop_down_data[value + '_from']?.data || [];
                if (max.length === 0) {
                    max = data_from.length > 1 ? data_from[data_from.length - 1] : min;
                }
                if (min.length === 0) {
                    min = data_from.length ? data_from[0] : 0;
                }
            }
            jQuery(`#${value}-range-values`).val(`${pre}${min} - ${pre}${max}`)
            jQuery(`#${value}-range-slider`).slider('values', [min, max]);
        }
    )
}

// Repopulate Remove Tags
function extender_repopulate_remove_tags(new_tags) {
    jQuery('#search-tag-container').children().remove();
    jQuery('#search-tag-container').append(new_tags);
}

// Update Inventory Count
function extender_update_inventory_count(count) {
    jQuery('.search-vehicle-count').text(count);
}

// Update Inventory List
function extender_update_inventory(inventory) {
    jQuery('.inventory-vehicle-page').remove();
    jQuery('#inventory-vehicles-container').append(inventory);
}

// Ajax load remove style
function extender_ajax_worker_load() {
    jQuery('#inventory-vehicles-container').addClass('searching');
    jQuery('#search-item-container').addClass('searching');
    jQuery('#inventory-ajax-icon').addClass('searching');
}

function extender_ajax_worker_remove() {
    jQuery('#inventory-vehicles-container').removeClass('searching');
    jQuery('#search-item-container').removeClass('searching');
    jQuery('#inventory-ajax-icon').removeClass('searching');
}

// Update Pagination
function extender_update_pagination(content) {
    jQuery('.inventory-pagination-container').children().remove();
    jQuery('.inventory-pagination-container').append(content);
}

// AJAX Call
function extender_ajax_handler() {
    // console.log( " ===== function_handler ", function_handler );
    // console.log( "function_data ", function_data );
    // console.log( "extender_get_params ", extender_get_parameters() );
    // console.log( "extra ", function_extra );
    jQuery('#search-tag-container').css('display', 'block'); // Show 'filters' on dropdown update.
    return jQuery.ajax(
        {
            url: ajax_object.url,
            data: {
                'action': 'extender_ajax_handler', 'handler': function_handler, 'data': function_data,
                'parameters': extender_get_parameters(), 'extra': function_extra, 'nonce': ajax_object.nonce,
            },
            dataType: 'json',
            beforeSend: function () {
                extender_ajax_worker_load();
            },
            complete: function () {
                extender_ajax_worker_remove();
            },
            success: function (data) {
                if (data['key'] === 'form') {
                    jQuery('#' + data['id'] + ' .bottom-form-holder').append(data['content']['form']);
                } else if (data['key'] == 'pageURL') {
                    window.history.pushState('', '', window.location.protocol + '//' + window.location.host + data['url']);
                } else if (data['key'] === 'page') {
                    jQuery('.inventory-vehicle-page.active').removeClass('active');
                    jQuery('#inventory-vehicles-container').append(data['content']['inventory']);
                    if (!jQuery.isEmptyObject(data['ajax_script'])) {
                        jQuery('#ajax-script-wrapper').children().remove();
                        jQuery('#ajax-script-wrapper').append(data['ajax_script']);
                    }
                    window.history.pushState('', '', window.location.protocol + '//' + window.location.host + data['url']);
                } else {
                    //console.log( 'success data: ' , data );
                    extender_update_parameters(data['parameters']);
                    if (!jQuery.isEmptyObject(data['content']['dropdown_data'])) {
                        extender_repopulate_dropdowns(data);
                        extender_repopulate_sliders(data);
                    }
                    if (!jQuery.isEmptyObject(data['content']['tag_data'])) {
                        extender_update_tag_data(data['content']['tag_data']);
                        initMultiSelects();
                    }
                    if (!jQuery.isEmptyObject(data['content']['top_banner'])) {
                        jQuery('#cdp-banner-top-container').children().remove();
                        jQuery('#cdp-banner-top-container').append(data['content']['top_banner']);
                    }
                    if (!jQuery.isEmptyObject(data['content']['bottom_banner'])) {
                        jQuery('#cdp-banner-bottom-container').children().remove();
                        jQuery('#cdp-banner-bottom-container').append(data['content']['bottom_banner']);
                    }
                    if (!jQuery.isEmptyObject(data['ajax_script'])) {
                        jQuery('#ajax-script-wrapper').children().remove();
                        jQuery('#ajax-script-wrapper').append(data['ajax_script']);
                    }
                    extender_repopulate_remove_tags(data['content']['remove_tags']);
                    extender_update_inventory_count(data['content']['inventory_count']);
                    extender_update_pagination(data['content']['pagination']);
                    extender_update_inventory(data['content']['inventory']);
                    window.history.pushState('', '', window.location.protocol + '//' + window.location.host + data['url']);
                    populate_title_tag(data);
                    if (Object.getOwnPropertyNames(extender_get_parameters()).length === 1) {
                        jQuery('#listing-clear-search').css('display', 'none'); // Show 'reset search' on dropdown update.
                    } else {
                        jQuery('#listing-clear-search').css('display', 'block'); // Hide if there are no params.
                    }
                    jQuery('#search-mobile-banner .filter-label').text('View Results');
                }
            },
            error: function (xhr, status, error) {
                // alert('Ajax call failed.');
                // alert(error);
            }
        }
    );
}

function is_needle_empty(obj) {
    for (let main_key in obj) {
        for (let key1 in obj[main_key]) {
            if ('needle' === key1) {
                let value = obj[main_key][key1];
                if (value === "") {
                    delete obj[main_key]
                }
            }
        }
    }
    return obj;
}

function remove_empty_params(url) {
    let keys = []
    let parsed_url = url.split('?')[1]
    let params = new URLSearchParams(parsed_url)
    for (const key of params.keys()) {
        keys.push(key);
    }
    for (let key of keys) {
        if (params.get(key) === '') {
            params.delete(key)
        }
    }
    let new_url = url.split('?')[0] + '?' + params.toString()
    return new_url;
}

function populate_title_tag(data) {
    let params = data['parameters'] || [];
    if (params.hasOwnProperty('saleclass')) {
        saleclass = params['saleclass'];
    } else {
        saleclass = 'used';
    }
    if (params['make'] == null) {
        make = ' selection';
    } else {
        make = ' ' + params['make'] + '\'s';
    }
    title = 'Select from our ' + saleclass + make + '!';
    jQuery('#list-page-title').text(title);
}

function extender_scroll_Handler() {
    if (jQuery('#compare-vehicle-container.visible').length) {
        var mainContainer = jQuery('.inventory-main-container');
        var mainHeight = mainContainer.outerHeight() + 200;
        var container = document.getElementById('compare-vehicle-container');
        var contentHeight = container.offsetHeight;
        var yOffset = window.pageYOffset;
        var windowY = yOffset + window.innerHeight;
        var bottomOffset = windowY - (contentHeight * 2);

        if (windowY > mainHeight) {
            jQuery(container).css({'bottom': 'inherit', 'position': 'relative'});
        } else {
            jQuery(container).css({'bottom': '0px', 'position': 'fixed', 'left': '50%', 'margin-left': '-460px'});
        }

        jQuery('#compare-button').position(
            {
                my: 'center',
                at: 'center',
                of: '#compare-vehicle-count-container'
            }
        );
    }

    if (jQuery('#top-search-container').length) {
        var container = document.getElementById('inventory-listing');
        var contentTop = jQuery(container).offset().top + 25;
        var contentHeight = container.offsetHeight + 350;
        var yOffset = window.pageYOffset;
        var windowY = yOffset + window.innerHeight;

        if (contentTop <= yOffset) {
            jQuery('#top-search-container').addClass('scroll');
            jQuery('#inventory-ajax-icon').addClass('scroll');
        } else {
            jQuery('#top-search-container').removeClass('scroll');
            jQuery('#inventory-ajax-icon').removeClass('scroll');
        }
    }

    if (jQuery('#list-filters-container.sidebar-flamingo').length) {
        var container = document.getElementById('inventory-vehicles-container');
        var contentTop = jQuery(container).offset().top;
        var contentHeight = container.offsetHeight + 350;
        var yOffset = window.pageYOffset;
        var windowY = yOffset + window.innerHeight;
        var sidebarW = jQuery('#list-filters-container.sidebar-flamingo').width();
        var sidebarL = jQuery('#list-filters-container.sidebar-flamingo').offset().left;
        var sidebarB = jQuery(document).height() - (jQuery(container).offset().top + container.offsetHeight);
        if (window.innerHeight < 500) {
            var sidebarH = window.innerHeight;
        } else {
            var sidebarH = window.innerHeight - sidebarB;
        }

        var sidebarM = jQuery('#inventory-top-container').offset().top - yOffset;

        if (contentTop <= yOffset) {
            jQuery('#side-search-container').addClass('scroll');
            jQuery('#inventory-ajax-icon').addClass('scroll');
            if (!jQuery('#list-filters-container.sidebar-flamingo').hasClass('mobile')) {
                // jQuery('#side-search-container').css({'position':'fixed','width':+sidebarW+'px','left':+sidebarL+'px','top':'0','height':+sidebarH,'overflow-y':'scroll','margin-bottom':+sidebarB});
            }
            jQuery('#inventory-sidebar-mobile-search').addClass('scroll');
            jQuery('#inventory-sidebar-mobile-search').css({'position': 'fixed', 'top': '0px'});
        } else {
            jQuery('#side-search-container').removeClass('scroll');
            jQuery('#inventory-ajax-icon').removeClass('scroll');
            if (!jQuery('#list-filters-container.sidebar-flamingo').hasClass('mobile')) {
                jQuery('#side-search-container').removeAttr("style");
            }
            jQuery('#inventory-sidebar-mobile-search').removeClass('scroll');
            jQuery('#inventory-sidebar-mobile-search').css({'position': 'relative', 'top': 'inherit'});
        }
    }

    if (jQuery('#inventory-detail-banner').length) {
        var container = document.getElementById('inventory-detail');
        var contentTop = jQuery(container).offset().top + 25;
        var contentHeight = container.offsetHeight + 350;
        var yOffset = window.pageYOffset;
        var windowY = yOffset + window.innerHeight;

        if (contentTop <= yOffset) {
            jQuery('#inventory-detail-banner').addClass('scroll');
        } else {
            jQuery('#inventory-detail-banner').removeClass('scroll');
        }
    }
}

String.prototype.extender_capitalizeFirstLetter = function () {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function capitalize_each_word(str) {
    return str.replace(/\b\w/g, function (char) {
        return char.toUpperCase();
    });
}
