/** @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 gIconUred = null;
var gIconSred = null;
var gIconXred = null;
var gIconXblue = null;
var gIconAddr = null;
var gLat, gLng, gLoadCount;

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 CreateIcon(iconType, iconColor)
{
//	iconLetter = MapTypeToName(iconType);

	var iconLetter = 'C';
	
	if (iconType == 'Brownfield')
		iconLetter = 'B';
	else
	if (iconType == 'SuperFund')
		iconLetter = 'S';
	else
	if (iconType == 'LUSTs')
		iconLetter = 'U';

	if (gIconXred == null)
	{
		gIconXred   = CreateNewIcon('X', 'red'  );
		gIconCred   = CreateNewIcon('C', 'red'  );
		gIconBred   = CreateNewIcon('B', 'red'  );
		gIconSred   = CreateNewIcon('S', 'red'  );
		gIconUred   = CreateNewIcon('U', '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 == 'U')
				return (gIconUred);
			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 };

	var marker = new GMarker(new GLatLng(lat, lng), markerOptions);
	var html =  '<b>' + name + '</b><br>' +
				address + '<br><br>' +
				'<span class="sponsor">' +
					'<a href="http://maps.SaferBuilding.com/MoreInfo.php?p=' + ref + '" target="_blank">More Info</a>...&nbsp;&nbsp;&nbsp;' +
					'<a href="http://maps.SaferBuilding.com/Comment.php?p='  + 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>';

	GEvent.addListener(marker, 'click', function()
	{
        marker.openInfoWindowHtml(html, {maxWidth:400});
	});
      
	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 	= new Array();
	
	/** @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;
	
	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;
	 }	
	
	map.setCenter(new GLatLng(Lat, Lng), Zoom);

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

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

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 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 len = markers.length;		
	
//	GLog.write(data);
//	GLog.write('Markers Downloaded: '+len);

//			for (var i=0; i < 100 ; i++)
	for (var i=0; i < len ; i++)
	{
		Title 	  = markers[i].getAttribute("Title");
		Address   = markers[i].getAttribute("Addr");
		LatMarker = markers[i].getAttribute("Lat");
		LngMarker = markers[i].getAttribute("Lng");
		Desc 	  = markers[i].getAttribute("Desc");
		LocType   = markers[i].getAttribute("Type");
		Ref 	  = markers[i].getAttribute("Ref");
		MinZoom   = markers[i].getAttribute("MinZoom");

		if (MinZoom < 7)   // fast
		{
			batch.push(createMarker(LatMarker, LngMarker, Title, Address + '<BR><BR>' + Desc, LocType, Ref));
		}
		else
		{
			batchSF.push(createMarker(LatMarker, LngMarker, Title, Address + '<BR><BR>' + Desc, LocType, Ref));		// didn't make a difference
		}
		
		// This is where you would display the information about the actual item if you were going to
		// display it in a list.
	}

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

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

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

	TotalMarkers = gMkrMgr.getMarkerCount((map.getCurrentMapType()).getMaximumResolution());

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

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

		LoadMapMarkers2(gLat, gLng);
	}
}
		
function LoadMapMarkers(Lat, Lng)
{
	gLoadCount = 0;

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

	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;
	
		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++;
	
		GDownloadUrl(URL, LoadMarkersCallback);
	}
}

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.

						place = response.Placemark[0];
						point = new GLatLng(place.Point.coordinates[1],
											place.Point.coordinates[0]);
		
						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);
	
						map.setCenter(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 = [];

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

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("+", " ");
		
		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);
}
