﻿// Custom google maps v3 script - Patrick H. Lauke 3 May 2011

function mapInit(placeholder,address) {
	// set the container to a nice 16:9 ratio of the layout - this way the map adapts to its parent/styling
    var container = document.getElementById(placeholder);
	if (container) {
		container.setAttribute('style',"width: 100%; height: "+container.offsetWidth*9/16+"px;");
	
		// get the address text
		var addr = document.getElementById(address).innerHTML;
		addr=addr.replace(/<br>/g,'');
		addr=addr.replace(/\n/g,', ');
		addr=addr.replace(/\r/g,'');
		// debug
		if (console.log) { console.log(addr); }
	
		// see if we can find the coordinates for the address
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': addr}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				// only if the geocoding was successful do we actually create the map and marker
				var mapOptions = {
					zoom: 16,
					center: results[0].geometry.location,
					panControl: true,
					zoomControl: true,
					scaleControl: false,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				}
			
				// debug
				if (console.log) { console.log(results[0].formatted_address); }
			
				map = new google.maps.Map(document.getElementById(placeholder), mapOptions);
				var marker = new google.maps.Marker({
					map: map, 
					position: results[0].geometry.location
				});
			} else { 
				// if geocode fails, just remove the empty map placeholder container
				if(console.log) {
					console.log("Geocode failed: " + status);
				}
				container.parentNode.removeChild(container);
			}
		});
	}
}

window.addEventListener('load', function() { mapInit('gmap','address'); }, true);
