/*
 * Google MAPs API Functions 
 */

/*
Usage:
<?php //include("init-googlemaps.html"); ?>
<?php //include("init-graybox.html"); ?> //if using greybox

	<script src="gmaps.js" type="text/javascript"></script>
	<!--
	#### Greybox doesnt work with the onload even in the Body tag 
	#### so use this to replace Google Maps (or other scripts) onload events -->
	<script>
  	AJS.AEV(window, 'load', function() {
 			mapLoad('<?php //echo($gpostcode);?>');
    });
   </script> 
*/

var map;
var localSearch = new GlocalSearch();
var pointermoved = false;

var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.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, 34);


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");
}

function placeMarker(point) {

	map.setCenter(point, 17);

  var marker = new GMarker(point, {draggable: true});
	map.addOverlay(marker);
		
  GEvent.addListener(marker, "dragend", function() {
    	outstr = ghtml.replace("GoogleMapsLL", "<br><br><strong>Pointer Moved to:<br>"+marker.getLatLng().toUrlValue(6)+"</strong>");			  
	  	marker.openInfoWindowHtml(outstr);
	  	pointermoved=true;
  	}
	);

  GEvent.addListener(marker, "click", function() {
			if (pointermoved) {			  
				outstr = ghtml.replace("GoogleMapsLL", "<br><br><strong>Pointer Moved to:<br>"+marker.getLatLng().toUrlValue(6)+"</strong>");
			} else {
	  		outstr = ghtml.replace("GoogleMapsLL", "");
	  	}
	  	marker.openInfoWindowHtml(outstr);
  	}
	);
	
	GEvent.trigger(marker, "click");	
}

function showPointLatLng(point) {
	alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}

function mapLoad(postcode) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));		
		
    //map.setMapType(G_NORMAL_MAP);
    //map.setMapType(G_HYBRID_MAP);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl(true));

 		usePointFromPostcode(postcode, placeMarker);
	}
}
