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

// This function is called by the Google Maps API when it's fully loaded
function initMap() {

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

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

    searchBox.addListener("places_changed", () => {
        const places = searchBox.getPlaces();

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

        // 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;
            }
        });

        // Sends the position to draw the pins
        //requestData(places[0].geometry.location.lat(), places[0].geometry.location.lng());     
        sendtoQuery(places[0].geometry.location.lat(), places[0].geometry.location.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) {

    $('[name=latitude]').val(position.coords.latitude);
    $('[name=longitude]').val(position.coords.longitude);    
    
    // sends to MY query
	sendtoQuery(position.coords.latitude, position.coords.longitude);

    // Sends the position to draw the pins
    //requestData(position.coords.latitude, position.coords.longitude);
}

// Draws pins
//function requestData(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("");
//
//            if(data.length == 0) {
//                showErrorMessage("There are no restaurants near your location.");
//                return;
//            }
//
//            $('.empty-error-msg').hide();
//
//            data.map(function(data, index) {
//                showListing(data);
//            });
//        },
//        error: function() {
//            alert('An error occurred while fetching the data.');
//        }
//    });
//}

function sendtoQuery(lat, lng) {
    // retrieve data by radius
    $.ajax({
        url: "/shop/getNearbyListings",
        cache: true,
        type: "GET",
        data: { "lat" : lat, "lng": lng },
        success: function(html){
            //alert('Data: ' + data);
              	//alert(html);
                $(".projects-listing-wrapper").html(html);
                //self.initUI();
        },
        error: function() {
            alert('An error occurred while fetching the data.');
        }
    });
}

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);
}

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();

// 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');
});