//<![CDATA[

// ====== create variables ======
var myClick;
var goTo;
var GTM;
var defaultLocation;
var readXML;
var clickedPixel;

function loadmap() {
	if (GBrowserIsCompatible()) {
		
		// ====== create holder for markers ======
		var gmarkers = [];

		// ====== function for sidebar click ======
		myClick = function(i) {
			GEvent.trigger(gmarkers[i], "click");
			var point = gmarkers[i].getPoint();
			map.setCenter(point, 16);
		}
		
		goTo = function(lat,lng,zoom) {
			point = new GLatLng(lat,lng);
			map.setCenter(point,zoom);
			var tempMarker = new GMarker(point);
			map.addOverlay(tempMarker);
		}


		// ====== create geocoder client ======
		var geocoder = new GClientGeocoder();

		// ====== Array for decoding the failure codes ======
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
		reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
		reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

		// ====== function for Go To Address box ======
		
		// ====== Geocoding ======
		GTM = function(check) {
			geocoder.getLocations(check, function (result) {
				if (result.Status.code == G_GEO_SUCCESS) {
					if (result.Placemark.length > 1) {
						window.parent.$("#addressReturns").html("");
						window.parent.$("#addressReturns").append("<div id='iframe_format'>Did you mean:</div>");
						for (var i=0; i<result.Placemark.length; i++) {
							place = result.Placemark[i];
							lat = place.Point.coordinates[1];
							lng = place.Point.coordinates[0];
							var N = place.ExtendedData.LatLonBox.north;
							var S = place.ExtendedData.LatLonBox.south;
							var E = place.ExtendedData.LatLonBox.east;
							var W = place.ExtendedData.LatLonBox.west;
							var bounds = new GLatLngBounds(new GLatLng(S,W), new GLatLng(N,E));
							var zoom = map.getBoundsZoomLevel(bounds);
							window.parent.$("#addressReturns").append("<br />"+(i+1)+": <a href='javascript:void(0);' onclick=\"window.parent.$('#gtm').attr('value','"+result.Placemark[i].address+"');window.parent.tb_remove();window.parent.goTo('"+lat+"','"+lng+"','"+zoom+"')\">"+result.Placemark[i].address+"<\/a>");
						}
						window.parent.$("#addressReturns").append("<br /><br /><div id='iframe_format'>or<br /><br /><a href='javascript:void(0);' onclick=\"window.parent.$('#gtm').attr('value','enter an address or notification area...');window.parent.$('#gtm').css({'color' : '#999999'});window.parent.tb_remove()\">Cancel Search</a></div>");
						window.parent.tb_show("","#TB_inline?height=225&width=350&inlineId=addressReturns&modal=true","");
					} else {
						place = result.Placemark[0];
						lat = place.Point.coordinates[1];
						lng = place.Point.coordinates[0];
						var N = place.ExtendedData.LatLonBox.north;
						var S = place.ExtendedData.LatLonBox.south;
						var E = place.ExtendedData.LatLonBox.east;
						var W = place.ExtendedData.LatLonBox.west;
						var bounds = new GLatLngBounds(new GLatLng(S,W), new GLatLng(N,E));
						var zoom = map.getBoundsZoomLevel(bounds);
						goTo(lat,lng,zoom);
					}
				} else {
					var reason="Code "+result.Status.code;
					if (reasons[result.Status.code]) {
						reason = reasons[result.Status.code]
					} 
					alert('Sorry! We were unable to find "' + check + '"\r\n\r\n' + reason);
				}
			}
			);
		}

		// ====== function for Default Location ======
		
		defaultLocation = function() {
		  map.setCenter(new GLatLng(37.0625,-95.677068), 4, G_HYBRID_MAP);
		}

		// ====== function to create tabbed markers ======
		function createTabbedMarker(point,label,tabs,tooltip) {
			var marker = new GMarker(point,{icon:Icon,title:tooltip});
			var marker_num = label;
			marker.marker_num = marker_num;
			marker.tabs = tabs;
			gmarkers[marker_num] = marker;
			GEvent.addListener(gmarkers[marker_num], "click", function() {
				marker.openInfoWindowTabsHtml(gmarkers[marker_num].tabs,{maxWidth:300});
			});
			return marker;
		}
		
		// ====== function to get node value ======
		function getNodeValue(Element) {
			if ((Element.length>0) && Element[0] && Element[0].firstChild && Element[0].firstChild.nodeValue) {
				return Element[0].firstChild.nodeValue;
			}
		}

		// ====== create the map ======
		var map = new GMap2(document.getElementById("map"));      
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.setCenter(new GLatLng(37.0625,-95.677068), 4, G_HYBRID_MAP);
		
		new GKeyboardHandler(map);
		var Icon = new GIcon();
		Icon.shadow = "./images/shadow.png";
		Icon.iconSize = new GSize(36.0, 40.0);
		Icon.shadowSize = new GSize(57.0, 40.0);
		Icon.iconAnchor = new GPoint(18.0, 20.0);
		Icon.infoWindowAnchor = new GPoint(18.0, 20.0);

		/*
		// ====== create the context menu div ======
		var contextmenu = document.createElement("div");
		contextmenu.style.visibility="hidden";
		contextmenu.style.background="#ffffff";
		contextmenu.style.border="1px solid #8888FF";
		contextmenu.innerHTML = '<a href="javascript:void(0);" onclick="zoomIn()" class="context"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;</div></a>'
							+ '<a href="javascript:void(0);" onclick="zoomOut()" class="context"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:void(0);" onclick="zoomInHere()" class="context"><div class="context">&nbsp;&nbsp;Zoom in here&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:void(0);" onclick="zoomOutHere()" class="context"><div class="context">&nbsp;&nbsp;Zoom out here&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:void(0);" onclick="centerMapHere()" class="context"><div class="context">&nbsp;&nbsp;Center map here&nbsp;&nbsp;</div></a>';
		map.getContainer().appendChild(contextmenu);

		// ====== listen for singlerightclick ======
		GEvent.addListener(map,"singlerightclick",function(pixel,tile) {
		clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
		if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
		if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
		pos.apply(contextmenu);
		contextmenu.style.visibility = "visible";
		});

		function zoomIn() {
			map.zoomIn();
			contextmenu.style.visibility="hidden";
		}      
		
		function zoomOut() {
			map.zoomOut();
			contextmenu.style.visibility="hidden";
		}      
		
		function zoomInHere() {
			var point = map.fromContainerPixelToLatLng(clickedPixel)
			map.zoomIn(point,true);
			contextmenu.style.visibility="hidden";
		}      
		
		function zoomOutHere() {
			var point = map.fromContainerPixelToLatLng(clickedPixel)
			map.setCenter(point,map.getZoom()-1); // There is no map.zoomOut() equivalent
			contextmenu.style.visibility="hidden";
		}      
		
		function centerMapHere() {
			var point = map.fromContainerPixelToLatLng(clickedPixel)
			map.setCenter(point);
			contextmenu.style.visibility="hidden";
			}
		
		// ====== close the context menu ======
		GEvent.addListener(map, "click", function() {
			contextmenu.style.visibility="hidden";
		});
		
		*/
		
		// ====== read the data ======
		readXML = function(url) {
			var request = GXmlHttp.create();
			request.open("GET", url, true);
			request.onreadystatechange = function() {
			
			if (request.readyState == 4) {
				if ((request.status != 200) && (request.status != 304)) {
					alert("file not found: "+filename);
					return;
				}
			
			var xmlDoc = request.responseXML;
			
			// loop through markers and create an array
			var markers = xmlDoc.documentElement.getElementsByTagName("marker");
			
			// hide current info windows
			map.getInfoWindow().hide();
			map.clearOverlays();
			
			// clear current array of markers
			gmarkers = [];
			
			for (var i=0; i<markers.length; i++) {
				// create variables for attributes
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("lng"));
				var infoIcon = markers[i].getAttribute("icon");
				var label = markers[i].getAttribute("label");
				var textTip = markers[i].getAttribute("name");
				
				// give error if no lat/lng
				if (isNaN(lat) || isNaN(lng)) {
					alert("bad point "+i);
					continue;
				}
				
				var point = new GLatLng(lat,lng);
				
				// create variables for marker info
				tabInfo = markers[i].getElementsByTagName("tab");
				tabIcon = markers[i].getElementsByTagName("icon");
				
				tabs = new Array();
				
				if (tabInfo.length > 0) {
					
					for (var j=0; j<tabInfo.length; j++) {
						var tabLabel = getNodeValue(tabInfo[j].getElementsByTagName("label"));
						var tabHtml = getNodeValue(tabInfo[j].getElementsByTagName("contents"));
					
						if ((j==0) && (tabInfo.length > 2)){ // adjust width for number of tabs
							tabHtml = tabHtml;
						}
					
					tabs.push(new GInfoWindowTab(tabLabel,tabHtml));
					}
				} else {
					alert("no tabs point "+i); 
				}      
			
				// format marker
				var marker = createTabbedMarker(point,label,tabs,textTip);
				Icon.image = "./images/" + infoIcon + ".png";
				
				// add marker to map
				map.addOverlay(marker);
			} // var i=0; i<markers.length; i++
			} // request.readyState == 4
			} // request.onreadystatechange = function() {
			
			request.send(null);
			
			} // end readXML function
		
	} else { // GBrowserIsCompatible() */
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
} // loadmap()
//]]>