	//global variables
	var map;	
    var mapParam;		
    var mapStatusMsg;
	var stationhtml = [];
	var iwhtml = [];
	var _centerlng = -91.2689209;
	var _centerlat = 48.011975;
	var _zoom = 8;	
	var _defaultEntranceZoom = 12;
	var infoOpened = false;	
	var mapTypeChanged = false;		
	var facility;
	var contractCode;
	var chosenEntrance;
	var permitType;
	var i = 0;
    var entrances = new Array();	
	var gmarkers = [];
	var gicons = [];
	var minimap = false;
	var entryDate;
	var permitTypeID;
	var label;
	
	function onLoad() { 
		try {
    		init();   
	   	} catch(e){}
			var latlng = new google.maps.LatLng(_centerlng, _centerlat);
			var myOptions = {
				zoom : _zoom,
				center : latlng,
				disableDefaultUI: true,
			    panControl: true,
			    panControlOptions: {
			        //position: google.maps.ControlPosition.LEFT_TOP //position creates issues with IE7 and IE8 (as of today, Oct. 6, 2011).
			    },	    
			    zoomControl: true,
			    zoomControlOptions: {
			        style: google.maps.ZoomControlStyle.SMALL/*,
			        position: google.maps.ControlPosition.LEFT_TOP*/
			    },	    
			    scaleControl: true,
			    mapTypeControl: true,
			    mapTypeControlOptions: {
			      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU/*,
			      position: google.maps.ControlPosition.RIGHT_TOP*/
			    },
				mapTypeId : google.maps.MapTypeId.ROADMAP
		}
			map = new google.maps.Map(document.getElementById("mapviewport"), myOptions);
			mapStatusMsg = new MapStatusControl();
		  	map.controls[google.maps.ControlPosition.TOP_LEFT].push(mapStatusMsg);
			infoWindow = new google.maps.InfoWindow();
			initIcons();
			createListeners();
	  		showMap();	  		  	 

	}
	
	function detailsViewOnLoad() {
		if (document.getElementById("mapviewport") != null) {
			try {
	    		init();   
		   	} catch(e){}

			var latlng = new google.maps.LatLng(_centerlng, _centerlat);
			var myOptions = {
				zoom : _defaultEntranceZoom,
				center : latlng,
				disableDefaultUI: true,
			    panControl: false,
			    zoomControl: false,
			    scaleControl: false,
			    mapTypeControl: false,
			    mapTypeId : google.maps.MapTypeId.ROADMAP
			}
			map = new google.maps.Map(document.getElementById("mapviewport"), myOptions);
			minimap = true;
			initIcons();			
			showMap();	  
		  		
		}
	}
	
	function initIcons() {
		var imageSize = new google.maps.Size(27, 27);
		var origin = new google.maps.Point(0,0);
		var iconAnchor = new google.maps.Point(6, 20);
		gicons["entrance"] = new google.maps.MarkerImage("/images/maps/pin_entrance.png",
				imageSize,
				origin,
				iconAnchor);
		gicons["coop"] = new google.maps.MarkerImage("/images/maps/pin_coop.png",
				imageSize,
				origin,
				iconAnchor);
    	gicons["issuing"] = new google.maps.MarkerImage("/images/maps/pin_issuing.png",
				imageSize,
				origin,
				iconAnchor);
	}
	
	function showMap() {		
	    getEntrancesAndStations();	 
	}
	
	function createListeners() {			
		google.maps.event.addListener(map, "idle", function() {			
			if (infoOpened == true ) { 				  
            	infoOpened = false; 
           	    return; 
		    } 		   	
		    if (mapTypeChanged == true) { 				  
            	mapTypeChanged = false;            	
		    }					  		
		} );
		google.maps.event.addListener(map, "click", function() {
			infoWindow.close();
		} );
		
	}			
	
	function showMarkers(){	
		if(i < entrances.length){
			var max = Math.min(i+20, entrances.length);	//select the minimum batch size of 20 entrances or the remainder of total entrances divided by 20				
			showStatus(max, entrances.length);	//show loading status bar
			while(i < max){			
				var parkID = entrances[i].getAttribute("contractCode") + entrances[i].getAttribute("parkid"); 															//loop thru all entrances to be plotted in this batch
				var entranceID = entrances[i].getAttribute("id"); 	
				var iconType = entrances[i].getAttribute("type");  	  											  						  					  						  					  					

       			var availStatus = entrances[i].getAttribute("status");
       			var statusLineTop = "";
       			var statusLineBottom = "";
       			var permitTypeInfo = "";
       			var entranceDetailsLink = "";
       			var bookButton;
       			if (iconType == "entrance") {       				
       				entranceDetailsLink = "/entranceDetails.do?topTabIndex=Permits&contractCode=" + entrances[i].getAttribute("contractCode") 
										+ "&parkId=" + entrances[i].getAttribute("parkid") + "&entranceId=" + entranceID;
						
					if (permitType != "")
						permitTypeInfo = "&permitTypeID=" + permitType;
						
	       			if (entrances[i].getAttribute("status") == "X" || entrances[i].getAttribute("status") == "C"
	       				|| entrances[i].getAttribute("status") == "W" || entrances[i].getAttribute("status") == "R" ) {
	       			    statusLineTop = "Not available";
	       				bookButton = "<a href=\"/entranceDetails.do?topTabIndex=Permits&contractCode=" + entrances[i].getAttribute("contractCode") 
	       							+ "&parkId=" + entrances[i].getAttribute("parkid") + "&entranceId=" + entranceID + permitTypeInfo       			
	       							+ "\" class=\"book next\" onclick=\"\">Find Next Avail. Date*</a>";
	       			} else if (entrances[i].getAttribute("status") == "A" || entrances[i].getAttribute("status") == "L") {
	       				if (entrances[i].getAttribute("status") == "A" ) {
	       					statusLineTop = "Available";
	       					statusLineBottom = "Book Now";
	       				} else if (entrances[i].getAttribute("status") == "L") {
	       					statusLineTop = "Accepting Lottery";
	       					statusLineBottom = "ApplyNow";
	       				}
	       				bookButton = "<a href=\"/entranceDetails.do?topTabIndex=Permits&contractCode=" + entrances[i].getAttribute("contractCode") 
	       							+ "&parkId=" + entrances[i].getAttribute("parkid") + "&entranceId=" + entranceID + permitTypeInfo
	       							+ "\" class=\"book now\" onclick=\"\">See Details</a>";
	       			} else { 	       			
	       				bookButton = "<a href=\"/entranceDetails.do?topTabIndex=Permits&contractCode=" + entrances[i].getAttribute("contractCode") 
	       							+ "&parkId=" + entrances[i].getAttribute("parkid") + "&entranceId=" + entranceID + permitTypeInfo	        							
	       							+ "\" class=\"book now\" onclick=\"\">Enter Date</a>";
	       			}
	       		}
				
				//prepare marker	
   				var point = new google.maps.LatLng(parseFloat(entrances[i].getAttribute("lat")), parseFloat(entrances[i].getAttribute("lng")));
    	        setInfoWindowHTML(entranceID, entrances[i], bookButton, entranceDetailsLink, statusLineTop, statusLineBottom);
	  	 	  	var	marker = createMarker(point, entranceID, entrances[i].getAttribute("name"), iwhtml[entranceID], iconType, entranceDetailsLink);
		 	  
		 	  	if (!minimap) {
			 	  	// Generate the link in the mapviewcampgroundlist 
		  			if ((("ENTRANCES" == mapParam || "SEARCH" == mapParam) && iconType == "entrance" && availStatus != "NL" ) 
		 	  			|| ("STATIONS" == mapParam && (iconType == "coop" || iconType == "issuing"))) {	  		
		  				html = getResultsListHTML(entranceID, gmarkers[entranceID]);	 	  			
		  				document.getElementById("mapentrancelist").innerHTML = document.getElementById("mapentrancelist").innerHTML + html;				
			 	  	}		 
		 	  	}
		 	  	if (chosenEntrance != null && chosenEntrance == entranceID) {		 	  		
	        		if (minimap) {	        			        			
	        			map.panTo(point);	        			
	        		} else {
	        			clickResult(chosenEntrance);
	        		}
			 	}		 	  	
				i++;
			}	//end while							
			window.setTimeout(showMarkers,1);
		} else {
			closeMapStatusMsg();
		}		
	}	//end function showMarkers
	
	function getEntrancesAndStations(){		
		plotting = true;		
		document.getElementById('mapmessage').innerHTML = "";			
		document.getElementById('mapentrancelist').innerHTML = "";			
		setMapStatusMsg('loading...');
		var start = "entrancesStations";
		if ( mapParam != null && mapParam != "" && mapParam != "null" ) {
			start = mapParam;
		}
		
		var url = "/getEntrancesForMap.do?start=" + start + "&parkId=" + facility + "&contractCode=" + contractCode;	
		makeHttpRequest(url, function(data) {
			// Retrieve downloaded XML content. 
			var xmlDoc = raParseXmlData(data);
			if (xmlDoc == null) {
				closeMapStatusMsg();		
				document.getElementById('mapmessage').innerHTML = "<div class='msg error'>Error retrieving data!</div>";			
				return;
			}		
			if (xmlDoc.documentElement != null) {
				var xinfo = xmlDoc.documentElement.getElementsByTagName("xinfo");
				if ( xinfo != null) {
					mapParam = xinfo[0].getAttribute("map");
					var kmlURL = xinfo[0].getAttribute("kmlURL");				
					if ( kmlURL != null && kmlURL != ""  ) {
						//add area outline to map
	    				var geoXml = new google.maps.KmlLayer(kmlURL);    				
	   					geoXml.setMap(map);	   	   	
					}
					permitType = xinfo[0].getAttribute("permitType");
					clat = parseFloat(xinfo[0].getAttribute("centerLat"));			
					clng = parseFloat(xinfo[0].getAttribute("centerLng"));
					if ( clat != 0 && clng != 0 ) {
						_centerlat = clat;
						_centerlng = clng;
					}			
			
					if (chosenEntrance != null && chosenEntrance > 0) {
						_zoom = _defaultEntranceZoom;
					} 
					map.setCenter(new google.maps.LatLng(_centerlat, _centerlng), _zoom);

					
					if (!minimap) {
						var kmlLabel = xinfo[0].getAttribute("kmlLabel");	
						if ( kmlLabel != null && kmlLabel != ""  ) { 
							label = new ELabel(map, new google.maps.LatLng(_centerlat,_centerlng), kmlLabel, "elabel", new google.maps.Size(100,90));
						}
					}   				
				}						
	    		entrances = xmlDoc.documentElement.getElementsByTagName("marker");
	    	}	
    		if (entrances == null) {
    			closeStatus();		
    			showNoResultsFoundMessage();
    			return;
    		}
    		var count = 0;
    		count = entrances.length;       	    				 		    		
    		if(count == 0){	//if no matching facilities were found...
				closeStatus();			
				showNoResultsFoundMessage();
				return;
			} else if (count > 0) {			
    			i = 0;		
 	  			window.setTimeout(showMarkers,1);		    					
 	  		} 	
 	  		// == show or hide the categories initially ==
        	show("issuing");
        	show("coop");       	
		}, false, false);		
	}
      
	 // A function to create the marker and set up the event window
	function createMarker(point, id, name, html, category, entranceLink ) {	
//	 	if (chosenEntrance != null && chosenEntrance == id) {
//	 		order = 1000000;
//		} else {
//	 		order = id;
//		}
	  	var origin = new google.maps.Point(0,0);
		var shadowSrc = "/images/maps/mm_20_shadow.png";		;
		shadowSize = new google.maps.Size(22, 20);
		iconAnchor = new google.maps.Point(6, 20);

		var image = gicons[category];
		var shadow = new google.maps.MarkerImage(shadowSrc,
				shadowSize,
				origin,
				iconAnchor);
			
	    var marker = new google.maps.Marker({
	        position: point,
	        map: map,
	        shadow: shadow,
	        icon: image,
	        //shape: shape,
	        title: name/*,
	        zIndex: order*/
	    });	
		marker.mycategory = category;
		marker.myname = name;
		marker.myid = id;
		marker.mylink = entranceLink;		

	    google.maps.event.addListener(marker, "click", function() {
	  		if (minimap) {
	 			window.location.href ="/wildernessAreaMap.do?page=map&contractCode=" + contractCode + "&parkId=" + 
	 			facility + "&topTabIndex=Permits" + "&entranceId=" + id + "&entranceDate=" + entryDate + "&permitTypeId=" + permitTypeID;
	 		} else {	  		
	 		   infoWindow.setContent(html);
			   infoWindow.open(map, marker);
			   if ( category == "coop" || category == "issuing" ) {
				   document.getElementById("stationInfo").innerHTML = stationhtml[id];
	   		} 
		}
		   
		   
	  	});	  	
	  	
	  	gmarkers[id] = marker;
	  	return marker;
	}
	
  	//== shows all markers of a particular category, and ensures the checkbox is checked ==
    function show(category) {
    	if ( minimap ) { return; } 
    	for (i in gmarkers) {
        	if (gmarkers[i].mycategory == category) {
            	gmarkers[i].setMap(map);
          	}
        }
        // == check the checkbox ==
    	if (document.getElementById(category+"box")) {
    		document.getElementById(category+"box").checked = true;
    	}
   	}

    // == hides all markers of a particular category, and ensures the checkbox is cleared ==
    function hide(category) {
    	if ( minimap ) { return; } 
    	for (i in gmarkers) {
        	if (gmarkers[i].mycategory == category) {
            	gmarkers[i].setMap(null);
          	}
        }
        // == clear the checkbox ==
        document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infoWindow.close();
   	}
	
   	// == a checkbox has been clicked ==
  	function boxclick(box,category) {
    	if (box.checked) {
      		show(category);
    	} else {
      		hide(category);
    	}
	    // == rebuild the side bar
    	makeSidebar();
  	}
      
  	function clickResult(id) { 		
		try {
			google.maps.event.trigger(gmarkers[id], 'click');
		} catch( err ){}

    }

    // == rebuilds the sidebar to match the markers currently displayed ==
    function makeSidebar() {
    	var html = "";
    	for (i in gmarkers) {
      		if (!gmarkers[i].isHidden() && gmarkers[i].mycategory != "entrance") {
      			html += getResultsListHTML(i, gmarkers[i]); 		
      		}
    	}
        document.getElementById("mapentrancelist").innerHTML = html;
    }

    function getResultsListHTML(entranceID, gmarker) {
    	var html = ""; 
    	if (gmarker.mycategory == "entrance") {  	
    		html = "<div class=\"pin\">" + 
					"<a href=\"javascript:clickResult('" + entranceID + "')\" onmouseover=\"gmarkers['" + entranceID + "'].setIcon('/images/maps/pin_" + gmarker.mycategory + "_hl.png')\" onmouseout=\"gmarkers['" + entranceID + "'].setIcon('/images/maps/pin_" + gmarker.mycategory + ".png')\">" +
					"<img src=\"/images/maps/pin_" + gmarker.mycategory + ".png\"></img></a>" + 
					"<a href=\"" + gmarker.mylink + "\">" + gmarker.myname + "</a>" +
					"&nbsp;</div>";
    	} else {
    		html = "<div class=\"pin\">" + 
					"<a href=\"javascript:clickResult('" + entranceID + "')\" onmouseover=\"gmarkers['" + entranceID + "'].setIcon('/images/maps/pin_" + gmarker.mycategory + "_hl.png')\" onmouseout=\"gmarkers['" + entranceID + "'].setIcon('/images/maps/pin_" + gmarker.mycategory + ".png')\">" +
					"<img src=\"/images/maps/pin_" + gmarker.mycategory + ".png\"></img></a>" + 
					gmarker.myname + "&nbsp;</div>";
    	}
		return html;
    }
    
	function setInfoWindowHTML(entranceID, marker, bookButton, entranceLink, statusLineTop, statusLineBottom) {
		photoUrl = marker.getAttribute("photoPath");
		var defaultPhotoUrl = "this.src=\"/images/nophoto.jpg\";"
		var startSpan = "<span style=\"font-size:12px;\">";
		var endSpan = "</span>";
		if (entranceLink != "") {
			entranceLink = "<a href=\"" + entranceLink + "\">" + startSpan + marker.getAttribute("name") + endSpan + "</a>";
		} else {
			entranceLink = "<span style=\"font-size:12px;font-weight: bold;\">" + marker.getAttribute("name") + endSpan;
		}

		iwhtml[entranceID] ="<div>" +"<div style=\"padding-bottom:5px;\" >" + entranceLink + "&nbsp;&nbsp;&nbsp;</div><div>";			
		if (marker.getAttribute("type") == "coop" || marker.getAttribute("type") == "issuing") {	
			iwhtml[entranceID] = iwhtml[entranceID] + "<div style='clear:both;padding-bottom:5px;'>" +
				"<span class='iwstyle'>Open: " + marker.getAttribute("time") + "</span></div>" + "<div style='width:200px;text-align:left;'>" +
				"<span class='iwstyle'>Driving Directions: " + marker.getAttribute("description") + "</span></div>";
				setStationInfoHTML(entranceID, marker);
		} else {
			iwhtml[entranceID] = iwhtml[entranceID] + "<div style=\"width:90px; float:left; vertical-align:center; text-align:center\">" + statusLineTop + bookButton +
		   		 statusLineBottom + "</div><div style=\"width:90px; padding-left:10px\">" +
		   		 "<img src=\"" + photoUrl + "\" style=\"padding-bottom: 3\" border=\"0\" width=\"80px\" height=\"53px\"/ onError='" + defaultPhotoUrl + "'\" ></div>";
		}											  	    
	    iwhtml[entranceID] = iwhtml[entranceID] + "</div></div>";

	}
	
	function setStationInfoHTML(entranceID, marker) {		
		stationhtml[entranceID] = "<h2>" + marker.getAttribute("name") + "</h2>" +
			"<table cellspacing='0' cellpadding='5'>" +
			"<tr><td colspan=\"2\">" + marker.getAttribute("address") +  ", " + marker.getAttribute("city") + ", " + marker.getAttribute("state") + ", " + 
			marker.getAttribute("zipcode") + "</td>" +			
			"<tr><td>Telephone: </td><td>" + marker.getAttribute("phone") + "</td>" +
			"<tr><td>Fax: </td><td>" + marker.getAttribute("fax") + "</td>" + 
			"<tr><td>Open: </td><td>" + marker.getAttribute("time") + "</td>" + 
			"<tr><td>Directions: </td><td>" + marker.getAttribute("description") + "</td>" +
			"</table>";	
	}

	function showStatus(index, total){ //this function shows the "loading" status window
		setMapStatusMsg('loading park '+index+' of '+total+'...')
	}
	
	function setCoords(lng, lat, zm) {		
		_centerlng = lng;
		_centerlat = lat;
		_zoom = zm;		
	} 	
	
	function setFacility(pkId, agCd) {		
		facility = pkId;		
		contractCode = agCd;		
	}
	
	function setFacilityAndCriteria(pkId, agCd, dtEntry, ptId) {		
		facility = pkId;		
		contractCode = agCd;
		entryDate = dtEntry;
		permitTypeID = 	ptId	
	}
	
	function setMapParam(param) {		
		mapParam = param;	
	}
		
	function showNoResultsFoundMessage() {
		if ("SEARCH" == mapParam) {	
			document.getElementById('mapmessage').innerHTML = "<div class='msg error'>No matching entrances found.  Please modify the search criteria.</div>";			
		} else {
			document.getElementById('mapmessage').innerHTML = "<div class='msg error'>No entrances found for this facility.</div>";							
		}
	}
	
	function showMapNotAvailableMessage() {
		document.getElementById('mapmessage').innerHTML = "<div class='msg error'><h2>Map not available!</h2></div>";
		document.getElementById('mapmessage').style.display = "";
	} 
		
	function MapStatusControl() {
		var container = document.createElement("div");
		var statusDiv = document.createElement("div");
		statusDiv.id = 'mapStatusMsg';
		statusDiv.style.width = "390px";
		statusDiv.style.backgroundColor = "#FAE5BA";
		statusDiv.style.font = "11px bold";
		statusDiv.style.fontFamily = "Arial,Helvetica,sans-serif";
		statusDiv.style.padding = "2px";
		statusDiv.style.marginBottom = "3px";
		statusDiv.style.textAlign = "center";
		statusDiv.style.display = "none";
		container.appendChild(statusDiv);
		container.index = 1;
		return container;
	}

	function setMapStatusMsg(msg){ //this function sets the map status message window
		if (document.getElementById('mapStatusMsg')) {
			document.getElementById('mapStatusMsg').innerHTML = msg;
			document.getElementById('mapStatusMsg').style.display = "block";
		}
	}

	function closeMapStatusMsg(){ //this function hides the status message window
		if (document.getElementById('mapStatusMsg')) {
			document.getElementById('mapStatusMsg').innerHTML = "";
			document.getElementById('mapStatusMsg').style.display = "none";
		}
	}
	

