let map, infoWindow, pins = [], selfPin;

// This function is called by the Google Maps API when it's fully loaded
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 42.226810,
            lng: -71.254140
        },
        zoom: 15,
        zoomControl: true,
        mapTypeControl: false,
        zoomControlOptions: {
            position: google.maps.ControlPosition.LEFT_CENTER,
        },
    });

    const input = document.getElementById("map-search");

    const searchBox = new google.maps.places.SearchBox(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener("bounds_changed", () => {
        searchBox.setBounds(map.getBounds());
    });

    let markers = [];

    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener("places_changed", () => {
        const places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Clear out the old markers.
        markers.forEach((marker) => {
            marker.setMap(null);
        });

        markers = [];

        // For each place, get the icon, name and location.
        const bounds = new google.maps.LatLngBounds();

        places.forEach((place) => {
            if (!place.geometry || !place.geometry.location) {
                console.log("Returned place contains no geometry");
                return;
            }

            infoWindow = new google.maps.InfoWindow();

            // Create a marker for each place.
            const selfPin = new google.maps.Marker({
                position: place.geometry.location,
                map,
                optimized: true,
            });

            selfPin.addListener("click", () => {
                infoWindow.close();
                infoWindow.setContent('Your location.');
                infoWindow.open(selfPin.getMap(), selfPin);
            });

            if (place.geometry.viewport) {
                // Only geocodes have viewport.
                bounds.union(place.geometry.viewport);
            } else {
                bounds.extend(place.geometry.location);
            }
        });

        // Sends the position to draw the pins
        requestPinsData(places[0].geometry.location.lat(), places[0].geometry.location.lng());
        map.fitBounds(bounds);
        var lat = places[0].geometry.location.lat();
        var lng = places[0].geometry.location.lng();
     		$('[name=lat]').val(lat);
     		$('[name=lng]').val(lng);            
    });

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(userPositionForward);
    }

    // Create an info window to share between markers.
    infoWindow = new google.maps.InfoWindow();
}

// Detects the current position of the user
function userPositionForward(position) {

    let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    map.setCenter(latLng);
    
     		$('[name=latitude]').val(position.coords.latitude);
     		$('[name=longitude]').val(position.coords.longitude);    

    // Create a marker for each place.
    selfPin = new google.maps.Marker({
        position: latLng,
        map,
        title: 'test',
        optimized: true,
    });

    selfPin.addListener("click", () => {
        infoWindow.close();
        infoWindow.setContent('Your location.');
        infoWindow.open(selfPin.getMap(), selfPin);
    });
    
    // Sends the position to draw the pins
    requestPinsData(position.coords.latitude, position.coords.longitude);
}

// Draws pins
function requestPinsData(lat, lng) {
    // retrieve data by radius
    $.ajax({
        url: "data.php",
        cache: true,
        type: "POST",
        data: { "lat" : lat, "lng": lng },
        success: function(data){
            
            data = $.parseJSON( data );

            $('.listings').html("");
            removeAllPins();

            if(data.length == 0) {
                showErrorMessage("There are no restaurants near your location.");
                return;
            }

            $('.empty-error-msg').hide();

            drawPins(data);
        },
        error: function() {
            alert('An error occurred while fetching the data.');
        }
    });
}

// Draw pins on the map
function drawPins(mapData) {
    pins = mapData.map(function(data, index) {
        showListing(data);
        let pinLatLng = new google.maps.LatLng(data['latitude'], data['longitude']);
        const pin = new google.maps.Marker({
            position: pinLatLng,
            map,
            title: data['name'],
            customData: data,
            optimized: true,
        });
        // Show pin details when clicked
        pin.addListener("click", () => {
            $('.pin-data').show();
            $('.pin-img').attr('src', pin['customData']['image']);
            $('.pin-name').html( pin['customData']['name']);
            $('.pin-address').html( pin['customData']['address']);

            infoWindow.close();
            infoWindow.setContent('<h6 class="text-danger">'+pin['customData']['name']+'</h6><p>'+pin['customData']['address']+'</p><p>'+Number(pin['customData']['distance']).toFixed(2)+' Miles</p><button class="btn btn-primary btn-sm">Call to action</button>');
            infoWindow.open(pin.getMap(), pin);
        });
        return pin;
    });

    activateFavorites();
}

function showListing(data) {
    let template = $('script[data-template="listitem"]').html();
    template = $($.parseHTML(template));
    template.attr('data-id', data['id']);
    template.attr('data-lid', data['location_id']);
    template.attr('data-name', data['name']);
    template.find('.name').html(data['name']);
    template.find('.miles span').html(Number(data['distance']).toFixed(2));
    template.find('.address').html(data['address']);
    template.find('.cover').attr('src', data['image']);

    if(data['location_id'] == selectedLocation) 
        template.find('.order-button').addClass('selected');
    
    $('.listings').append(template);
}

// Removes all current pins on the map (This is for the performance)
function removeAllPins() {
    //Loop through all the pins and remove
    for (var i = 0; i < pins.length; i++) {
        pins[i].setMap(null);
    }
    pins = [];
};

function showErrorMessage(msg) {

    $('.empty-error-msg .content').html(msg);
    $('.empty-error-msg').show();
}

// highlights favorites
function activateFavorites() {

    let favorites = localStorage.getItem('favorites');
        
    if(favorites) {
        // if the favorites array already exist
        favorites = $.parseJSON(favorites);

        $('.listing').each(function() {
            let id = $(this).data('id');

            if($.inArray(id, favorites) !== -1) 
                $(this).find('.favorite').addClass('active');
        });
    }
}

activateFavorites();

// Hide error messages by default
$('.empty-error-msg').hide();

// Hide pin details
$('.pin-data').hide();

// ORDER HERE BUTTONS
$(document).on('click', '.order-button', function(e) {
    var id = $(this).parent().data('lid');
    var name = $(this).parent().data('name');
    var button = $(this);
    
    $('.order-button').removeClass('selected');
    button.addClass('selected');
    
    $('#restaurant_id_input').val(id);
    $('#restaurant_name_input').val(name);
    //$('#restaurant_id_form').submit();
    
    $.ajax({
        type: "POST",
        cache: true,
        url: "order.php",
        data: { "id" : id, "name" : name },
        success: function(data){
            console.log(data);
            //alert('Success');
            //alert('Data:' + data + ' Result: ' + result);
            // Do what you want to do when the session has been updated
            //alert('The submit ajax function worked!');
            //window.location = 'https://preorder.sqdash.co/shopp';
        },
        error: function(){
            button.removeClass('selected');
            alert('Ooops. Something went wrong. Please refresh and try again.');
        }
    });
});

// Favorite button
$(document).on('click', '.favorite', function(e) {
    let favorites = localStorage.getItem('favorites');
    let id = $(this).parent().parent().data('id');

    if(!favorites) {
        // Create an array by default
        favorites = [];
    }else {
        // if the favorites array already exist
        favorites = $.parseJSON(favorites);
    }

    if($.inArray(id, favorites) !== -1) {
        // remove the id from array
        favorites.splice( $.inArray(id, favorites), 1 );
        $(this).removeClass('active');
    }else {
        favorites.push(id);
        $(this).addClass('active');
    }

    localStorage.setItem('favorites', JSON.stringify(favorites));
});

$('#map-search').keyup(function (e) {
    if(this.value.length > 0) {
        $('.clear-input').css('visibility', 'visible');
    }else {
        $('.clear-input').css('visibility', 'hidden');
    }
});

$('.clear-input').click(function (e) {
    $('#map-search').val("");
    $('.clear-input').css('visibility', 'hidden');
});