
var map;
var local_search = new GlocalSearch();
var bounds = new GLatLngBounds();
var icon = new GIcon();
var start_icon = new GIcon();
var directions;
// locations
icon.image = "http://www.google.com/mapfiles/marker.png"; //"./images/findaclinic/map-masta-icon.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 12);
// start point marker
start_icon.image = "http://www.google.com/mapfiles/dd-start.png";
start_icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
start_icon.iconSize = new GSize(20, 34);
start_icon.shadowSize = GSize(37, 34);
start_icon.iconAnchor = new GPoint(10, 34);

var GMap = {
	postcodes: null,
	counter: 0,
	
	show_directions: function(from, to) {
		directions = new GDirections(map, $("#directions"));
		directions.load("from: " + from + ", UK to: + " + to + ", UK");
		
		$("#directions").show();
	},
	
	use_point_from_postcode: function(postcode, callback, type, finalcallback) {
		local_search.setSearchCompleteCallback(null, function(){
			if (local_search.results[0]) {
				var resultLat = local_search.results[0].lat;
				var resultLng = local_search.results[0].lng;
				var point = new GLatLng(resultLat, resultLng);
				callback(point, type, finalcallback);
			} else {
				alert("Postcode not found");
			}
		});
		
		local_search.execute(postcode + ", UK");
	},
	
	place_marker_at_point: function(point, type, finalcallback) {
		var marker;
		if (type == "start") {
			marker = new GMarker(point, start_icon);
		} else {
			marker = new GMarker(point, icon);
		}
		
		map.addOverlay(marker);
		bounds.extend(marker.getPoint());
		
		if (type != "start") {
			GMap.counter++;
			if (GMap.counter >= GMap.postcodes.length) {
				GMap.adjust_view(finalcallback);
			}
		}
	},
	
	set_center_to_point: function(point) {
		map.setCenter(point, 15);
	},
	
	adjust_view: function(finalcallback) {
		var zoom = map.getBoundsZoomLevel(bounds);
		if (zoom >= 17) {
			map.setZoom(17);
		} else {
			map.setZoom(zoom);
		}
		map.setCenter(bounds.getCenter());
		if (finalcallback != undefined)
			finalcallback();
	},
	
	map_load: function() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("google-map"));
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_NORMAL_MAP);
		}
	},
	
	set_points: function(callback) {
		for (var postcode in GMap.postcodes) {
			GMap.use_point_from_postcode(GMap.postcodes[postcode], GMap.place_marker_at_point, "normal", callback);
		}
	},
	
	print_screen: function() {
		setTimeout(function(){
			window.print();
		}, 500);
	}
};