//$('#myModal').modal('hide');
var fuelType = 'reg';

$('#map_canvas').gmap().bind('init', function(ev, map) {

    $('.dropdown-menu').on('click', 'li', function(event) {
        fuelType = $('a', this).attr('id');
        var displayFuelType = $('a', this).attr('data');
        $('#type-display').html(displayFuelType);
        if (isSearchNear === true) {
            getResults(map.getCenter().lat(), map.getCenter().lng(), apiKey, map, fuelType);
        } else {
            getResultsByCity(id, apiKey, map, fuelType);
			
        }
    });

    if (isSearchNear === true) {
        $('#cityLocation').html('Searching for your location...');

        $('#map_canvas').gmap('getCurrentPosition', function(position, status) {
            if (status === 'OK') {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;

                var geoAddressApi = apiDomain + 'locations/geoaddress/' + lat + '/' + lng + '/' + apiKey + '.json?callback=?';
                $.getJSON(geoAddressApi, function(e) {

                    if (e.location.country_long != "United States") {
                        lat = defaultLat;
                        lng = defaultLng;
                    }
                    $('#map_canvas').gmap('option', 'center', new google.maps.LatLng(lat, lng));
                    $('#map_canvas').gmap('option', 'zoom', 12);
                    $('#cityLocation').html('<span id="type-display">Regular</span> gas prices around  <span id="location"></span>');
                    getResults(lat, lng, apiKey, map, fuelType);
					
                });
            }
        });

    } else {
		
		
        var latlng = new google.maps.LatLng(lat, lng);
        $('#map_canvas').gmap('option', 'center', latlng);
        $('#map_canvas').gmap('option', 'zoom', 12);
        getResultsByCity(id, apiKey, map, fuelType);
    }

    $('#redoSearch').on('click', function(event) {
        if (map.getZoom() > 10) {
            isSearchNear = true;
            getResults(map.getCenter().lat(), map.getCenter().lng(), apiKey, map, fuelType);
        } else {
            alert("You are zoomed too much out");
        }
    });
});

function typePrice(marker, type) {
    var price, date;
    if (type == "reg") {
        price = marker.reg_price;
        date = marker.reg_date;
    } else if (type == "mid") {
        price = marker.mid_price;
        date = marker.mid_date;
    } else if (type == "pre") {
        price = marker.pre_price;
        date = marker.pre_date;
    } else if (type == "diesel") {
        price = marker.diesel_price;
        date = marker.diesel_date;
    }

    if (price != "N/A") {
        price = "$" + price;
    }

    return {
        price: price,
        date: date
    };
}

function displayList(marker, type) {

    var p = typePrice(marker, type);

    var html = '';

    html += "<li id='" + marker.id + "'>";
    html += "<div class='left-container'>";
    html += "<p class='station'>" + marker.station + "</p>";
    html += "<p class='address'>" + marker.address + "</p>";
    html += "</div>";
    html += "<div class='right-container'>";
    html += "<p class='price'>" + p.price + "</p>";
    html += "<!--<p class='last-update'>" + p.date + "</p> -->";
    html += "</div>"
    html += "</li>";

    return html;
}

function displayInfoWindow(data, type) {

    var p = typePrice(data, type);

    var c = "<div class='googlemaps-name'>" + data.station + " - " + p.price + " <!--<span class='googlemaps-last-update'>(" + p.date + ")</span>--></div>";
    c += "<p class='googlemaps-details'>" + data.address + "</p>";
    c += "<p class='googlemaps-details'>" + data.city + ", " + data.region + "</p>";
    c += "<div class='googlemaps-separator'></div>";
    c += "<!--<a href='#' style='margin-right: 10px;font-size:12px;' id='report" + data.id + "'>Report price</a> -->";
    c += "<!-- <a href='details.html/" + data.id + "/" + data.region + "/" + data.city + "' style='margin-right: 10px;font-size:12px;' target='_blank' class='btn btn-success btn-xs'>View details</a>-->";
    c += "<!-- <a href='#' style='font-size:12px;' id='streetView" + data.id + "'>Street view</a> -->";

    return c;
}

function getResults(lat, lng, apiKey, map, type) {
  //  fadeOutNotification();
  //  setNotification('Loading Gas Stations...');
  //  fadeInNotification();

    var apiUrl = apiDomain + 'stations/radius/' + lat + '/' + lng + '/2/' + type + '/price/' + apiKey + '.json?callback=?';

    $.getJSON(apiUrl, function(data) {
        $('#map_canvas').gmap('clear', 'markers');
        $('.gaslist').html('');
        $('#location').html(data.geoLocation.city_long + ', ' + data.geoLocation.region_short);

        var html = '<li style="height:15px"></li>';
        $('.gaslist').append(html);
        $.each(data.stations, function(i, data) {
            html = displayList(data, fuelType);
            $('.gaslist').append(html);

            $('#map_canvas').gmap('addMarker', {
                'id': data.id,
                'position': new google.maps.LatLng(data.lat, data.lng),
                "animation": google.maps.Animation.DROP
            }, function(map, marker) {
                $('.gaslist li#' + data.id).click(function() {
                    $(marker).triggerEvent('click');
                });
            }).click(function() {

                $('#streetView' + data.id).on("click", function() {
                    $('#map_canvas').gmap('displayStreetView', 'map_canvas', {
                        'enableCloseButton': true,
                        'position': new google.maps.LatLng(data.lat, data.lng),
                        'pov': {
                            'heading': 34,
                            'pitch': 10,
                            'zoom': 1
                        }
                    });
                });

                $('#report' + data.id).on("click", function() {
                    alert('Coming soon! To report gas price view the details page.')
                });

                $('#map_canvas').gmap('openInfoWindow', {
                    'content': displayInfoWindow(data, fuelType)
                }, this);

            });
        });
        //fadeOutNotification();
       // $('.content').jScrollPane();

    });
}

function getResultsByCity(id, apiKey, map, type) {
   // fadeOutNotification();
   // setNotification('Loading Gas Stations...');
   // fadeInNotification();

    var apiUrl = apiDomain + 'stations/cityid/' + id + '/99/' + type + '/' + apiKey + '.json?callback=?';

    $.getJSON(apiUrl, function(data) {
        $('#map_canvas').gmap('clear', 'markers');
        $('.gaslist').html('');
        $('#location').html(data.geoLocation.city_long + ', ' + data.geoLocation.region_short);

        var html = '<li style="height:15px"></li>';
        $('.gaslist').append(html);
        $.each(data.stations, function(i, data) {
            html = displayList(data, fuelType);
            $('.gaslist').append(html);

            $('#map_canvas').gmap('addMarker', {
                'id': data.id,
                'position': new google.maps.LatLng(data.lat, data.lng),
                "animation": google.maps.Animation.DROP
            }, function(map, marker) {
                $('.gaslist li#' + data.id).click(function() {
                    $(marker).triggerEvent('click');
                });
            }).click(function() {

                $('#streetView' + data.id).on("click", function() {
                    $('#map_canvas').gmap('displayStreetView', 'map_canvas', {
                        'enableCloseButton': true,
                        'position': new google.maps.LatLng(data.lat, data.lng),
                        'pov': {
                            'heading': 34,
                            'pitch': 10,
                            'zoom': 1
                        }
                    });
                });

                $('#report' + data.id).on("click", function() {
                    alert('Coming soon! To report gas price view the details page.')
                });

                $('#map_canvas').gmap('openInfoWindow', {
                    'content': displayInfoWindow(data, fuelType)
                }, this);

            });
        });
       // fadeOutNotification();
       // $('.content').jScrollPane();

    });
}

