//<![CDATA[
//	Declare variables
	var map = null;
    var geocoder = null;
//  var toggleState = 1;
    var iconBlue = new GIcon(); 
    iconBlue.image = 'http://www.vaservice.org/global/image/mm_20_blue.png';
    iconBlue.shadow = 'http://www.vaservice.org/global/image/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);
    var iconRed = new GIcon(); 
    iconRed.image = 'http://www.vaservice.org/global/image/mm_20_red.png';
    iconRed.shadow = 'http://www.vaservice.org/global/image/mm_20_shadow.png';
    iconRed.iconSize = new GSize(12, 20);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);
    var iconGreen = new GIcon(); 
    iconGreen.image = 'http://www.vaservice.org/global/image/mm_20_green.png';
    iconGreen.shadow = 'http://www.vaservice.org/global/image/mm_20_shadow.png';
    iconGreen.iconSize = new GSize(12, 20);
    iconGreen.shadowSize = new GSize(22, 20);
    iconGreen.iconAnchor = new GPoint(6, 20);
    iconGreen.infoWindowAnchor = new GPoint(5, 1);		
    var iconYellow = new GIcon(); 
    iconYellow.image = 'http://www.vaservice.org/global/image/mm_20_yellow.png';
    iconYellow.shadow = 'http://www.vaservice.org/global/image/mm_20_shadow.png';
    iconYellow.iconSize = new GSize(12, 20);
    iconYellow.shadowSize = new GSize(22, 20);
    iconYellow.iconAnchor = new GPoint(6, 20);
    iconYellow.infoWindowAnchor = new GPoint(5, 1);	
    var customIcons = [];
    customIcons["seniorcorps"] = iconBlue;
    customIcons["americorps"] = iconRed;
	customIcons["learnserve"] = iconGreen;
	customIcons["volunteer"] = iconYellow;	
    var markerGroups = { "americorps": [], "learnserve": [], "seniorcorps": [], "volunteer": []};	 
//	GMaps load function on window.load
    function loadMap() {
	if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();		
		map = new GMap2(document.getElementById("map"));
// 	Background loading graphic underneath the tiles
      	document.getElementById("map").style.backgroundImage = "url(http://www.vaservice.org/global/image/map_loading.gif)";
		map.setCenter(new GLatLng(38.0740, -79.5520), 7);
		map.addControl(new GSmallMapControl());
//		map.addControl(new GMapTypeControl());
//	Cycle through initial load XML for all service org markers and attributes
        GDownloadUrl("http://www.vaservice.org/go/training/servicemap.xml", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var orgname = markers[i].getAttribute("orgname");
            var pname = markers[i].getAttribute("pname");
            var director = markers[i].getAttribute("director");				
            var address = markers[i].getAttribute("address");
			var phone = markers[i].getAttribute("phone");
			var phoneext = markers[i].getAttribute("phoneext");				
			var email = markers[i].getAttribute("email");
			var url = markers[i].getAttribute("url");
			var display_url = markers[i].getAttribute("display_url");
			var area = markers[i].getAttribute("area");				
			var type = markers[i].getAttribute("type");
			var category = markers[i].getAttribute("category");	
			var category_url = markers[i].getAttribute("category_url");	
			var image = markers[i].getAttribute("image");												
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("long")));					
            var marker = createMarker(point, orgname, pname, director, address, phone, phoneext, email, url, display_url, area, type, category, category_url, image);
            map.addOverlay(marker);
          };
        });
	}
// display a warning if the browser was not compatible
    else {
      alert("Sorry, Google Maps is not compatible with this browser");
	}
	};
//	Begin function to avoid using body tag for load/unload
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
		window.onload = func;
	  } else {
		window.onload = function() {
		  if (oldonload) {oldonload();}
		  func();
		};
	  }
	};
	addLoadEvent(loadMap);
// arrange for our onunload handler to 'listen' for onunload events
	if (window.attachEvent) {
			window.attachEvent("onunload", function() {
					GUnload();      // Internet Explorer
			});
	} else {
			window.addEventListener("unload", function() {
					GUnload(); // Firefox and standard browsers
			}, false);
	}
// 	End new function to avoid using body tag for load/unload	
//	Begin function to detect if user presses Return or Enter from keyboard
    function submitEnter(myfield,e) {
        var keycode;
        if (window.event) {
        keycode = window.event.keyCode;
        } else if (e) {
        keycode = e.which;
        } else {
        return true;
		}
        if (keycode == 13)
        {
        searchLocations();
        return false;
        } else {
        return true;
        }
    };
//	Begin function to gecode user submitted address	
   function searchLocations() {
     var address = document.getElementById('addressInput').value;
     geocoder.getLatLng(address, function(latlng) {
//	if/else to determine if geocode was successful. If not throw alert, if so run function searchLocationsNear 
       if (!latlng) {
         alert('Your address \"' + address + '\" was not found. Please try again.');
       } else {searchLocationsNear(latlng);}
     });
   };
//	If geocoding was successful pass user submitted variables (address lat and lng, radius) to service org and radius query
   function searchLocationsNear(center) {
     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = '/go/training/servicemap_radius.xml?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');
       map.clearOverlays();
       var sidebar = document.getElementById('sidebar');
       sidebar.innerHTML = '';
// If statement to determine if no markers are returned. If so return no results found and instructions in sidebar	
       if (markers.length == 0) {
         sidebar.innerHTML = '<p class=\"pubdate\">No results were found.<br /><br />Try one of the following search tips:<br /><br />1. Increase the distance of your search.<br /><br />2. Check the spelling or try varying the spelling of your location.<br /><br />3. Make sure you have the correct city, state or zip code associated with your location.<br /><br />4. Make sure you use one of the following formats for searching:<br /> - street address, city, state<br /> - city, state<br /> - zip code</p>';
         map.setCenter(new GLatLng(38.0740, -79.5520), 7);
         return;
       }
//	Declare var bounds and cycle through XML for markers and attributes and 
       	var bounds = new GLatLngBounds();
		for (var i = 0; i < markers.length; i++) {									
            var orgname = markers[i].getAttribute("orgname");
            var pname = markers[i].getAttribute("pname");
            var director = markers[i].getAttribute("director");			
            var address = markers[i].getAttribute("address");
			var phone = markers[i].getAttribute("phone");
			var phoneext = markers[i].getAttribute("phoneext");			
			var email = markers[i].getAttribute("email");
			var url = markers[i].getAttribute("url");
			var display_url = markers[i].getAttribute("display_url");
			var area = markers[i].getAttribute("area");				
			var type = markers[i].getAttribute("type");
			var category = markers[i].getAttribute("category");
			var category_url = markers[i].getAttribute("category_url");	
			var image = markers[i].getAttribute("image");
			var distance = parseFloat(markers[i].getAttribute("distance"));				
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                    parseFloat(markers[i].getAttribute("long")));																			
            var marker = createMarker(point, orgname, pname, director, address, phone, phoneext, email, url, display_url, area, type, category, category_url, image);
            map.addOverlay(marker);
         	var sidebarEntry = createSidebarEntry(marker, orgname, address, distance, type, category, image);
        	sidebar.appendChild(sidebarEntry);
         	bounds.extend(point);
       	};
//	Set map center and zoom level according to latlng bounds and radius		
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
     });
   };
//	Create markers according to results
    function createMarker(point, orgname, pname, director, address, phone, phoneext, email, url, display_url, area, type, category, category_url, image) {
      var marker = new GMarker(point, customIcons[type]);
      markerGroups[type].push(marker);
      var html = "<div style=\"width:350px; height:300px;\"><p><img style=\"padding:0 5px 0 0; float:right;\" src=\""+ image +"\" width=\"80\" height=\"80\" alt=\"logo\" /><b>"+ orgname +"</b><br />"+ pname +"</p><p>Director: "+ director +"<br />Address: "+ address +"<br />Phone: "+ phone +"&nbsp;"+ phoneext +"<br />Email: <a href=\"mailto:"+ email +"?subject= Virginia Service Map Inquiry\">"+ email +"</a><br />Web: <a href=\""+ url +"\">"+ display_url +"</a></p><p>Category: <a href=\""+ category_url +"\">"+ category +"</a><br />Areas Served: "+ area +"<br /><a href=\"http://maps.google.com/maps?daddr="+ address +"\">Get directions</a></p></div>";
      GEvent.addListener(marker, 'click', function() {marker.openInfoWindowHtml(html);});
      return marker;
    };
//	Create sidebar entries html and style according to results	
    function createSidebarEntry(marker, orgname, address, distance, type, category, image) {
      var div = document.createElement('div');
      var html = '<span class=\"pubdate\"><strong>' + orgname + '</strong><br /><span class="required">Distance: ' + distance.toFixed(1) + ' mi</span><br />' + address + '<br /><em>' + category + '</em></span>';
      div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.paddingTop= '5px';
      div.style.paddingRight= '3px';
      div.style.paddingBottom= '5px';
      div.style.paddingLeft= '3px';	  
      div.style.borderTop= '1px dotted #bbbbbb';	  
//	  div.style.padding = '3px'; 
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#fff';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#eee';
      });
      return div;
    };
/*	Old toggle function
    function toggleGroup(type) {
      for (var i = 0; i < markerGroups[type].length; i++) {
        var marker = markerGroups[type][i];
        if (marker.isHidden()) {marker.show();} else {marker.hide();}
      }; 
    };
*/
//]]>
