function initSearch() {
    const searchBarApp = Vue.createApp({
        data() {
            return {
                fullSuggestionsList: [],
                filteredSuggetionsList: [],
                suggestionHighlightPos: -1,
                userInputtedSearchTerm: '',
                searchTerm: ''
            };
        },
        methods: {
            mountEvents() {
                $.getJSON(`/Umbraco/Api/Search/GetSearchSuggestions`, function (data) {
                    this.fullSuggestionsList = data;
                    this.searchTerm = this.getParameterByName('term');
                    $('#searchListingInput').val(this.searchTerm);
                }.bind(this));
            },
            searchEntry(e) {
                console.log('searchEntry');
                let term = e.target.value;
                if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 65 && e.keyCode <= 90) // only update highlighted term text if alphanumeric key pressed
                    || e.keyCode == 8) { // or backspace key
                    if (term && term.length > 2) {
                        this.filteredSuggetionsList = this.fullSuggestionsList.filter(element => element.toLowerCase().includes(term.toLowerCase())).slice(0, 6)
                        this.filteredSuggetionsList.forEach(function (part, index) {
                            let startOfTermPos = this[index].toLowerCase().indexOf(term.toLowerCase());
                            let endOfTermPos = startOfTermPos + term.length;
                            this[index] = this[index].substring(0, startOfTermPos) + '<span>' + this[index].substring(startOfTermPos, endOfTermPos) + '</span>' + this[index].substring(endOfTermPos);
                        }, this.filteredSuggetionsList);
                    } else if (term.length == 0) {
                        this.filteredSuggetionsList = [];
                    }
                }
            },
            submitSearch() {
                this.$refs.searchForm.submit()
            },
            hideSearchBar() {
                document.querySelector('#searchBarApp').style.display = "none";
            },
            selectSuggestionLink() {
                let suggestionLink = document.querySelector('[data-suggestionKey="suggestionLink' + this.suggestionHighlightPos + '"]');
                suggestionLink.classList.add('selected');
                this.$refs.searchInput.value = suggestionLink.textContent; // put text in search box
            },
            clearSuggestionSelection() {
                document.querySelectorAll('[data-suggestionKey]').forEach((element) => { // clear all selected styling
                    element.classList.remove('selected');
                });
            },
            keyDown() {
                if (this.suggestionHighlightPos + 1 < this.filteredSuggetionsList.length) { // do nothing if on last item
                    this.clearSuggestionSelection();

                    if (this.suggestionHighlightPos == -1) { // store user-inputted term so we can restore it if they key back up to search box
                        this.userInputtedSearchTerm = this.$refs.searchInput.value;
                    }

                    this.suggestionHighlightPos++;
                    this.clearSuggestionSelection();
                    this.selectSuggestionLink();
                }
            },
            keyUp() {
                this.suggestionHighlightPos--;

                this.clearSuggestionSelection();

                if (this.suggestionHighlightPos > -1) { // only move up if item selected within suggestionLinks (suggestionHighlightPos at 0 or more)
                    this.selectSuggestionLink();
                } else {
                    this.$refs.searchInput.value = this.userInputtedSearchTerm; // restore user-inputted term
                }

            },
            getParameterByName(name, url = window.location.href) {
                name = name.replace(/[\[\]]/g, '\\$&');
                var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            }
        },
        mounted: function () {
            this.mountEvents();
        },
        created() {
        }
    })

    if (window.location.pathname.split('/')[1] && window.location.pathname.split('/')[1].toLowerCase() == 'search') { // we're on search page so mount app to search page's search bar
        console.log('/Search');
        const vm = searchBarApp.mount('#searchBarAppListing');
    } else { // mount to nav search bar
        console.log('NOT /Search');
        const vm = searchBarApp.mount('#searchBarAppNav');
    }
}

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

initSearch();
