// Unified Search Google Map View
//global variables
var map = null;	
var iwhtml = [ ];
//initialize with default view
var centerlng = -98.8;
var centerlat = 39.5;
var centerName;
var zoom = 4;
var bestViewBouds;
var contractCode;	
var CONTRAT_CODE_ELS = 'ELS';
var CONTRAT_CODE_TRLS = 'TRLS';
var CONTRAT_CODE_KOA = 'KOA';
var mapMarkers = {};
var i = 0;
var mapStatusMsg;
var msgFromServer;
var bubbleToOpen;
var bubbleLat;
var bubbleLng;
var markerToClick;

function initializeMap() {
	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();
	
    // add directions control
    //gdir = new google.maps.Directions(map, document.getElementById("directions"));
    //GEvent.addListener(gdir, "load", onGDirectionsLoad);
	//GEvent.addListener(gdir, "error", handleErrors);
	showMap();
	geo = new google.maps.Geocoder;
}
function showMap() {	
	if (bestViewBouds) {
		map.fitBounds(bestViewBouds);
	} else { 
		map.setCenter(new google.maps.LatLng(centerlat, centerlng), zoom);
	}
	if (bubbleLng && bubbleLat) {
		map.setCenter(new google.maps.LatLng(bubbleLat, bubbleLng), zoom);
		bubbleLat = null;
		bubbleLng = null;
	}  
	createListeners(); 
	
}

function createListeners() {			
	google.maps.event.addListener(map, "idle", function() {			
		if ($("search_results_map").style.display == "block") {
			closeMapStatusMsg();
			if (msgFromServer) {
				createTargetMarker();
				setMapStatusMsg(msgFromServer);
				msgFromServer = null;
			} else {
				window.setTimeout("getParks()",1);
			}
		}
	} );
	google.maps.event.addListener(map, "click", function() {
		infoWindow.close();
	} );
}

//StatusControl is a Custom Control that displays data load status info at the top of the map
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 showLoadParksStatusMsg(index, total){ //this function shows the status message window
	setMapStatusMsg('loading park '+index+' of '+total+'...');
}
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";
	}
}
function pushMarkers(){
	if(i < parks.length){
		var max = Math.min(i+20, parks.length);	//select the minimum batch size of 20 facilities or the remainder of total facilities divided by 20				
		showLoadParksStatusMsg(max, parks.length);	//show loading status bar
		while(i < max){		
			var parkID = parks[i].getAttribute("contractCode") + parks[i].getAttribute("parkid"); //loop through all facilities to be plotted in this batch
       	 	var facilityType = parks[i].getAttribute("facilityType");
       	 	if (facilityType == "area" || facilityType == "facility") {
       	 		parkID += "_" + parks[i].getAttribute("agencyId")
       	 	}
			var j = 0;
			var exists = mapMarkers[parkID] != null;
			var marker; 	  	  											  						  					  						  					  					
       	 	var contractType = parks[i].getAttribute("contractType");
	       	var iconType = facilityType; 
	       	if (facilityType == "facility") {
       			iconType = "area"; 
       		}

	       	var hiddenOnMap = parks[i].getAttribute("hiddenOnMap") == "true";
	       	var facilityDetailsLink;

       		if (facilityType == "tour") { 
       			facilityDetailsLink = "/tourParkDetail.do?contractCode=" + parks[i].getAttribute("contractCode") 
       			+ "&parkId=" + parks[i].getAttribute("parkid");
       		} else if (facilityType == "permit") { 
       			facilityDetailsLink = "/wildernessAreaDetails.do?contractCode=" + parks[i].getAttribute("contractCode") 
       			+ "&parkId=" + parks[i].getAttribute("parkid");
       		} else if (facilityType == "area") { 
       			facilityDetailsLink = "/recAreaDetails.do?contractCode=" + parks[i].getAttribute("contractCode") 
       			+ "&recAreaId=" + parks[i].getAttribute("parkid") + "&agencyCode=" + parks[i].getAttribute("agencyId");  
       		} else if (facilityType == "facility") {
       			facilityDetailsLink = "/recAreaDetails.do?contractCode=" + parks[i].getAttribute("contractCode") 
       			+ "&facilityId=" + parks[i].getAttribute("parkid") + "&agencyCode=" + parks[i].getAttribute("agencyId");   
       		} else { //Campground ((facilityType == "camping" || null))
       			facilityDetailsLink = "/unifSearchInterface.do?interface=camping&contractCode=" + parks[i].getAttribute("contractCode") 
       			+ "&parkId=" + parks[i].getAttribute("parkid"); 
       		} 
	       	if (exists == false && hiddenOnMap == false){ //if this marker is not already plotted...
				//prepare marker												 			 	  			
   				var point = new google.maps.LatLng(parseFloat(parks[i].getAttribute("lat")), parseFloat(parks[i].getAttribute("lng")));  
   				setInfoWindowHTML(parkID, parks[i], facilityDetailsLink);			    	     
	 	  		marker = createMarker(point, parkID, parks[i].getAttribute("parkname") + ", " + parks[i].getAttribute("state"), iwhtml[parkID], iconType/*contractType*/, i);   				 	  	
		 	  	marker.parkID = parkID;			
		 	  	mapMarkers[parkID] = marker;
			}	//end if not already plotted
	       	if (marker && bubbleToOpen == marker.parkID) {
	       		markerToClick = marker;
	       	} 
			i++;
		}	//end while			
		window.setTimeout(pushMarkers,1);
	} else {
		if (msgFromServer) {
			setMapStatusMsg(msgFromServer);
			msgFromServer = null;
		} else {
			closeMapStatusMsg();
		}
	}
	if (bubbleToOpen && markerToClick) {
		try {
			google.maps.event.trigger(markerToClick, 'click');
		} catch( err ){}
		bubbleToOpen = null;
		markerToClick = null;
	}
}	//end function pushMarkers

function setInfoWindowHTML(parkID, marker, facilityTypeLink) {
	var facilityCard = UnifSearchEngine.getFacilityCard(parkID);
	if (facilityCard != null) {
		facilityCard = facilityCard.replace(' id="',' id="bbl_');
		facilityCard = facilityCard.replace('width="180"','width="80"'); 
		facilityCard = facilityCard.replace('height="120"','height="53"'); 
		facilityCard = facilityCard.replace('180x120.jpg','80x53.jpg');
		// for IE7 & IE8 only
		facilityCard = facilityCard.replace(' id=',' id=bbl_');
		facilityCard = facilityCard.replace('width=180','width=80'); 
		facilityCard = facilityCard.replace('height=120','height=53'); 
	} else {
		photoUrl = marker.getAttribute("photoPath");
		var defaultPhotoUrl = "this.src=\"/images/nophoto.jpg\";"
		if (!facilityTypeLink) {
			facilityTypeLink = "/unifSearchInterface.do?interface=camping&contractCode=" + marker.getAttribute("contractCode") 
			+ "&parkId=" + marker.getAttribute("parkid") 
		}
		
		var region = "<div class=\"facility_header_parent\">"; ;
		if (marker.getAttribute("region")!="") {
			region += "<span>part of</span><span class=\"region\">" + marker.getAttribute("region") + "</span>"; 
		} 
		if (marker.getAttribute("agencyName")!="") {
			region += "<span class=\"agency\">" + marker.getAttribute("agencyName") + "</span>";
		}
		region += "</div>";

		var facilityViewHeader = "<a class=\"facility_link\" title=\"" + marker.getAttribute("parkname") + "\"" + 
			" onclick=\"UnifSearchEngine.showProgressBar(&quot;Retrieving...&quot;,&quot;usearch_results&quot;)\"" + 
			" href=\"" + facilityTypeLink + "\">" + marker.getAttribute("parkname") + "</a> <span>, " + marker.getAttribute("state") + "</span><br>" + region; 

		var seeDetailsLink = "<div class=\"check_avail_panel\"><a class=\"check_available\" title=\"See Details\" " +
			" onclick=\"UnifSearchEngine.showProgressBar(&quot;Retrieving...&quot;,&quot;usearch_results&quot;)\"" + 		
				"href=\"" + facilityTypeLink + "\">See Details</a></div>";
		
		facilityCard = "<img src=\"" + photoUrl + "\" border=0 width=\"80px\" height=\"53px\"/ onError='" + defaultPhotoUrl + "'\" >" + 
			"<div class=\"facility_view_header\">" + facilityViewHeader + seeDetailsLink + "</div>";			
	}
	iwhtml[parkID] = "<div id=\"mapbubble\" class=\"facility_view_card\">" + facilityCard + "</div>";
}

function createMarker(point, parkId, name, desc, contractType, index) {
	var shadowSrc = "";
	var imageSize = null;
	var shadowSize = null;
	var order = index;
	if ("chosen"  == contractType || "encore" == contractType || "koa" == contractType) {
		if ("encore" == contractType || "koa" == contractType) {
			shadowSrc = "/images/maps/shadow_encore.png";
			imageSize = new google.maps.Size(25, 34);
			shadowSize = new google.maps.Size(39, 34);			
		} else {
			shadowSrc = "/images/maps/shadow50.png";
			imageSize = new google.maps.Size(20, 34);
			shadowSize = new google.maps.Size(37, 34);			
		}
	} else {
		shadowSrc = "/images/maps/mm_20_shadow.png";	
		imageSize = new google.maps.Size(12, 20);
		shadowSize = new google.maps.Size(22, 20);
	}	
	var origin = new google.maps.Point(0,0);
	var iconAnchor;
	var pinImgSrc = UnifSearchEngine.getMapMarker(parkId);
	if ( pinImgSrc == null) {
		pinImgSrc = '/images/maps/mm_20_' + contractType + '.png';
		iconAnchor = new google.maps.Point(6, 20);
	} else {
		imageSize = new google.maps.Size(20, 34);
		shadowSrc = "/images/maps/shadow50.png";
		shadowSize = new google.maps.Size(37, 34);
		iconAnchor = new google.maps.Point(9, 34);			
		order = index + 1000;
	}
	var image = new google.maps.MarkerImage(pinImgSrc,
		imageSize,
		// The origin for this image is 0,0.
		origin,
		// The anchor for this image is the base of the flagpole at 0,32.
	    iconAnchor);
	var shadow = new google.maps.MarkerImage(shadowSrc,
		// The shadow image is larger in the horizontal dimension
		// while the position and offset are the same as for the main image.
		shadowSize,
		origin,
		iconAnchor);
	
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        shadow: shadow,
        icon: image,
        //shape: shape,
        title: name,
        zIndex: order
    });	
    google.maps.event.addListener(marker, "click", function() {
	   infoWindow.setContent(desc);
	   infoWindow.open(map, marker);    	
	   
  	});	  	
  	return marker;
}

function createTargetMarker() {
	if (centerName) {
		var point = new google.maps.LatLng(centerlat,centerlng);
		var imageSize = new google.maps.Size(27, 27);
		var origin = new google.maps.Point(0,0);
		var iconAnchor = new google.maps.Point(13, 13);
		var pinImgSrc = '/images/maps/mapmarker_where.png';
		var image = new google.maps.MarkerImage(pinImgSrc,
				imageSize,
				// The origin for this image is 0,0.
				origin,
				// The anchor for this image is the base of the flagpole at 0,32.
				iconAnchor);
		var marker = new google.maps.Marker({
			position: point,
			map: map,
			//shadow: shadow,
			icon: image,
			//shape: shape,
			title: centerName,
			zIndex: 1
		});
	}
}

function getParks(){
	setMapStatusMsg('loading...');
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();	
	var url = "/getParksForMap.do?start=uSearchResults&minX=" + southWest.lng() + "&minY=" + southWest.lat()  +
	"&maxX=" + northEast.lng() + "&maxY=" + northEast.lat() + "&long=" +  centerlng + "&lat=" + centerlat;
	makeHttpRequest(url, function(data) {
		// Retrieve downloaded XML content. 
		var xmlDoc = raParseXmlData(data);
		if (xmlDoc == null) {
			setMapStatusMsg("<div class='msg error'>Error retrieving data!</div>");			
			return;
		}		
		if (xmlDoc.documentElement != null) {
			var submit = xmlDoc.documentElement.getElementsByTagName("submitform");
			if (submit && submit.length > 0) {
				document.getElementById("unifSearchForm").submit();
			}
			var msg = xmlDoc.documentElement.getElementsByTagName("div");
			if (msg && msg.length > 0) {
				msgFromServer = msg[0].childNodes[0].data;
			}
    		parks = xmlDoc.documentElement.getElementsByTagName("marker");
    	}	
		if (msgFromServer) {
			if (Object.keys(mapMarkers).length > parks.length) {
				removePins();
			}
			setMapStatusMsg(msgFromServer);
		}
		if (parks == null) {
			return;
		}
		var count = 0;
		count = parks.length;       	    				 		    		
		createTargetMarker();
		if(count == 0){
			return;
		} else {
			i = 0;
			window.setTimeout(pushMarkers,1);
		}
	}, false, false);
	}
function removePins() {
	for (var key in mapMarkers) {
		mapMarkers[key].setMap(null);
	}
	mapMarkers = {};
}

if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (obj.hasOwnProperty(k)) { keys.push(k); }
        }
        return keys;
    };
}
