//***************************************************************
// Check, Please! Google Maps 
// v1.0 2006-12-29 
// Copyright © 2006, Intersites, Inc. (http://www.intersites.com)
// All Rights Reserved.
// You are free to use this code for your own purposes as long as 
//		you email us at info@intersites.com to tell us how you are 
//		using it and this notice stays intact.
// 
//****************************************************************



if (GBrowserIsCompatible()) { // The browser has to be compatible...

	var map; // The map
	var request; // Used to make an asynchronous call to get the map data
	var bounds = new GLatLngBounds(); // Bounds of the map
	var geocoder = null; // Used to resolve addresses the user enters
	var markerArrayIndex = 0; // Index of the current restaurant data
	var tab1Label = 'Restaurant'; // Label for the first tab
	var tab2Label = 'Reviewers'; // Label for the second tab
	var gmarkers = []; // The array of all map markers
	var htmls = []; // Array to store the default HTML for the first tab of a marker
	var to_htmls = []; // Array to store the HTML of the first tab of a marker when the user clicks the Directions To link
	var from_htmls = []; // Array to store the HTML of the first tab of a marker when the user clicks the Directions From link
	var to_htmls_details = []; // Array to store the HTML of the second tab of a marker when the user clicks the Directions To link
	var from_htmls_details = []; // Array to store the HTML of the second tab of a marker when the user clicks the Directions From link
	var icons=[]; // Array of our different colored icons
	var baseIcon = new GIcon();	// The default icon/pushpin with the appropriate values set below... 
	baseIcon.image = "/resources/images/map_pushpins/pushpin_red.png";
	baseIcon.shadow = "/resources/images/map_pushpins/pushpin_shadow.png";
	baseIcon.iconSize = new GSize(12, 20);
	baseIcon.shadowSize = new GSize(22, 20);
	baseIcon.iconAnchor = new GPoint(6, 20);
	baseIcon.infoWindowAnchor = new GPoint(5, 1);
	baseIcon.imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0];


	// The main function for the map. Should be called by the <BODY > tag's onLoad="" event.
	function makeMap() {
		map = new GMap2(document.getElementById("map")); // Create a map using the div named "map"
		map.addControl(new GLargeMapControl()); // Add the zoom control
		map.addControl(new GMapTypeControl()); // Add the map/satelite/hybrid control
		map.addControl(new GScaleControl()); // Add the scale control indicator
		map.setCenter(new GLatLng(41.89278, -87.60831), 9); // Set the center over Chicagoland and zoom to a level likely to encompass the markers
		
		request = GXmlHttp.create(); // Prepare to make an asynchronous call to get the map data
		request.open("GET", "/resources/xml/2009_hotspots.xml", true); // Make the call to get the map data
		request.onreadystatechange = processXML; // When data is returned, call the function to process the data
		request.send(null); // Close the connection

		geocoder = new GClientGeocoder(); // Create a geocoder so we can translate an address the user enters
	}	
	
	
	// This function does most of the hard work. 
	//	It checks to see if the data has been fully downloaded.
	//	If so, it reads the XML data in and parses it.
	//	For each datum in the XML, it reads in the specific data for the restaurant 
	//		and builds HTML and then calls a function to add the marker to the map.
	function processXML() {
		if (request.readyState == 4) { // If we have a final response from the server
			if (request.status != 200) { //	and it's a file not found
				alert("File not found: " + request.status); // let the user know
				return; // and get out
			}
			var xmlDoc = request.responseXML; // Okay, we have a completed request and some data - read it into an XML parser
			if (!xmlDoc) { // If the file is not valid XML
				alert("Invalid xml file");  // let the user know
				return; // and get out
			}
			markers = xmlDoc.documentElement.getElementsByTagName("marker"); // Parse the file by markers/restaurants
			for (var i=0; i < markers.length; i++) { // For each restaurant
				
				tab1HTML = '<strong>' + markers[i].getAttribute("name") + '</strong><br /> ' + markers[i].getAttribute("address1"); // Build the HTML for the first tab
				if (((markers[i].getAttribute("address2")).length > 0)) { tab1HTML += ', ' + markers[i].getAttribute("address2"); }
				if (((markers[i].getAttribute("city")).length > 0)) { tab1HTML += ', ' + markers[i].getAttribute("city"); }
				if (((markers[i].getAttribute("state")).length > 0)) { tab1HTML += ', ' + markers[i].getAttribute("state"); }
				if (((markers[i].getAttribute("phone")).length > 0)) { tab1HTML += '<br />' + markers[i].getAttribute("phone"); }
				if (((markers[i].getAttribute("website")).length > 0)) { tab1HTML += '<br /><br /><a href="http://' + markers[i].getAttribute("website") + '" target="fest_hotels">' + markers[i].getAttribute("website") + '</a>'; }
				if (((markers[i].getAttribute("additional_data")).length > 0)) { tab1HTML += '<br /><br />' + markers[i].getAttribute("additional_data"); }
			
				 // Call the function to add the marker to the map
				addTabbedMarker(parseFloat(markers[i].getAttribute("lng")),
								parseFloat(markers[i].getAttribute("lat")),
								markers[i].getAttribute("name"),
								markers[i].getAttribute("code"),
								tab1HTML,
								markers[i].getAttribute("icon"));
	
			}
			
			// After iterating over every marker
			map.setZoom(map.getBoundsZoomLevel(bounds)); // Set the zoom to encompass the bounds
			var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2; // Figure out the latitude of the center of the map 
			var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2; // and the longitude
			map.setCenter(new GLatLng(clat,clng)); // and set the map's center to that location
		}
	}

  function createMarker(point,html) {
    var marker = new GMarker(point);
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
    });
    return marker;
  }
      

	// This function does most of the rest of the hard work
	// 	It takes all the data about a restaurant and creates a marker with 
	//	colored pushpin and a tabbed info window at the correct location 
	function addTabbedMarker(lng, lat, name, code, firstTabHTML, pushpinColor) {
		var point = new GLatLng(lat, lng); // Create a point at the latitude and longitude
		bounds.extend(point); // Extend the bounds of the map to include the point
		var icon = createCategoryIcon(pushpinColor); // Get the icon for this color
		var marker = new GMarker(point, icon); // Create a marker at this location and with the right color
		marker.type = pushpinColor; // Note the color of the marker in the marker so we can hide or show it with the checkboxes
		marker.code = code; // Note the code of the marker in the marker so we can hide or show it when the user clicks on the pushpin to the left of the name in the list

		// Build the HTML to display on the first tab
		firstTabHTML = '<div style="width:250px; font-family:arial;">' + 
			firstTabHTML + 
			'<br/><br/>Directions: <a href="javascript:directionsToHere(' + markerArrayIndex + ')">To here</a> - <a href="javascript:directionsFromHere(' + markerArrayIndex + ')">From here</a>' +
			'</div>';
		
		htmls[markerArrayIndex] = firstTabHTML;
			
		// Build the HTML to display if the user clicks the Directions To link and put into the array
		to_htmls[markerArrayIndex] = '<div style="width:250px; font-family:arial">' + 
			firstTabHTML + 
			'<br/><br/>Directions: <b>To here</b> - <a href="javascript:fromhere(' + markerArrayIndex + ')">From here</a>' +
			'<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
			'<input type="text" size=40 maxlength=40 name="saddr" id="saddr" value="" /><br>' +
			'<input value="Get Directions" type="submit">' +
			'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
							"(" + name + ")" +
			'"/></div>';
			
//		to_htmls_details[markerArrayIndex] = secondTabHTML; // Store the second tab's HTML to display if the user clicks the Directions To link then the second tab

		// Build the HTML to display if the user clicks the Directions From link and put into the array
		from_htmls[markerArrayIndex] = '<div style="width:250px; font-family:arial;">' + 
			firstTabHTML + 
			'<br/><br/>Directions: <a href="javascript:tohere(' + markerArrayIndex + ')">To here</a> - <b>From here</b>' +
			'<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
			'<input type="text" size=40 maxlength=40 name="daddr" id="daddr" value="" /><br>' +
			'<input value="Get Directions" type="submit">' +
			'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
							"(" + name + ")" +
			'"/></div>';
			
//		from_htmls_details[markerArrayIndex] = secondTabHTML; // Store the second tab's HTML to display if the user clicks the Directions From link then the second tab
		
		GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(firstTabHTML);}); // Create the function to call if the user clicks on the marker
		if (document.getElementById(pushpinColor).checked == true) {
			map.addOverlay(marker); // Add the marker to the map! Yeah!
			marker.displayed = true;
		} else {
			marker.displayed = false;
		}
		gmarkers[markerArrayIndex] = marker; // Store the marker into the array

		markerArrayIndex++; // Increment the array index
	};
	
	
	// This function creates a new icon for a specific color and stores it 
	//	in our array of icons.
	function createCategoryIcon(requestedColor) {
		var color;
		if ((typeof(requestedColor) == "undefined") || (requestedColor == null)) { // We were called with a bogus value,
			color = "red"; // so set the color for this icon to a known value 
		} else { 
			color = requestedColor; // otherwise set the color to the requested color 
		}
		if (!icons[requestedColor]) { // If the icon array doesn't already have the requested color
			var icon = new GIcon(baseIcon); // create a new icon based off the base icon
			icon.image = "/resources/images/map_pushpins/pushpin_"+ color +".png"; // change the path to the actual image
			icons[requestedColor] = icon; // and add it to the array
		}
		return icons[requestedColor]; // Return the icon
	}


	// This function is called if the user clicks the Directions To link in the first tab of the marker's info window 
	function directionsToHere(i) {
		gmarkers[i].openInfoWindowHtml(to_htmls[i]); // Basically, we just swap out the current HTML with the HTML which includes the address form
	}

	// This function is called if the user clicks the Directions From link in the first tab of the marker's info window 
	function directionsFromHere(i) {
		gmarkers[i].openInfoWindowHtml(from_htmls[i]); // Basically, we just swap out the current HTML with the HTML which includes the address form
	}
	
	
} else { // display a warning if the browser is not compatible
	alert("Sorry, the Google Maps API is not compatible with this browser");
}



// This function hides or shows the Google map markers 
//	for a given category
// It's not in the main if (GBrowserIsCompatible()) block 
//	because the means to call this function (i.e. checkboxes)
//	may appear on the page even if the browser is not compatible
function toggleMarkers(category) {

	if (map && typeof map == 'object') { // First check to see if the map exists
		map.closeInfoWindow(); // Close any open info windows
	
		if (document.getElementById(category).checked == false) { // The user has unchecked the category's checkbox
			for (var i=0; i<gmarkers.length; i++) { // Iterate over all the markers
				if (gmarkers[i].type == category) { // If the marker is in this category,
					map.removeOverlay(gmarkers[i]);  // remove it from the map
				}
			}
		} else { // The user has checked the category's checkbox
			for (var i=0; i<gmarkers.length; i++) { // Iterate over all the markers
				if (gmarkers[i].type == category) { // If the marker is in this category,
					map.addOverlay(gmarkers[i]); // add it to the map
				}
			}
		}
	}
}

// This function hides or shows a specific Google map marker
// It's not in the main if (GBrowserIsCompatible()) block 
//	because the means to call this function (i.e. checkboxes)
//	may appear on the page even if the browser is not compatible
function toggleMarker(marker) {
	if (map && typeof map == 'object') { // First check to see if the map exists
		map.closeInfoWindow(); // Close any open info windows
	
		for (var i=0; i<gmarkers.length; i++) { // Iterate over all the markers
			if (gmarkers[i].code == marker) { // If this is the marker we're looking for
				gmarkers[i].openInfoWindowHtml(htmls[i]);  // open its window
				break;
			}
		}
	}
}