/* 
	Our custom extensions to the Google Maps API. Built on the ym4r extensions.
	Must be in this seperate file because of load order - application.js is loaded before Google Maps, this file, right after.
*/

/* Centers the map on a specific given coordinate, while attempting to zoom out far enough to show all given points */
GMap2.prototype.centerSpecificAndZoomToPoints = function(center, points, prefered_zoom, min_zoom) {
	// Calculate "fake" point as the inverse of the point farthest away from the center, to ensure that zoom level
	// will be sufficient even when centering
	var farthest_point;
	var farthest_distance = 0;
	for (var i=0, len = points.length ; i<len; i++) {
		if( points[i].distanceFrom(center) > farthest_distance )
			farthest_point = points[i];
	}
	var inverse_lat = center.lat() + (center.lat() - farthest_point.lat());
	var inverse_lng = center.lng() + (center.lng() - farthest_point.lng());
	var inverse_point = new GLatLng(inverse_lat, inverse_lng);
	
	// Get the zoom level required to show all points on the map, including the center
	var bounds = new GLatLngBounds(center, center);
	for (var i=0, len = points.length ; i<len; i++) {
		bounds.extend(points[i]);
	}
	bounds.extend(inverse_point);
	var points_zoom = this.getBoundsZoomLevel(bounds);

	// If the zoom required to show all points is above prefered zoom, set it to prefered zoom, as not to zoom too far in
	// If it is below min zoom, set it to min zoom as not to zoom far out - this means some points will be outside the map
	// If it is within the allowed zoom range, use the points zoom
	var zoom;
	if(points_zoom > prefered_zoom) {
		zoom = prefered_zoom;
	} else if( points_zoom < min_zoom ) {
		zoom = min_zoom;
	} else {
		zoom = points_zoom;
	}

	// Center and zoom
	this.setCenter(center, zoom);
};