var json_google_map;
var json_points;
var map_points = [];

var json_url = "";

function get_json_url(lat, long) {
	return json_url + "?latitude=" + lat + "&longitude=" + long; 
}

function init_explore_map(lat, long, json_url_1) {
	json_url = json_url_1;
	if (GBrowserIsCompatible()) {
		setupMap();
		json_google_map.setCenter(new GLatLng(lat, long), 10);
		centerMap(lat, long);
		// fitMap(json_google_map, map_points);
	}
	else {
		$("explore_map").hide();
	}
}

var oldCenterLat;
var oldCenterLong;
function movedFarEnough(lat, long) {
	if (!oldCenterLat)
		return true;
	if (Math.abs(lat - oldCenterLat) > 0.05 || Math.abs(long - oldCenterLong) > 0.05) {
		// alert("lat: " + Math.abs(lat - oldCenterLat) + " and long: " + Math.abs(long - oldCenterLong));
		return true
	}
	return false;
}

function centerMap(lat, long) {
	lat = roundNumber(lat, 4);
	long = roundNumber(long, 4);
	if (movedFarEnough(lat, long)) {
		oldCenterLat = lat;
		oldCenterLong = long;
		new Ajax.Request(get_json_url(lat, long), {
			method:"get",
			requestHeaders: {Accept: "application/json"},
			onSuccess: function(transport) {
				responseInfo = transport.responseText.evalJSON(true);	
				json_points = responseInfo.restaurants.evalJSON(true);
				$("explore_info").innerHTML = (responseInfo.html);
				addExplorerToMap(new GLatLng(lat, long));	
				populateMap();
			},
			onFailure: function(transport) {
			}
		});
	}
}

function roundNumber(num, dec) {
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	return result;
}

function showPoint(lat, long) {
	json_google_map.setCenter(new GLatLng(lat, long), 15);
}

var localRestaurantIcon;
var chainRestaurantIcon;

function setupMap() {
    json_google_map = new GMap2($("explore_map"));
	// json_google_map.addControl(new GSmallZoomControl3D());
	
	json_google_map.enableContinuousZoom();
	var customUI = json_google_map.getDefaultUI();
	customUI.controls.scalecontrol = false;
	customUI.maptypes.hybrid = false;
	customUI.maptypes.satellite = false;
	customUI.controls.smallzoomcontrol3d = true ;	
	customUI.controls.largemapcontrol3d = false ;	
	
	json_google_map.setUI(customUI);
	json_google_map.setMapType(G_PHYSICAL_MAP);

	GEvent.addListener(json_google_map, "moveend", function() {
		var center = this.getCenter();
		centerMap(center.lat(), center.lng());
	});
	
	
	// Create our "tiny" marker icon
	localRestaurantIcon = new GIcon();
	localRestaurantIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	localRestaurantIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	localRestaurantIcon.iconSize = new GSize(12, 20);
	localRestaurantIcon.shadowSize = new GSize(22, 20);
	localRestaurantIcon.iconAnchor = new GPoint(6, 20);
	localRestaurantIcon.infoWindowAnchor = new GPoint(5, 1);
	
	chainRestaurantIcon = new GIcon();
	chainRestaurantIcon.image = "http://labs.google.com/ridefinder/images/mm_20_gray.png";
	chainRestaurantIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	chainRestaurantIcon.iconSize = new GSize(12, 20);
	chainRestaurantIcon.shadowSize = new GSize(22, 20);
	chainRestaurantIcon.iconAnchor = new GPoint(6, 20);
	chainRestaurantIcon.infoWindowAnchor = new GPoint(5, 1);
}

var shouldFit = true;
function populateMap() {
	json_google_map.clearOverlays();
	addExplorerToMap(null);
	json_points.each(function(x){
		addRestaurant(x.restaurant);
	});
	if (shouldFit) {
		fitMap(json_google_map, map_points);
		shouldFit = false;
	}
}

var explorerMarker;
function addExplorerToMap(point) {
	// Create our "tiny" marker icon
	if (!explorerMarker) {
		var userIcon = new GIcon();
		userIcon.image = "/images/map/you.png";
		userIcon.shadow = "/images/map/you_shadow.png";
		userIcon.iconSize = new GSize(11, 36);
		userIcon.shadowSize = new GSize(48, 33);
		userIcon.iconAnchor = new GPoint(6, 36);
		userIcon.infoWindowAnchor = new GPoint(5, 1);
		var userMarkerOptions = { icon:userIcon , draggable:false};
		explorerMarker = new GMarker(point, userMarkerOptions);
		json_google_map.addOverlay(explorerMarker);
		map_points.push(point);
		fitMap(json_google_map, map_points);
		// GEvent.addListener(explorerMarker, "dragend", function() {
		// 	centerMap(explorerMarker.getLatLng().lat(), explorerMarker.getLatLng().lng());
		// });
	}
	else {
		json_google_map.addOverlay(explorerMarker);
	}
}

function addRestaurant(restaurant) {
	if (!restaurant.latitude || !restaurant.longitude)
		return;	
		
	if (restaurant.been_reviewed == false)
		theIcon = chainRestaurantIcon;
	else
		theIcon = localRestaurantIcon;
	
	var point = new GLatLng(restaurant.latitude, restaurant.longitude);
	map_points.push(point);
	var marker = new GMarker(point, { icon:theIcon });
	json_google_map.addOverlay(marker);
	
	GEvent.addListener(marker, 'click', function(){ 
      marker.openExtInfoWindow(
        json_google_map,
        "simple_example_window",
        '<div class="map_info_loading">Loading...</div>',
		{
			ajaxUrl: "/restaurant/info_window?restaurant=" + restaurant.id, 
			beakOffset: 3
		}
      ); 
    });
    
	// GEvent.addListener(marker, "click", function() {
	//   marker.openInfoWindow(document.getElementById("info_<%= i %>").cloneNode(true));
	//   	});
}


function fitMap( map, points ) {
	var bounds = new GLatLngBounds();
	for (var i=0; i< points.length; i++) {
		bounds.extend(points[i]);
	}
	// bounds.extend(explorerMarker.getLatLng());
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
}
