var _____WB$wombat$assign$function_____=function(name){return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name))||self[name];};if(!self.__WB_pmw){self.__WB_pmw=function(obj){this.__WB_source=obj;return this;}}{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opens = _____WB$wombat$assign$function_____("opens");
let searchBy = 'city'; // default search type
const searchByNavs = document.querySelectorAll('.search-card__nav');
let searchInput = document.querySelector('#search-input');
searchByNavs.forEach(el => {
    el.addEventListener('click', (e) => {
        document.querySelectorAll('.search-card__nav').forEach(el => el.classList.remove('active'));
        const li = e.target;
        li.classList.add('active');
        searchBy = li.dataset.searchType;
        document.querySelector('#search-input').placeholder = li.dataset.placeholder;
        searchInput.value = '';
    })
})


// original search bar
// const searchType = document.querySelectorAll('.search-by');
// searchType.forEach(el => {
//     if (el.checked) {
//         searchBy = el.value
//     }

//     if (searchBy === 'city') {
//         document.querySelector('#search-input').placeholder = 'Search for City or Region'
//     } 

//     if (searchBy === 'title') {
//         document.querySelector('#search-input').placeholder = 'Search for School Name'
//     }
    
//     if (searchBy === 'zip') {
//         document.querySelector('#search-input').placeholder = 'Search by Zip Code'
//     } 

//     el.addEventListener('click', (e) => {
//         searchBy = e.target.value;

//         if (searchBy === 'city') {
//             document.querySelector('#search-input').placeholder = 'Search for City or Region'
//         } 

//         if (searchBy === 'title') {
//             document.querySelector('#search-input').placeholder = 'Search for School Name'
//         }
        
//         if (searchBy === 'zip') {
//             document.querySelector('#search-input').placeholder = 'Search by Zip Code'
//         } 
//     })
// })          


$(function () {
    $.widget( "custom.catcomplete", $.ui.autocomplete, {
        _create: function() {
            this._super();
            this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
        },
        _renderMenu: function( ul, items ) {

            if (items.length == 0) {
                alert("empty array")
            }

            let that = this;
            currentCategory = "";
            $.each( items, function( index, item ) {
                let li;
                if ( item.category != currentCategory) {
                    if (item.category === "City") {
                        ul.append( "<li class='ui-autocomplete-category'>" + "Location" + "</li>");
                        currentCategory = item.category;
                    }

                    if (item.category === "Title") {
                        ul.append( "<li class='ui-autocomplete-category'>" + "School Name" + "</li>");
                        currentCategory = item.category;
                    }

                    if (item.category === "Zip") {
                        ul.append( "<li class='ui-autocomplete-category'>" + "Zip / Postal Code" + "</li>");
                        currentCategory = item.category;
                    }
                }

                li = that._renderItemData( ul, item);
                if ( item.category ) {
                    li.attr( "aria-label", item.category + " : " + item.label)
                }
            });
        }
    });

    $('#search-input').catcomplete({
        source: async function(req, res) {


            let uniqueCities = [];
            let listings = [];
            let zipResults = [];
            let output = []; // final output object to be send to autocomplete

            

            let data = await fetch(`/search?query=${req.term}&searchFilter=${searchBy}`)
                .then(results => results.json())
                .then(results => results.map(result => {
                    // console.log('after fetch result')
                    // console.log(result)
                    
                    if (searchBy === 'city') {
                        let city = {
                            city: result.city.name,
                            country: result.country.name,
                            country_lowercase: result.country.lowercase,
                            region: result.context.region,
                            geometry: result.geometry,
                            bbox: result.city.bbox
                        }

                        // check if the city from the result is unique
                        // if yes, add to array for further processing
                        if (uniqueCities.map((e) => {
                            // console.log(e)
                            return e.city
                        }).indexOf(city.city) == -1) {
                            // console.log(uniqueCities)
                            uniqueCities.push(city)
                        }

                       
                    }

                    if (searchBy === 'title') {
                        let listing = {
                            id: result._id,
                            title: result.title,
                            city: result.city.name,
                            country: result.country.name,
                            geometry: result.geometry,
                            url: result.url
                        }
                        listings.push(listing)
                    }

                    if (searchBy === 'zip') {
                        let listing = {
                            id: result._id,
                            zip: result.context.zip,
                            title: result.title,
                            city: result.city.name,
                            country: result.country.name,
                            geometry: result.geometry,
                            url: result.url
                        }
                        zipResults.push(listing)
                    }
                }))
                
                uniqueCities.forEach(el => output.push({label: el.city + ', ' + el.country, value: el.city, category: "City", cityCenter: el.geometry.coordinates, cityBbox: el.bbox, country_lowercase: el.country_lowercase }))
                listings.forEach(el => output.push({ label: el.title + ', ' + el.city + ', ' + el.country, value: el.title, url: el.url, category: "Title" }))
                zipResults.forEach(el => output.push({ label: '<strong>' + el.zip + '</strong>' + ' - ' + el.title + ', ' + el.city + ', ' + el.country, value: el.title, url: el.url, category: "Zip" }))
            
                // console.log(uniqueCities)
            // console.log(listings)
            // listings.slice(0,5).forEach(el => output.push({label: el.title + ', ' + ' ' + el.city + ', ' + el.country, value: el.title, category: "School", geometry: el.geometry.coordinates }))

            res(output)
        },

        appendTo: "#search-dropdown-results",

        minLength: 3,

        select: function(event, ui) {
            // console.log(ui)
            if (ui.item.category == "City") {
                let el = ui.item.cityBbox.split(',')
                const bbox = `sw_long=${el[0]}&sw_lat=${el[1]}&ne_long=${el[2]}&ne_lat=${el[3]}`
                window.location.href = `/s/${ui.item.country_lowercase}/schools?${bbox}&page=1&search_by_map=true`;
                // window.location.href = `/s/${ui.item.country_lowercase}/schools?lat=${ui.item.cityCenter[0]}&long=${ui.item.cityCenter[1]}&page=1`;
                // window.location.href = `/searchmap?lat=${ui.item.cityCenter[0]}&long=${ui.item.cityCenter[1]}&page=1`;
            }

            if (ui.item.category == "Title") {
                window.location.href = `/school/${ui.item.url}`;
            }

            if (ui.item.category == "Zip") {
                window.location.href = `/school/${ui.item.url}`;
            }
        },
        response: function(event, ui) {
            if (!ui.content.length) {
                let noResult = { value: "", label: "Oh boy! No results found. Try again!"};
                ui.content.push(noResult)
            }
        }
    }).catcomplete( "instance" )._renderItem = function(ul, item) {
        return $( "<li>" )
            .append( "<span>" + item.label + "</span>")
            .appendTo(ul)
    };
});


}