
/* Convert degress to radians */
function deg2rad(deg) 
{
  return deg / (180 / Math.PI);
}

/* Calculate distance between two points */
function point_distance(a, b) 
{
  var r = 6378700;

  var lat1 = a.y;
  var lat2 = b.y;
  var lon1 = a.x;
  var lon2 = b.x;

  var dist = r * Math.acos(Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + 
			   Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
			   Math.cos(deg2rad(lon1 - lon2)));
  return dist;
}

/* find closest store */ 
function get_closest_index (a) 
{
	var min = -1;
	var index = -1;

	for ( i = 0; i < storeJSON.length; i++)
	{
		var distance = point_distance (a, storeJSON [i].point);
		if (distance < min || min == -1)
		{
			min = distance
			index = i;
		}
	}

	return index;
}

function get_zoom_level (map, a, i)
{
	var ne = new GLatLng ( 
			storeJSON[i].point.y < a.lat () ? storeJSON[i].point.y : a.lat (), 
			storeJSON[i].point.x > a.lng () ?  storeJSON[i].point.x : a.lng ());
	var sw = new GLatLng ( 
			storeJSON[i].point.y > a.lat () ? storeJSON[i].point.y : a.lat (), 
			storeJSON[i].point.x < a.lng () ? storeJSON[i].point.x : a.lng ());

	var bounds = new GLatLngBounds (sw, ne);
	map.setCenter (bounds.getCenter ());
	map.setZoom (map.getBoundsZoomLevel (bounds) - 1);
}

function get_icon_urls (image, shadow)
{
	// Create our "tiny" marker icon
	var icon = new GIcon();
	icon.image = image;
	icon.shadow = shadow;
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);
	return icon;
}

function get_icon ()
{
	return get_icon_urls ("http://labs.google.com/ridefinder/images/mm_20_red.png","http://labs.google.com/ridefinder/images/mm_20_shadow.png");
}

function get_marker (map, i)
{
	var point = new GLatLng (storeJSON[i].point.y, storeJSON[i].point.x);
	var marker = new GMarker(point, get_icon());
	var html = "<h2>"+storeJSON[i].name+"</h2><p>"+storeJSON[i].address+"</p><p>" + storeJSON[i].phone + "</p>";

	GEvent.addListener(marker, "click", function() { 
			map.openInfoWindowHtml(point, html); 
		}); 

	return marker;
}

function add_stores_map (map)
{
	for (i = 0; i < storeJSON.length; i++)
	{
		var marker = get_marker (map, i);
		map.addOverlay(marker);
	}
}

function format_location (i)
{
	return storeJSON [i].name + "@" + storeJSON[i].point.y + "," + storeJSON[i].point.x;
}
