//<![CDATA[

document.onload=StartMapLoadTimer();

// make sure browser tidies up memory on page unload
document.onunload="GUnload()";

var timerID = null;
var EditMapTimerID = null;
var currentCafeChurch = "";
var viewmap = null;
var editmap = null;
var geocoder;		// for address searches

// gets an address from the user, converts to lat/lng, then redirects page to local listings page
function searchLocations() {
     var address = document.getElementById('address').value;
     var country = document.getElementById('country').value;
     if (country == "") country = "UK";
     var fullAddress = address + ', ' + country;
     var radius = document.getElementById('radius').value;

     geocoder.getLatLng(fullAddress, function(latlng) {
     	if (!latlng) {
     		alert(address + ' not found - please try again.');
     	} else {
     		window.location='http://www.cafechurch.net/index.php?module=phpwsbusinesses&BUSINESSES_MAN_OP=listlocal&category=9&postcode=' + address + '&radius=' + radius + '&lat=' + latlng.lat() + '&lng=' + latlng.lng();
     	}
     });
}

// Creates a marker whose info window displays the given number
function createMarker(latlng, info) {
        var icon = new GIcon();
        icon.image = "themes/cafe2/img/cafechurchsmall.png";
        icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        icon.iconSize = new GSize(29, 28);
        icon.shadowSize = new GSize(37, 34);
        icon.iconAnchor = new GPoint(9, 34);
        icon.infoWindowAnchor = new GPoint(30, 1);

	var marker = new GMarker(latlng, icon);
	GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml( info ); } );
	return marker;
}

function DoMap() {
	var markerinfo;
	
	if (GBrowserIsCompatible()) {
		//clear the timer now
		clearTimeout( timerID );
		timerID = null;
		
		var mapdiv = document.getElementById( 'map' + currentCafeChurch );
		if (mapdiv) {
			var map = new GMap( mapdiv );
			
			map.addControl(new GSmallMapControl());
			
			// add the markers from an xml file in the root
			var request = GXmlHttp.create();
			request.open( "GET", 'markers'+currentCafeChurch+'.xml', true );
			request.onreadystatechange = function() {
				if (request.readyState == 4) {
					var xmlDoc = request.responseXML;
					var markers = xmlDoc.documentElement.getElementsByTagName("marker");
					
					for (var i = 0; i < markers.length; i++) {
						// make new point from lat/lng
						var point = new GPoint( parseFloat( markers[i].getAttribute( "lng" ) ), parseFloat( markers[i].getAttribute( "lat" ) ) );
						// centre map around first marker
						if (i == 0) {
							map.centerAndZoom( point, 3 );
						}
						// get point details
						if (markers[i].childNodes.length > 0) {
							markerinfo = markers[i].childNodes[0].nodeValue;
						}
						// add overlay for marker
						map.addOverlay( createMarker( point, markerinfo ) );
					}
				}
			}
			request.send( null );
		// fail gracefully if no map div found
		} else {
			var infoLabel = document.getElementById( 'expand' + currentCafeChurch );
			if (infoLabel)
				infoLabel.innerHTML = "Sorry, a google map error has occured.";
		}
	// fail gracefully if browser doesn't support googlemaps
	} else {
		var infoLabel = document.getElementById( 'expand' + currentCafeChurch );
		if (infoLabel)
			infoLabel.innerHTML = "Sorry, your browser does not support google maps.";
	}
}

function DoMapView() {
	if (GBrowserIsCompatible()) {
		var mapdiv = document.getElementById( 'viewmap' );
		var Lng = document.getElementById( 'Longitude' );
		var Lat = document.getElementById( 'Latitude' );
		if (mapdiv) {
	 		if (Lng && Lat) {
	 			if (viewmap == null) {
					viewmap = new GMap2(mapdiv);
					viewmap.addControl(new GSmallMapControl());
				}
				var LatLng = new GLatLng( parseFloat( Lat.value ), parseFloat( Lng.value ) );
				viewmap.setCenter(LatLng, 13, G_NORMAL_MAP);
				// clear any previous overlays
				viewmap.clearOverlays();
				// add overlay for marker
				viewmap.addOverlay(createMarker(LatLng, "cafechurch"));
			} else {
				mapdiv.innerHTML = "Location not yet set.";
			}
		// fail gracefully if no map div found
		} else {
			mapdiv.innerHTML = "Sorry, a google map error has occured.";
		}
	// fail gracefully if browser doesn't support googlemaps
	} else {
		mapdiv.innerHTML = "Sorry, your browser does not support google maps.";
	}
}

function LoadEditMap() {
	//clear the timer now
	clearTimeout( EditMapTimerID );
	timerID = null;
	var mapdiv = document.getElementById( 'editmap' );
	if (mapdiv) {
			editmap = null;
			editmap = new GMap2(mapdiv);
			editmap.addControl(new GSmallMapControl());
			// lng / lat not blank  - plot this position
			
			// there are no ID tags on these input fields, - they are built deep in phpwebsite which I'm not about to alter
			// therefore need to look up the elements collection by name (assume first element).
			
			if ((document.getElementsByName('Business_custom2')[0].value !="")
				&& (document.getElementsByName('Business_custom1')[0].value != "")) {
				var LatLng = new GLatLng(document.getElementsByName('Business_custom1')[0].value,
							 document.getElementsByName('Business_custom2')[0].value);
				var marker = new GMarker(LatLng, {draggable: true});
				GEvent.addListener(marker, "dragend", function() { 
					document.getElementsByName('Business_custom2')[0].value = marker.getLatLng().lng();
					document.getElementsByName('Business_custom1')[0].value = marker.getLatLng().lat();}
				);
				editmap.setCenter(LatLng, 13, G_NORMAL_MAP);
				// add the marker now
				editmap.addOverlay(marker); 
			} else {
				// show whole country - no position set
				editmap.setCenter(new GLatLng( 54.41892996865827, -3.93310546875 ), 5, G_NORMAL_MAP);
			}
	}
}

function DoMapFindPostcode() {
	var postcode = document.BUSINESSES_Business_edit.Business_company_zip;
	//alert("find postcode " + postcode.value);
	var mapdiv = document.getElementById( 'editmap' );
	if (mapdiv) {
		postcodeSearch = new GlocalSearch();
		postcodeSearch.setSearchCompleteCallback(null, 
		function() {
			if (postcodeSearch.results[0]) {    
				var resultLat = postcodeSearch.results[0].lat;
				var resultLng = postcodeSearch.results[0].lng;
				var LatLng = new GLatLng(resultLat,resultLng);
				var marker = new GMarker(LatLng, {draggable: true});
				
				GEvent.addListener(marker, "dragend", function() { 
					document.getElementsByName('Business_custom2')[0].value = marker.getLatLng().lng();
					document.getElementsByName('Business_custom1')[0].value = marker.getLatLng().lat();}
				);
				
				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowHtml(document.getElementById('hostname').value);}
				);
				document.getElementsByName('Business_custom2')[0].value = marker.getLatLng().lng();
				document.getElementsByName('Business_custom1')[0].value = marker.getLatLng().lat();
				// clear any previous overlays
				editmap.clearOverlays();
				// add the marker now
				editmap.addOverlay(marker);
				editmap.setCenter(LatLng, 13, G_NORMAL_MAP);
			}
		}
		);  
		postcodeSearch.execute(postcode.value + ", UK");
	}
	else {
	alert("mapdiv not found");
	}
}

function StartMapLoadTimer() {
	// do any initialisation stuff...
	if (GBrowserIsCompatible()) {
        	geocoder = new GClientGeocoder();
        }
	// start a timer for 1/2 second - should be long enough for the block to load and map div to be valid
	EditMapTimerID = self.setTimeout( "LoadEditMap()", 800 );
}

// This is called from mycafechurch.js, function "ShowCafeChurch"
function LoadMap( cafechurch ) {
	currentCafeChurch = cafechurch;
	
	// start a timer for 1/2 second - should be long enough for the block to load and map div to be valid
	timerID = self.setTimeout( "DoMap()", 500 );
}


//]]>
