$(function() {
	
	var localSearch = new GlocalSearch();

	// Google Maps API key for http://fih.torchboxapps.com
	// ABQIAAAAYI2hPvN74YVxSMU0PX2sPhQkrSQZCWe_v1nL-JVFG6UhQ-NN9xTZH-X93QXB5KoYs6SuATEZ0kXB6Q
	
	var ps_default_text = $(".postcode_search input").val();
	$(".postcode_search input").focus(function() {
		if (this.value == ps_default_text) {
			$(this).val("");
		}
	}).blur(function() {
		if (this.value == "") {
			$(this).val(ps_default_text);
		}
	});
	
	if (GBrowserIsCompatible()) {
		$('<div id="map_canvas"></div>').css({'height':'286px'}).prependTo(".gp_listing");
		var map = new GMap2(document.getElementById("map_canvas"));
		var markers = new Array();
		map.setCenter(new GLatLng(54,0), 5);
        map.addControl(new GLargeMapControl3D());
		var i = 0;
		
		$(".gp_listing .vcard").each(function() {
		    i = this.id.split("_")[2];
			var lat = $(".latitude", this).text();
			var lon = $(".longitude", this).text();
			markers[i] = new GMarker(new GLatLng(lat, lon));
			map.addOverlay(markers[i]);
			markers[i].bindInfoWindowHtml('<div class="map_bubble">' + $(this).html() + "</div>");
			i++;
		});
		
		$(".postcode_search").submit(function() {
			// validate postcode first
			var postcode = $(".postcode_search input").val().toUpperCase();
			if (/\b([A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]?)*([0-9][ABD-HJLN-UW-Z]{2})?\b/.test(postcode)) {
				
				usePointFromPostcode(postcode, function(point) {
					
					// Center map on postcode
					map.setCenter(point);
					
					var current_zoom = 13;
				    var current_bounds;
				    var marker_in_view = false;
				    
					// Zoom out until first marker in view
				    while(!marker_in_view) {
    					map.setZoom(current_zoom);
    				    current_bounds = map.getBounds();
    					for (id in markers) {
    					    if (current_bounds.containsLatLng(markers[id].getLatLng())) {
    					        marker_in_view = true;
    					    }
    					}
    					current_zoom--;
    				}
				});
				
			} else {
				window.alert("Please enter a valid postcode.");
			}
			return false;
		});
		
		if (window.location.hash) {
		    var point_id = window.location.hash.split("_")[2];
		    map.setCenter(markers[point_id].getLatLng(), 11);
		    GEvent.trigger(markers[point_id], "click");
		}
		
    }
    
	function usePointFromPostcode(postcode, callbackFunction) {

		localSearch.setSearchCompleteCallback(null, 
			function() {

				if (localSearch.results[0])
				{		
					var resultLat = localSearch.results[0].lat;
					var resultLng = localSearch.results[0].lng;
					var point = new GLatLng(resultLat,resultLng);
					callbackFunction(point);
				}else{
					alert("Postcode not found!");
				}
			});	

		localSearch.execute(postcode + ", UK");
	}
});

