/** @preserve Copyright © 2008-2010 Yorick Phoenix /  Doesnt Stink Software. All Rights Reserved */

var geocoder = null; 
var map = null;
var gMarker = null;
var gMkrMgr = null;
var gIconCgreen = null;
var gIconXgreen = null;
var gIconBred = null;
var gIconCred = null;
var gIconLred = null;
var gIconSred = null;
var gIconXred = null;
var gIconXblue = null;
var gIconAddr = null;
var gLat, gLng, gLoadCount;
var gMarkers = [];
var gTimer = null;
var gAddress = '';

function BrowserCheck()
{
	if (GBrowserIsCompatible()) {}
	else
	{
		document.write(
			'<style type="text/css">' + 
			'.x18 { font-size: 18px; }' +
			'</style>' +
			'<center>' +
			'<p class="x18"><BR>Your Browser is not supported for Map Display<BR>' +
			'<p class="x18">Supported Browsers include:<BR><BR>' + 
			'<table>' +
			'<tr><td><p class="x18">&nbsp;&bull;&nbsp;IE 6.0+ (Windows)</td></tr>' +
			'<tr><td><p class="x18">&nbsp;&bull;&nbsp;Firefox 2.0+ (Windows, Mac, Linux)</td></tr>' +
			'<tr><td><p class="x18">&nbsp;&bull;&nbsp;Safari 3.1+ (Mac)</td></tr>' +
			'</table>'
			);
	}
}

function GetIconLetter(iconType)
{
	var iconLetter = 'C';

	if (iconType == 'Brownfield')
		iconLetter = 'B';
	else
	if (iconType == 'SuperFund')
		iconLetter = 'S';
	else
	if (iconType == 'LUST')
		iconLetter = 'L';
	else
	if (iconType == 'address')
		iconLetter = '';

	return (iconLetter);
}

function CreateIcon(iconType, iconColor)
{
//	iconLetter = MapTypeToName(iconType);

	var iconLetter;

	iconLetter = GetIconLetter(iconType);
	
	if (gIconXred == null)
	{
		gIconXred   = CreateNewIcon('X', 'red'  );
		gIconCred   = CreateNewIcon('C', 'red'  );
		gIconBred   = CreateNewIcon('B', 'red'  );
		gIconSred   = CreateNewIcon('S', 'red'  );
		gIconLred   = CreateNewIcon('L', 'red'  );
		gIconXblue  = CreateNewIcon('X', 'blue' );
		gIconCgreen = CreateNewIcon('C', 'green');
		gIconXgreen = CreateNewIcon('X', 'green');
		gIconAddr	= CreateNewIcon('X', 'addr' );
	}
	
	if (iconType == 'address')
	{
		return (gIconAddr);
	}
	else
	switch (iconColor) {
		default:
		case 'red' :
			if (iconLetter == 'B')
				return (gIconBred);
			else
			if (iconLetter == 'S')
				return (gIconSred);
			else
			if (iconLetter == 'L')
				return (gIconLred);
			else
			if (iconLetter == 'C')
				return (gIconCred);
			else
				return (gIconXred);
		case 'blue':
				return (gIconXblue);
		case 'green' :
			if (iconLetter == 'C')
				return (gIconCgreen);
			else
				return (gIconXgreen);
			// add error checking
	}
}

function CreateNewIcon(iconLetter, iconColor)
{
	var newIcon = new GIcon(G_DEFAULT_ICON);

	if (iconColor == 'addr')
	{
		newIcon.image = "http://maps.google.com/mapfiles/ms/micons/homegardenbusiness.png";
		newIcon.shadow = "http://maps.google.com/mapfiles/ms/micons/homegardenbusiness.shadow.png";
	    newIcon.iconSize = new GSize(32, 32);
	    newIcon.shadowSize = new GSize(59, 32);
	    newIcon.iconAnchor = new GPoint(16, 16);
	    newIcon.infoWindowAnchor = new GPoint(16, 16);
	}
	else
	{
		newIcon.image = "/ToxMapAPI/icons/" + iconColor + "_Marker" + iconLetter + ".png";
	
		if (window.location.hostname == 'localhost' || window.location.hostname == '')
			newIcon.image = 'http://localhost/~yorick/toxmap' + newIcon.image;

		newIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	    newIcon.iconSize = new GSize(20, 34);
	    newIcon.shadowSize = new GSize(37, 34);
	    newIcon.iconAnchor = new GPoint(9, 34);
	    newIcon.infoWindowAnchor = new GPoint(9, 2);
	}

	return (newIcon);    
}

function MapTypeToName(iconType)
{
	return ('X');

/* 	GLog.write(iconType); */

	if (iconType == 'Permenant')    return ('P'); else
	if (iconType == 'Scheduled')	return ('S'); else
	if (iconType == 'Observed')		return ('O'); else
	if (iconType == 'HomeBusiness') return ('H'); else
	if (iconType == 'Public')		return ('P'); else
	if (iconType == 'Unknown')		return ('U'); else return ('X');
}

function createMarker(lat, lng, name, address, type, ref)
{
	var iconColor = (type == "HomeBusiness" || type == "Public") ? "green" : "red";
	var letteredIcon = CreateIcon(type, iconColor);
	
	markerOptions = { icon:letteredIcon, title:name };

	var marker = new GMarker(new GLatLng(lat, lng), markerOptions);
	var html =  '<span class="poi"><b>' + name + '</b><br>' +
				address + '<br><br>' +
				'<span class="sponsor">' +
					'<a href="/MoreInfo.php?poi=' + ref + '">More Info</a>...&nbsp;&nbsp;&nbsp;' +
					'<a href="http://maps.SaferBuilding.com/Comment.php?poi='  + ref + '" target="_blank">Add your comments</a>...&nbsp;&nbsp;&nbsp;' +
					'<a href="mailto:map_abuse@SaferBuilding.com?subject=Abuse%20Ref:' + ref + '&body=Please%20describe%20abuse%20below:%0a">Flag abuse</a>...' + 
				'</span></span>';

	GEvent.addListener(marker, 'click', function()
	{
		marker.openInfoWindowHtml(html, {maxWidth:450});		// was 400
		//RefreshAd();
	});

	return marker;
}

function createHomeMarker(lat, lng, name, address, type, ref)
{
	var iconColor = "blue";
	var letteredIcon = CreateIcon('address', iconColor);
	
	markerOptions = { icon:letteredIcon };

	var marker = new GMarker(new GLatLng(lat, lng), markerOptions);
	var html =  address;

	GEvent.addListener(marker, 'click',
		function()
		{
			marker.openInfoWindowHtml(html, {maxWidth:400});
		});

	return marker;
}

function BlankMapLoad(Lat, Lng, Zoom)
{
	var CurLoc 	= [];
	
	/** @const */ var BayAreaLat = 37.965854;				// these should be constants with compiler directives
	/** @const */ var BayAreaLng = -122.397308;	
	/** @const */ var BayAreaZoom = 10;
	
	/** @const */ var USALat =  34.62087;
	/** @const */ var USALng =-97;
	/** @const */ var USAzoom = 4;   

 	var CurLat  = BayAreaLat;
 	var	CurLng  = BayAreaLng;
 	var CurZoom = BayAreaZoom;

//	var CurLat  = USALat;
//	var	CurLng  = USALng;
//	var CurZoom = USAzoom;
	
	if (Lat == '')
	{
		sLatLng = readCookie('LatLng');
		if (sLatLng)
		{
			LatLng = GLatLng.fromUrlValue(sLatLng);
			Lat = LatLng.lat();
			Lng = LatLng.lng();
		}
	}
	
	if (Zoom == '')
	{	
		sZoom = readCookie('ZoomLevel');
		if (sZoom)
			Zoom = parseInt(sZoom);
	}

	map = new GMap2(document.getElementById("map"));

/*
	Lat = GetArg('Lat');		// get local from third party
	Lng = GetArg('Lng');
*/
	
	if ((Lat == "") || (Lat == "999") || (Lat == "999.000000"))	{	// refresh or duff address
		Lat = CurLat;					
		Lng = CurLng;		
		Zoom= CurZoom;
	 }	

//	GLog.write('Lat:  '+Lat);
//	GLog.write('Lng:  '+Lng);
//	GLog.write('Zoom: '+Zoom);

	LatLng = new GLatLng(Lat, Lng);
	map.setCenter(LatLng);
	map.setZoom(parseInt(Zoom));

	map.setUIToDefault();
	map.disableScrollWheelZoom();
	map.enableContinuousZoom();

//	map.addControl(new GLargeMapControl());
//	map.addControl(new GLargeMapControl3D());
//	map.addControl(new GMapTypeControl());

	CurLoc[0] = Lat;
	CurLoc[1] = Lng;
	CurLoc[2] = Zoom;
	
	SaveLocation(LatLng, Zoom);
	
	return (CurLoc);	
}

function UnloadToxMap()
{
	SaveMapLocation();
	GUnload();
}

function SaveMapLocation()
{
	if (map != null)
	{
		LatLng = map.getCenter();
		Zoom = map.getZoom();
		
		SaveLocation(LatLng, Zoom);
	}
	
	return (true);
}

function SaveLocation(LatLng, Zoom)
{
	iDays = 366;
	
	sLatLng = LatLng.toUrlValue();
	createCookie('LatLng', sLatLng, iDays);
	createCookie('ZoomLevel', Zoom, iDays);
}

function SaveSearchAddr(Address)
{
	iDays = 366;
	
	createCookie('Address', encodeURI(Address), iDays);
}

function MapLoad(Lat, Lng, Zoom)
{
	var CurLoc;

	if (!GBrowserIsCompatible())
		return;
	
//	GLog.write('Calling BlankMapLoad');
	CurLoc = BlankMapLoad(Lat, Lng, Zoom);

//	GLog.write('Calling LoadMapMarkers');
	LoadMapMarkers(CurLoc[0], CurLoc[1]);
}

function DisplayInfo(Ref)
{
	try
	{
		marker = gMarkers[Ref];
			
		if (marker.isHidden())
		{
			map.panTo(marker.getLatLng());
			marker.show();
		}
		
		GEvent.trigger(marker, 'click');
	}
	catch (err)
	{
	}
	
	return (false);
}

function decIt(field, target)
{
	var foo, curVal, newVal;

//	GLog.write("field: "+field+" / target: "+target);
	foo = document.getElementById(field);
	if (foo != null)
	{
		curVal = foo.innerHTML;
		if (curVal > target)
		{
			if (curVal > (target+10) && curVal > 19)
				newVal = curVal - 10;
			else
				newVal = curVal - 1;

			SetNewRegScore(field, newVal);

			StartTimer(field, target);
		}
	}
}

function StartTimer(field, target)
{
//	GLog.write("decIt('"+field+"',"+target+");");
//	StopTimer();

	gTimer = setTimeout("decIt('"+field+"',"+target+");", 50);
}

function StopTimer()
{
	if (gTimer != null)
	{
		clearTimeout(gTimer);
		gTimer = null;
	}
}

function GetScoresCallback(data)
{
	var xml 	= GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("marker");
	var len 	= markers.length;		
	var	NScore  = '';
	var HHScore = '';
	
	if (len > 0)
	{
		marker	  = markers[0];
	
		NScore 	  = marker.getAttribute('NScore');
		HHScore   = marker.getAttribute('HHScore');
	}
		
	foo = document.getElementById('HHS-NS')
	if (foo)
		SetScore('HHS-NS', NScore);

	foo = document.getElementById('HHS-HHS')
	if (foo)
		SetScore('HHS-HHS', HHScore);
}

function GetAddressScores(Address, Lat, Lng)
{
	try {
		URL = '/ToxMapAPI/ToxMapScore.php?Lat='+Lat+'&Lng='+Lng+'&Addr='+encodeURI(Address);
	
		if (GetArg('testDB') != "")
		{
			URL += '&testDB';
	//			alert('using Test DB');
		}
	
		if (window.location.hostname == 'localhost' || window.location.hostname == '')
			URL = 'http://localhost/~yorick/toxmap'+ URL;
	
	//		GLog.write('Host: '+window.location.hostname);
	//		GLog.write('URL: '+URL);
	//		GLog.write('Start1');
	
		GDownloadUrl(URL, GetScoresCallback);
	} catch (err) {};
}

function LoadMarkersCallback(data)
{
	var xml = GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("marker");

	var batch = [];
	var batchSF = [];
	
	var Title;
	var Address;
	var LatMarker;
	var LngMarker;
	var Desc;
	var LocType;
	var Ref;
	var MinZoom;
	var newMarker;
	var TotalMarkers;
	var iMaxResolution;

	var len = markers.length;		
	
//	GLog.write(data);
//	GLog.write('Markers Downloaded: '+len);

//			for (var i=0; i < 100 ; i++)

	var listTbl = document.getElementById('markList');
	var regScore = document.getElementById('HHS-RS');
	var newScore = -1;
	var txtHTML;
	var	listRow;
	
//	GLog.write('End');

	for (var i=0; i < len ; i++)
	{
		marker	  = markers[i];

		Title 	  = marker.getAttribute('Title');
		Address   = marker.getAttribute('Addr');
		LatMarker = marker.getAttribute('Lat');
		LngMarker = marker.getAttribute('Lng');
		Desc 	  = marker.getAttribute('Desc');
		LocType   = marker.getAttribute('Type');
		Ref 	  = marker.getAttribute('Ref');
		MinZoom   = marker.getAttribute('MinZoom');
		Dist	  = marker.getAttribute('Dist');
		Score	  = marker.getAttribute('Score');

		MinZoom = 0;

//		if (LocType == "LUST" && MinZoom == 0)
//			MinZoom = 13;

		if (Score != null)
			newScore = Score;

		newMarker = createMarker(LatMarker, LngMarker, Title, Address + '<BR><BR>' + Desc, LocType, Ref);

//		newMarker.Dist = Dist;
		
		gMarkers[Ref] = newMarker;

		if (MinZoom < 7)   // fast
		{
			batch.push(newMarker);
		}
		else
		{
			batchSF.push(newMarker);		// didn't make a difference
		}
		
		if (listTbl != null)
		{
			var iconLetter;
			
			iconLetter = GetIconLetter(LocType);

			try {
			listRow = listTbl.insertRow(-1);
			newCell0 = listRow.insertCell(0);
			newCell0.vAlign = 'top';
			// style='word-wrap: normal; word-break: break-strict'
			txtHTML = "<table width='100%' cellspacing='0' cellpadding='0' border='0'>"
					+ "<tr><td width='12' style='color: #505050;' valign='top'>"+iconLetter+":</td><td valign='top'><a href='MoreInfo.php?poi="+Ref+"' onclick='return DisplayInfo("+Ref+");'>"+Title+'</a></td>';
			if (Dist != -1)
			{
				txtHTML = txtHTML + "<td width='5'>&nbsp;</td>";
				txtHTML = txtHTML + "<td align='right' valign='top'>"+Dist+'&nbsp;mi</td>';
			}
			txtHTML = txtHTML + '</tr></table>';
			newCell0.innerHTML = txtHTML;
			
//			listRow.innerHTML = txtHTML;
	
			// This is where you would display the information about the actual item if you were going to
			// display it in a list.
			} catch (err) {};
		}
	}

	if (regScore && newScore != -1 && regScore != null)
	{
	//	GLog.write('newValue: '+newScore);
		StopTimer();
		StartTimer('HHS-RS', newScore);
	//	regScore.innerText = newValue;
	}

	gMkrMgr.addMarkers(batch, 0);
	gMkrMgr.addMarkers(batchSF, 13);  // this is fast was 7

	gMkrMgr.refresh();			// you need this to display items above

//	GLog.write('Finished Adding Markers');

	// Pin to 17 as MarkerManager doesn't support resolutions that are higher and returns NaN if you try.
	
	iMaxResolution = Math.min(17, (map.getCurrentMapType()).getMaximumResolution());
	
	TotalMarkers = gMkrMgr.getMarkerCount(iMaxResolution);

//	GLog.write('Total Markers: '+TotalMarkers);

/*
	fRange = 0.5;

	fLftLat = gLat - (gLoadCount * fRange);
	fRgtLat = gLat + (gLoadCount * fRange);
	fTopLng = gLng + (gLoadCount * fRange);
	fBotLng = gLng - (gLoadCount * fRange);

    var polyline = new GPolyline([
	    new GLatLng(fLftLat, fBotLng),
	    new GLatLng(fLftLat, fTopLng),
	    new GLatLng(fRgtLat, fTopLng),
	    new GLatLng(fRgtLat, fBotLng),
	    new GLatLng(fLftLat, fBotLng)
		], "#ff0000", 3);
	map.addOverlay(polyline);
*/

	if (TotalMarkers < 100)
	{
		// Need to widen our search and load more markers

		LoadMapMarkers2(gLat, gLng);
	}
}
		
function LoadMapMarkers(Lat, Lng)
{
	var listTbl = document.getElementById('markList');

	gLoadCount = 0;

	if (gMkrMgr == null)
		gMkrMgr = new MarkerManager(map);
	else
		gMkrMgr.clearMarkers();

	if (listTbl != null)
	{
		try {
		var divList = document.getElementById('divList');
		divList.innerHTML = '<table id="markList" cellpadding="0" cellpadding="0" border="0" width="180" height="200"><caption>Points of Interest<br><span style="font-size: 75%">(click for more information)</span><caption></table>';
		// <thead><caption>Points of Interest<caption></thead>
//		var x=listTbl.createCaption();
//		x.innerHTML="Points of Interest";
//		listTbl.tBodies[0].innerHTML = '';
		} catch(err) {};
	}

	StopTimer();
	
	if (document.getElementById('HHS-RS'))
		SetNewRegScore('HHS-RS', 100);

	gMarkers = [];		// Empty Marker Array

	LoadMapMarkers2(Lat, Lng);
}

function LoadMapMarkers2(Lat, Lng)
{
	var URL;

	if (gLoadCount < 5)	// Stop endless recusion for no datapoints
	{
		gLat = Lat;
		gLng = Lng;
		
		URL = '/ToxMapAPI/ToxMapXML.php?Lat='+Lat+'&Lng='+Lng+'&r='+gLoadCount+'&l=200';

		if (GetArg('testDB') != "")
		{
			URL += '&testDB';
//			alert('using Test DB');
		}

		if (window.location.hostname == 'localhost' || window.location.hostname == '')
			URL = 'http://localhost/~yorick/toxmap'+ URL;
	
//		GLog.write('Host: '+window.location.hostname);
//		GLog.write('URL: '+URL);
	
		gLoadCount++;
	
//		GLog.write('Start1');

		GDownloadUrl(URL, LoadMarkersCallback);

//		GLog.write('Start2');
	}
}

function ConfirmMapLoad()
{
	if (GBrowserIsCompatible())
	{
		BlankMapLoad(document.getElementById("Lat").value,
					 document.getElementById("Lng").value, 16);
	
		gMarker = AddNewMarker("X");
	}
}

function PrefillAddrInfoForm()
{
	document.getElementById('Lat').value = GetArg('Lat');
	document.getElementById('Lng').value = GetArg('Lng');
	document.getElementById('Address').value = GetArg('Address');
}

function GetLatLng(Lat, Lng)
{
//	GLog.write('in GetLatLng');

	document.getElementById(Lat).value = map.getCenter().lat().toFixed(6);
	document.getElementById(Lng).value = map.getCenter().lng().toFixed(6);

//	GLog.write('Lat:' + document.getElementById(Lat).value);
//	GLog.write('Lng:' + document.getElementById(Lng).value);
}

function FindAddress(address, bUpdateLatLng, bSelectAddress)
{
	LoadMapAtAddress(address, bUpdateLatLng, bSelectAddress, false);
}

function LoadMapAtAddress(address, bUpdateLatLng, bSelectAddress, bLoadMarkers)
{
	if (GBrowserIsCompatible())
	{
//		GLog.write('showAddress: ' + address);
	
		if (geocoder == null)
			geocoder = new GClientGeocoder();
	
		if (geocoder)
		{
	//		GLog.write('Have GeoCoder Object');
	
			geocoder.getLocations(address,
				function(response)
				{
					if (!response || response.Status.code != 200)
					{
						alert("Address:" + address + " not found");
						if (bUpdateLatLng)
						{
							document.getElementById("Lat").value = "999";
							document.getElementById("Lng").value = "999"
						}
						if (bSelectAddress)
						{
							document.getElementById("Address").focus();
						}
					}
					else
					{
						// Address found.

						gAddress = address;

						SaveSearchAddr(address);

						place = response.Placemark[0];

						gAddress = place.address;
						
						point = new GLatLng(place.Point.coordinates[1],
											place.Point.coordinates[0]);

						gLat = point.lat().toFixed(6);
						gLng = point.lng().toFixed(6);

						if (document.getElementById('HHS-NS') != null)
							GetAddressScores(gAddress, gLat, gLng);

						accuracy = place.AddressDetails.Accuracy;
					
//		 				GLog.write(accuracy);
					
// 0 - Unknown location.
// 1 - Country level accuracy.
// 2 - Region (state, province, prefecture, etc.) level accuracy.
// 3 - Sub-region (county, municipality, etc.) level accuracy.
// 4 - Town (city, village) level accuracy.
// 5 - Post code (zip code) level accuracy.
// 6 - Street level accuracy.
// 7 - Intersection level accuracy.
// 8 - Address level accuracy.
// 9 - Premise (building name, property name, shopping center, etc.) level accuracy.

						if (accuracy < 2) zoom = 5;
							else
						if (accuracy < 3) zoom = 6;
							else
						if (accuracy < 6) zoom = 11; //12;
							else zoom = 15; // 16;

//						zoom = 9;

						if (map == null)
							BlankMapLoad(point.lat().toFixed(6),point.lng().toFixed(6),zoom);
						else
						{
							map.setCenter(point, zoom);
							SaveLocation(point, zoom);
						}
		
						if (gMarker != null)
						{
							gMarker.setLatLng(point);
		//					GLog.write('marker.setLatLng');
						}
		
						if (bUpdateLatLng)
						{
							document.getElementById("Lat").value = point.lat().toFixed(6);
							document.getElementById("Lng").value = point.lng().toFixed(6);
		
	//	 					GLog.write(point.lat().toFixed(6) + '/' + point.lng().toFixed(6));
						}
		
		//				var marker = new GMarker(point, {draggable:true});
		//				document.getElementById("lat").value = marker.getPoint().lat().toFixed(6);
		//				document.getElementById("lng").value = marker.getPoint().lng().toFixed(6);
		//
		//				map.addOverlay(marker);
		//				GEvent.addListener(marker, "dragend", function()
		//				{
		//					document.getElementById("lat").value = marker.getPoint().lat().toFixed(6);
		//					document.getElementById("lng").value = marker.getPoint().lng().toFixed(6);
		//				});
		
						if (bLoadMarkers)
							LoadMapMarkers(point.lat().toFixed(6), point.lng().toFixed(6));
							
						if (gMkrMgr != null)
						{
							var batch = [];
							var listTbl = document.getElementById('markList');
							var txtHTML;

							newMarker = createHomeMarker(point.lat().toFixed(6), point.lng().toFixed(6), '', address, '', '');
							batch.push(newMarker);
							gMkrMgr.addMarkers(batch, 0);
							gMkrMgr.refresh();

							gMarkers[0] = newMarker;
													
							if (listTbl != null)
							{
								try {
								listRow = listTbl.insertRow(0);
								cell0 = listRow.insertCell(0)
								cell0.vAlign = 'top';
								txtHTML = "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr>"
										+ "<td width='12'>&nbsp;</td>"
										+ "<td valign='top'><a href='#' onclick='return DisplayInfo(0);'>"+address+'</a></td>'
										+ "<td width='5'>&nbsp;</td>"
										+ "<td align='right' valign='top'>0.00"+'&nbsp;mi</td>'
										+ "</tr></table>"
								cell0.innerHTML = txtHTML;
					
								} catch (err) {}
							}
						}
					}
				}
			);
		}
	}
}

function GetArg(name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	var argVal;

	if( results == null )
		return '';
	else
	{
		argVal = results[1];
		
		argVal = argVal.replace(/\+/g, " ");

		argVal = decodeURIComponent(argVal);
		
		return (argVal);
	}
}

function orderOfCreation(marker, b)
{
	return 1;
}

function AddNewMarker(markType)
{
	if (GBrowserIsCompatible())
	{
	//  	GLog.write('AddNewMarker');
	
		LatLng = map.getCenter();
	
	//  	GLog.write('LatLng: ' + LatLng.lat() + '/' + LatLng.lng());
	
		var letteredIcon = CreateIcon(markType, 'blue');
		
	//  	GLog.write('CreatedIcon');
	
		// Set up our GMarkerOptions object
		markerOptions = { icon:letteredIcon, draggable:true, zIndexProcess:orderOfCreation};
		var marker = new GMarker(LatLng, markerOptions);
	
	//  	GLog.write('Marker Created');
	
		map.addOverlay(marker);
		
		marker.bindInfoWindowHtml("Drag to the address of interest");
		
		GEvent.addListener(marker, "dragend", function()
		{
	//  		GLog.write('DragEnd'); 
			
			document.getElementById("Lat").value = marker.getPoint().lat().toFixed(6);
			document.getElementById("Lng").value = marker.getPoint().lng().toFixed(6);
	
	//  		GLog.write('Lat:' + document.getElementById("Lat").value);
		});
		
	// 	document.getElementById("Lat").value = marker.getPoint().lat().toFixed(6);
	// 	document.getElementById("Lng").value = marker.getPoint().lng().toFixed(6);
	
	//  	GLog.write('Updated Doc Lat / Lng');
	
	//  	GLog.write('End AddNewMarker');
	
		return (marker);
	}
}

function pausecomp(millis) 
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while(curDate-date < millis);
} 

function ValidateEntry(xForm, b2emailCheck, bAddressAlert, bCheckAddress, bCheckComment)
{
	if (bCheckAddress)
		CheckAddress(xForm);

	if (xForm.Title.value.length<=0)
		xForm.Title.value = DefTitle;
		
	if (xForm.Name.value.length<=0)
		xForm.Name.value = "Anonymous";
		
	if (bCheckComment)
	{
		if (xForm.Desc.value.length<=0)
		{
			alert("Please enter a comment");
			xForm.Desc.focus();
			return false;
		}
	}

//   	GLog.write('gDefAddr: '+gDefAddr);
//   	GLog.write('xForm.Address.value: '+xForm.Address.value);

	if (bCheckAddress && (xForm.Address.value.length<=0 || xForm.Address.value == gDefAddr))
	{
		alert("Please enter an address of interest");
		xForm.Address.focus();
		return false;
	}
	
	if (b2emailCheck == true)
	{
		if (xForm.Email.value.length <=0)
		{
			alert("Please Enter an Email Address");
			xForm.Email.focus();
			return false;
		}
	
		var emailStr = xForm.Email.value;
		if(emailStr.length >= 1)
		{
			var emailPat = /^[_a-zA-Z0-9-+]+(\.[_a-zA-Z0-9-+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,6})$/;
			var matchArray = emailStr.match(emailPat);
			if (matchArray == null) 
			{
				alert("Invalid or incorrectly formated email address");
				xForm.Email.focus();
				return false;
			}
		}
	
		if (xForm.Email.value != xForm.Email2.value)
		{
			alert("E-Mail addresses do not match");
			xForm.Email.focus();
			return false;
		}
	}
	
	if (bAddressAlert == true)
	{
// 		GLog.write('bAddressAlert == true');
// 		GLog.write('xForm.Lat.value:' + xForm.Lat.value);
		
		if (xForm.Lat.value == "999" || xForm.Lat.value == "999.000000")
		{
			alert("Address:" + xForm.Address.value + " not found");
			xForm.Address.focus();
			return (false);
		}
	}
	
// 	GLog.write('Validate Entry'); return false;

	return true;
}

function CheckAddress(xForm)
{
	if (GBrowserIsCompatible())
	{
	/* 	GLog.write('Address: ' + xForm.Address.value); */
	
		if (geocoder == null)
			geocoder = new GClientGeocoder();
	
		if (geocoder)
		{
			geocoder.getLatLng(xForm.Address.value,
	
				function(point)
				{
					if (!point)
					{
						xForm.Lat.value = xForm.Lng.value = 999;
					}
					else
					{
						xForm.Lat.value = point.lat();
						xForm.Lng.value = point.lng();
					}
		
		/*
					GLog.write('xForm.Lat.value: ' + xForm.Lat.value);
					GLog.write('xForm.Lng.value: ' + xForm.Lng.value);
		*/
				});
		}
	}
}

function AddNewAddress(address, step1, step2)
{
	if (GBrowserIsCompatible())
	{
		if (geocoder == null)
			geocoder = new GClientGeocoder();
	
		if (geocoder)
		{
			geocoder.getLatLng(address,
			function(point)
			{
				if (!point)
				{
					alert("Address: " + address + " not found");
				}
				else
				{
	/* 				GLog.write('showAddress: ' + address); */
	
					map.setCenter(point, 18);
	
					var letteredIcon = CreateIcon('X', 'blue');
	
					// Set up our GMarkerOptions object
					markerOptions = { icon:letteredIcon, draggable:true};
					var marker = new GMarker(point, markerOptions);
	
					document.getElementById("Address").value = address;
					document.getElementById("Lat").value = marker.getPoint().lat().toFixed(6);
					document.getElementById("Lng").value = marker.getPoint().lng().toFixed(6);
	
					map.addOverlay(marker);
					GEvent.addListener(marker, "dragend", function()
					{
						document.getElementById("Lat").value = marker.getPoint().lat().toFixed(6);
						document.getElementById("Lng").value = marker.getPoint().lng().toFixed(6);
					});
					
					NextStep(step1, step2);
				}
			});
		}
	}
}

function NextStep(curStep, nxtStep)
{
	document.getElementById(curStep).style.display = "none";
	document.getElementById(nxtStep).style.display = "block";
}

function showQuestions(xxx)
{
	document.getElementById(xxx).style.display='block';
//	document.getElementById('AddLoc').style.display='none';
}

function URLEncode(url)
{
	var encoded=escape(url);
	
	encoded = encoded.replace("+", "%2B");
	encoded = encoded.replace("/", "%2F"); 

	return (encoded);
}

function AddEntry(args)
{
	var addr;
	var alink = 'AddEntry.php?' + args;

	return (true);

	addr = document.getElementById("address");
	if (addr != null)
		if (addr.value != '' && addr.value != gDefAddr)
		{
			alink = alink + '&Addr=' + URLEncode(addr.value);

			if (map != null)
			{
				Lat = map.getCenter().lat().toFixed(6);
				Lng = map.getCenter().lng().toFixed(6);
		
				alink = alink + '&Lat=' + Lat + '&Lng=' + Lng;
			}
		}

	window.location.href = alink;

	return (false);
}

function UpdateURLSearch(searchVal)
{
	//	You can't do this as it causes a reload of the page in Safari.
	
	//	window.location.search = 'address='+searchVal;
}

function RefreshAd()
{
	var adSpace = document.getElementById("Ad_Space");

	if (adSpace != null)
		adSpace.innerHTML = adSpace.innerHTML + ' ';
}
