window.address;
window.coords;
window.lng;
window.lat;

getAddressField = function()
{
	"use strict";
	var obj = null, name = "dummy string", counter = 0;
	var tags = [];
	tags = document.getElementsByTagName('textarea');
	//wDebug(tags);
	for (var i=0; i<tags.length; i++)
	{
		obj = tags[i];
		name = tags[i].id;
		if ((name.indexOf('Address') >= 0) || (i > 29)) {break;}
	}
	return obj;
}

window.mapInitialize = function(lat, lng, zoom)
{
	var latlng = new google.maps.LatLng(lat, lng);
	var myOptions = { zoom: zoom, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
	window.mapSelector = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);
	//showAddress(lat, lng, undefined, zoom);
}

showAddress = function(lat, lng, physAddress, mapZoom)
{
	//var myLatlng = new google.maps.LatLng(parseFloat(window.lat), parseFloat(window.lng));
	var myLatlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
	mapZoom = mapZoom ? mapZoom : 17;
	if (window.mapSelector !== undefined)
	{
		window.mapSelector.setCenter(myLatlng);
		window.mapSelector.setZoom(mapZoom);
	}
	
	var mapOptions = 
	{
		zoom: mapZoom,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
	
	var marker = new google.maps.Marker(
	{
		position: myLatlng,
		animation: google.maps.Animation.DROP,
		map: map,
		title:companyTitle
	});
	
	google.maps.event.addListener(marker, 'click', goGoogleMaps);
	var addrField = getAddressField();
	var roAttr = (addrField !== null) ? addrField.getAttribute('readonly') : null;
	if ((roAttr === null) && (physAddress !== undefined) && (physAddress.trim() !== "") ) getAddressField().value = physAddress;
	window.address = physAddress;
	window.lng = lng;
	window.lat = lat;
	/*
	console.log(window.lat);
	console.log(window.lng);
	console.log(window.address);
	*/
}

goGoogleMaps = function()
{
	window.open('http://maps.google.co.za/maps?q='+window.address, '_blank');
}

coordsSearch = function(address)
{
	var geo = new google.maps.Geocoder();
	var geoRequest = {};
	if (address)
		geoRequest.address = address;
	else
	{
		var adf = getAddressField();
		geoRequest.address = (adf !== null) ? getAddressField().value : '';
	}
	geoRequest.bounds = new google.maps.LatLngBounds(new google.maps.LatLng(-35.2, 15.2,true), new google.maps.LatLng(-22.1, 33.6,true));
	geo.geocode(geoRequest, mapSearchCallback);
}

mapSearchCallback = function(result, status)
{
	var htmlA = "";
	var htmlB = "";
	var htmlC = "";
	var html = "";
	var lng, lat, address, coords;
	var cnt = 0;

	if (status=="OK")
	{
		htmlA = '<table class="searchResults">';
		htmlB = '<tr><td class="labelResultItem">Please select the correct address to display:</td></tr>';
		for (var i in result)
		{
			address 	= result[i].formatted_address.replace(/, South Africa/g,"").replace(/, ZA/g,"");
			coords 		= result[i].geometry.location;
			lng 		= result[i].geometry.location.lng();
			lat 		= result[i].geometry.location.lat();

			/*
			Details about the address can be gotten from result[i].address_components[x]:
			result[i].address_components[0].long_name = Hartenbos
			result[i].address_components[1].long_name = Mossel Bay
			result[i].address_components[2].long_name = South Africa
			result[i].address_components[3].long_name = 6520
			**Province missing....
			*/
			
			var loc = coords + "";
			var mapcoords = document.getElementById('mapCoords');
			if (mapcoords !== null)	mapcoords.innerHTML = loc;
			loc = loc.replace(/[\)\(]/g,"").replace(/ /g,"");
			var parts = loc.split(",");
			
			htmlC += '<tr>';
			htmlC += '	<td onclick="showAddress(\''+lat+'\', \''+lng+'\', \''+address+'\')" >';
			htmlC += 		address + '&nbsp;&nbsp;' + coords;
			htmlC += '	</td>';
			htmlC += '</tr>';
			cnt++;
			
		}
		if (cnt > 1) html = htmlA + htmlB + htmlC; else	html = htmlA + htmlC;
		html += "</table>";
		var srchres = document.getElementById('searchResults');
		if (srchres !== null) srchres.innerHTML = html;
		//showAddress(lng, lat, address); //load this address in the map on the screen.
	} //if status == "OK"
	
	if (status=="ZERO_RESULTS")
	{
		document.getElementById("searchResults").innerHTML = '<table class="noResults"><tr><td>The location could not be found. Please ensure the address is correct.</td></tr></table>';
	};
}

updateMapData = function()
{
	coordsSearch();
	if ((window.lng !== undefined) && (window.lat !== undefined)) mapInitialize(window.lat, window.lng, 9);
}
	
//Reverse Geocoding:
function getAddressFromCoords(latitude, longitude, addressFieldId)  //--> Get formatted address from given co-ordinates
{
	var geocoder = new google.maps.Geocoder;
	var latlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
	var obj = addressFieldId ? document.getElementById(addressFieldId) : null;
	var result = 'Failed to determine address';
	geocoder.geocode
	(
		{'location': latlng},
		function(results, status) 
		{
			if (status === 'OK') 
			{
				if (results[0]) 
				{
					result = results[0].formatted_address;
					if (obj.tagName.toLowerCase() == 'input')
						obj.value = result;
					else
						obj.innerHTML = result;
				} 
				else 
				{
					if (obj.tagName.toLowerCase() == 'input')
						obj.value = result;
					else
						obj.innerHTML = 'Address could not be detected.';
				}
			} 
			else 
			{
				if (obj.tagName.toLowerCase() == 'input')
					obj.value = result;
				else
					obj.innerHTML = 'Geocoder failed due to: ' + status;				
			}
		}
	);
	return result;
}

updateMarker = function(coords, physAddress, placeId)
{
	coords = coords + "";
	coords = coords.replace(/[\)\(]/g,"").replace(/ /g,"");
	var parts = coords.split(",");	
	var myLatlng = new google.maps.LatLng(parts[0]+0,parts[1]+0);
	
	// To remove the marker from the map
	marker.setMap(null);
	// To add the marker to the map, call setMap();
	//marker.setMap(map);
		
	marker = new google.maps.Marker(
	{
		position: myLatlng,
		map: map,
		title:companyTitle
	});
}
