var g_map;

// Given a map and the id of a div to use as a canvas, draws the map on screen for the first time

function initialize_map( map_canvas_id ) {
	if ( GBrowserIsCompatible() ) {
		the_map_canvas = document.getElementById( map_canvas_id );
		// Make the map square
		the_map_canvas.style.height = the_map_canvas.offsetWidth + "px";
		g_map = new GMap2( the_map_canvas );
		reset_map( g_map );
	}
}

// Center the map over the UK

function reset_map( map ) {
	if ( GBrowserIsCompatible() ) {
		g_map.setCenter( new GLatLng( 54, -4 ), 4 );
		g_map.addControl( new GSmallZoomControl() );
		map.clearOverlays();
	}
}

// Convenience method to call set_area_to_show_on_map and draw_overlay_on_map

function update_map( coordinates_array, map ) {
	set_area_to_show_on_map( coordinates_array, map );
	draw_overlay_on_map( coordinates_array, map );
}

// Given the coordinates of the overlay we want to draw, this sets a Google
// map to the best position and zoom level

function set_area_to_show_on_map( coordinates_array, map ) {
	if ( GBrowserIsCompatible() ) {
		// Get the most northern, southern, eastern and western points we want to plot
		var north, south, east, west;
		north = coordinates_array[ 0 ][ 0 ];
		south = coordinates_array[ coordinates_array.length / 2 ][ 0 ];
		east = coordinates_array[ coordinates_array.length / 4 ][ 1 ];
		west = coordinates_array[ coordinates_array.length * 3 / 4 ][ 1 ];
		// Add some padding so the overlay is never larger than 80% of the height of the map
		var padding = ( north - south ) * 10 / 100;
		var south_west = new GLatLng( south - padding, west );
		var north_east = new GLatLng( north + padding, east );
		var map_bounds = new GLatLngBounds( south_west, north_east );
		map.setCenter( map_bounds.getCenter() );
		map.setZoom( map.getBoundsZoomLevel( map_bounds ) );
	}
}

// Given the coordinates of a circle we want to draw, this removes any existing overlays
// and draws the circle on a new overlay

function draw_overlay_on_map( coordinates_array, map ) {
	if ( GBrowserIsCompatible() ) {
		// Convert each coordinate into a Google object
		var poly_points = new Array();
		for ( i = 0; i < coordinates_array.length; i++ ) {
			poly_points.push( new GLatLng( coordinates_array[ i ][ 0 ], coordinates_array[ i ][ 1 ] ) );
		}
		// Re-add the first coordnate to complete the circle
		poly_points.push( new GLatLng( coordinates_array[ 0 ][ 0 ], coordinates_array[ 0 ][ 1 ] ) );
		var poly = new GPolygon( poly_points,"purple", 3, 1,"purple", 0.2 );
		//var poly = new GPolyline( poly_points,"#ff0000", 3, 1 );
		map.clearOverlays();
		map.addOverlay( poly );
	}
}