	//global variables
	var map;	
    var mapParam;		
    var mapStatus;
	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;
	
	function onLoad() { 
		try {
    		init();   
	   	} catch(e){}
	   	if (GBrowserIsCompatible()) {	   	
	      	map = new GMap2(document.getElementById("mapviewport"));
		    map.addControl(new GLargeMapControl());      
	   	  	map.addControl(new GMapTypeControl());       
	   	  	map.addControl(new GScaleControl());	//add scale to map     	 
	   	  	mapStatus = new StatusControl();
			map.addControl(mapStatus);
			map.enableScrollWheelZoom();		
			initIcons();
			createListeners();
	  		showMap();	  		  	 
  		} else {
  			//TODO: should do something here - show message, redirect to another page, etc.
  		}
	}
	
	function detailsViewOnLoad() {
		if (document.getElementById("mapviewport") != null) {
			try {
	    		init();   
		   	} catch(e){}
		   	if (GBrowserIsCompatible()) {	   	
		      	map = new GMap2(document.getElementById("mapviewport"));
		      	map.getContainer().style.overflow="hidden";
		      	map.disableDragging();
		      	map.disableDoubleClickZoom();
		      	minimap = true;
		      	initIcons();			
		  		showMap();	  
		  		
	  		} else {
	  			//TODO: should do something here - show message, redirect to another page, etc.
	  		}
		}
	}
	
	function initIcons() {
		var icon = new GIcon();
		icon.shadow = "/images/maps/mm_20_shadow.png";		;
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 5);		
		
   		gicons["entrance"] = new GIcon(icon, "/images/maps/pin_entrance.png");
    	gicons["coop"] = new GIcon(icon, "/images/maps/pin_coop.png");
    	gicons["issuing"] = new GIcon(icon, "/images/maps/pin_issuing.png");
	}
	
	function showMap() {		
	   	//map.setCenter(new GLatLng(_centerlat, _centerlng), _zoom); //AS - moved this to getEntrancesAndStations()	   		
	    getEntrancesAndStations();	 
	   	map.savePosition();    	
	}
	
	function createListeners() {			
		GEvent.addListener(map, "moveend", function() {				
			if (infoOpened == true ) { 				  
            	infoOpened = false; 
           	    return; 
		    } 		   	
		    if (mapTypeChanged == true) { 				  
            	mapTypeChanged = false;            	
		    }					  		
		} );
		GEvent.addListener(map, "infowindowopen", function() {
			infoOpened = true;			
		} );		
		GEvent.addListener(map, "infowindowclose", function() {
			infoOpened = false; 
			document.getElementById("stationInfo").innerHTML = "";
		} );		
		GEvent.addListener(map, "maptypechanged", function() {
			mapTypeChanged = true; 		
		} );		 		
	}			
	
	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 GLatLng(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);
		 	  	map.addOverlay(marker);	
		 	  
		 	  	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 {
			closeStatus();
		}		
	}	//end function showMarkers
	
	function getEntrancesAndStations(){		
		plotting = true;		
		document.getElementById('mapmessage').innerHTML = "";			
		document.getElementById('mapentrancelist').innerHTML = "";			
		document.getElementById('status').style.display = "inline";
		document.getElementById('status').innerHTML = 'loading...';
		var start = "entrancesStations";
		if ( mapParam != null && mapParam != "" && mapParam != "null" ) {
			start = mapParam;
		}
		
		var url = "/getEntrancesForMap.do?start=" + start + "&parkId=" + facility + "&contractCode=" + contractCode;	
		GDownloadUrl(url, function(data, responseCode) {
			var xmlDoc = GXml.parse(data);
			if (xmlDoc == null) {
				closeStatus();		
				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 GGeoXml(kmlURL);    				
	   					map.addOverlay(geoXml);	   	   	
					}
					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 GLatLng(_centerlat, _centerlng), _zoom);
					
					if (!minimap) {
						var kmlLabel = xinfo[0].getAttribute("kmlLabel");	
						if ( kmlLabel != null && kmlLabel != ""  ) { 
							var label = new ELabel(new GLatLng(_centerlat,_centerlng), kmlLabel, "elabel", new GSize(100,90));
							map.addOverlay(label);
						}
					}   				
				}						
	    		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");       	
		});		
	}
      
	 // A function to create the marker and set up the event window
	function createMarker(point, id, name, html, category, entranceLink ) {	
	 	var options;	 	

	 	if (chosenEntrance != null && chosenEntrance == id) {
	 		options = { 
				icon: gicons[category],
				title: name,
				zIndexProcess: function(lat){return 1000000;} 
			};
	 	} else {
	 		options = { 
				icon: gicons[category],
				title: name			
			};
		}
	    var marker = new GMarker(point, options);	      
		// === Store the category and name info as a marker properties ===
		marker.mycategory = category;
		marker.myname = name;
		marker.myid = id;
		marker.mylink = entranceLink;		
	  	GEvent.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 {	  		
			   	marker.openInfoWindowHtml(html);	
		   		if ( category == "coop" || category == "issuing" ) {
	    			document.getElementById("stationInfo").innerHTML = stationhtml[id];
	    		} 
    		}
	  	});	
		
	  	/* remove this for now
	  	// highlight icon on marker mouseover and mouseout
        GEvent.addListener(marker, "mouseover", function() {
          marker.setImage("/images/maps/pin_" + category + "_hl.png");
        });
        GEvent.addListener(marker, "mouseout", function() {
          marker.setImage("/images/maps/pin_" + category + ".png");
        });
        */
	  	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].show();
          	}
        }
        // == check the checkbox ==
        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].hide();
          	}
        }
        // == clear the checkbox ==
        document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        map.closeInfoWindow();
   	}
	
   	// == 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) { 		
    	GEvent.trigger(gmarkers[id],"click");
    }

    // == 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 + "'].setImage('/images/maps/pin_" + gmarker.mycategory + "_hl.png')\" onmouseout=\"gmarkers['" + entranceID + "'].setImage('/images/maps/pin_" + gmarker.mycategory + ".png')\">" +
					"<img src=\"/images/maps/mm_20_" + gmarker.mycategory + ".gif\"></img></a>" + 
					"<a href=\"" + gmarker.mylink + "\">" + gmarker.myname + "</a>" +
					"&nbsp;</div>";
    	} else {
    		html = "<div class=\"pin\">" + 
					"<a href=\"javascript:clickResult('" + entranceID + "')\" onmouseover=\"gmarkers['" + entranceID + "'].setImage('/images/maps/pin_" + gmarker.mycategory + "_hl.png')\" onmouseout=\"gmarkers['" + entranceID + "'].setImage('/images/maps/pin_" + gmarker.mycategory + ".png')\">" +
					"<img src=\"/images/maps/mm_20_" + gmarker.mycategory + ".gif\"></img></a>" + 
					gmarker.myname + "&nbsp;</div>";
    	}
		return html;
    }
    
	function setInfoWindowHTML(entranceID, marker, bookButton, entranceLink, statusLineTop, statusLineBottom) {
		photoUrl = "/photos2/" + marker.getAttribute("contractCode").toUpperCase() + "/pid" + marker.getAttribute("parkid") + "/sid" + entranceID + "/0/80x53.jpg";		
		var defaultPhotoUrl = "this.src=\"/photos/details/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] =  
			"<table cellspacing='0' cellpadding='0'>" +
			"<tr><td colspan=\"2\" style=\"vertical-align:top; text-align:left; padding-bottom:5px\" >" + entranceLink + "&nbsp;&nbsp;&nbsp;</td></tr>";			
			if (marker.getAttribute("type") == "coop" || marker.getAttribute("type") == "issuing") {	
				iwhtml[entranceID] = iwhtml[entranceID] + "<tr><td style='float:left;padding-bottom:1;'>" +
				"<span class='iwstyle'>Open: " + marker.getAttribute("time") + "</span></td></tr>" + "<tr><td rowspan='2' style='width:200px;float:left;text-align:left;'>" +
				"<span class='iwstyle'>Driving Directions: " + marker.getAttribute("description") + "</span></td></tr>";
				setStationInfoHTML(entranceID, marker);
			} else {
				iwhtml[entranceID] = iwhtml[entranceID] + "<tr><td style=\"width:90px; float:left; vertical-align:center; text-align:center\">" + statusLineTop + bookButton +
		   		 statusLineBottom + "</td><td rowspan=\"2\" style=\"vertical-align:top; float:left; padding-left:10px\">" +
		   		 "<img src=\"" + photoUrl + "\" style=\"padding-bottom: 3\" border=\"0\" width=\"80px\" height=\"53px\"/ onError='" + defaultPhotoUrl + "'\" ></td></tr>";
			}											  	    
		    iwhtml[entranceID] = iwhtml[entranceID] + "</table>";
	}
	
	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
		document.getElementById('status').innerHTML = 'loading park '+index+' of '+total+'...';		
	}
	
	function closeStatus(){ //this function hides the "loading" status window
		document.getElementById('status').style.display = "none";		
		plotting = false;			
	}
	
	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 = "";
	} 
		
	// StatusControl is a GControl that displays map status info at the top of the map
	function StatusControl() {
	}
	StatusControl.prototype = new GControl();
	// Creates a one DIV for each of the buttons and places them in a container DIV which is returned as our 
	//control element. We add the control to the map container and return the element for the map class to position properly.
	StatusControl.prototype.initialize = function(map) {
		var container = document.createElement("div");
		var statusDiv = document.createElement("div");
		statusDiv.id = 'status';
		this.setStyle_(statusDiv);
		container.appendChild(statusDiv);
		map.getContainer().appendChild(container);
		return container;
	}
	// By default, the control will appear in the top left corner of the map with 0 pixels of padding.
	StatusControl.prototype.getDefaultPosition = function() {
	  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0));
	}
	// Sets the proper CSS for the given button element.
	StatusControl.prototype.setStyle_ = function(bar) {
		bar.style.color = "#FFFFFF";
		bar.style.backgroundColor = "#CC0000";
		bar.style.font = "12px bold";
		bar.style.padding = "2px";
		bar.style.marginBottom = "3px";
		bar.style.textAlign = "center";
		bar.style.width = 422 + "px";
		bar.style.cursor = "pointer";
		bar.style.display = "none";
	}
	
