// JavaScript Document

var map = null;
var geocoder = null;

function loadMap() {
var business = document.form1.business.value;
var address = document.form1.address.value;
var marker_address = document.form1.markertext.value;
var markertext = "<div id='marker'><strong>" + business + "</strong><br/>" + marker_address + "</div>";
var mappin = document.form1.mappin.value;
var mappins = document.form1.mappins.value;
var geocode = document.form1.geocode.value;

	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		geocoder = new GClientGeocoder();
		
      // Add custom icons
      // This icon uses the same shape as the default Google marker
      // So we can use its details for everything except the image 
      var theIcon = new GIcon();
      theIcon.image = mappin;
      theIcon.shadow = mappins;
      theIcon.iconSize = new GSize(32, 32);
      theIcon.shadowSize = new GSize(59, 32);
      theIcon.iconAnchor = new GPoint(9, 32);
      theIcon.infoWindowAnchor = new GPoint(9, 2);
      theIcon.infoShadowAnchor = new GPoint(18, 25);
      theIcon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
      theIcon.printImage = "coldmarkerie.gif";
      theIcon.mozPrintImage = "coldmarkerff.gif";		
	}
	
	function getDirections(point,html) { // add a "directions" link to info window text
	  html += '&raquo;&nbsp;<a href="http://maps.google.com/maps?saddr=&daddr=' + point.toUrlValue() + '" target ="_blank">Get Directions</a>';
	  return html;
	}
	
	if (geocoder) {
		map.addControl(new GSmallMapControl());
		if (geocode != "") {  // parse geocode if exists
			geocode = geocode.replace(/ /g,"");
			var pos = geocode.indexOf(',');
			var lat = geocode.substr(0, pos);
			var lng = geocode.substr(pos + 1);
			
			map.setCenter(new GLatLng(lat, lng), 15); // number sets zoom level, higher is in
			var point = new GLatLng(lat,lng);
			var marker = new GMarker(point, theIcon);
			map.addOverlay(marker);
			var new_markertext = getDirections(point, markertext);
			GEvent.addListener(marker, "mouseover", function() {
				marker.openInfoWindowHtml(new_markertext);
			});
		}
		else {		
			geocoder.getLatLng(address, function(point) {
				map.setCenter(point, 15);
				var marker = new GMarker(point, theIcon);
				map.addOverlay(marker);
				var new_markertext = getDirections(point, markertext);
				GEvent.addListener(marker, "mouseover", function() {
					marker.openInfoWindowHtml(new_markertext);
				});
			// }
			}
	   );
		}
	}
}

// ====== Geocoding ======
function getAddress(search) {
  geocoder.getLocations(search, function (result) { 
		// If that was successful
		if (result.Status.code == G_GEO_SUCCESS) {
		  var p = result.Placemark[0].Point.coordinates;
		  var lat=p[1];
		  var lng=p[0];
		}
	return p;
	 }
	);
}
	
