//***************************************************************
// Restaurant Blackbook Google Maps
// v1.0 2006-12-29
// Copyright © 2006 - 2010, 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_data_request; // Used to make an asynchronous call to get the map data
	var geolocation_request; // Used to make an asynchronous call to get the user's location data

	var map; // The map
	var bounds = new GLatLngBounds(); // Bounds of the map
	var geocoder = null; // Used to resolve addresses the user enters
	var all_markers = []; // The array of all map markers
	var all_markers_array_index = 0; // Index of the current restaurant data

	var icons = []; // Array of our different colored icons
	var base_icon = new GIcon();	// The default icon/pushpin with the appropriate values set below...
	base_icon.image = "/resources/images/map_pushpins/pushpin_black.png";
	base_icon.shadow = "/resources/images/map_pushpins/pushpin_shadow.png";
	base_icon.iconSize = new GSize(12, 20);
	base_icon.shadowSize = new GSize(22, 20);
	base_icon.iconAnchor = new GPoint(6, 20);
	base_icon.infoWindowAnchor = new GPoint(5, 1);
	base_icon.imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0];

	var restaurant_tab_label = 'Restaurant'; // Label for the first tab
	var notes_tab_label = 'Notes'; // Label for the second tab
	var directions_tab_label = 'Directions'; // Label for the third tab

	var all_restaurant_tabs_html = [];
	var all_notes_tabs_html = [];
	var all_directions_tabs_html = [];

	var users_latitude = 0;
	var users_longitude = 0;
	var users_zip_code = '';
	var intersites_latitude = 41.918113;
	var intersites_longitude = -88.341037;
	var intersites_zip_code = '60174';
	var map_latitude = intersites_latitude; // Set the center to our office by default
	var map_longitude = intersites_longitude;
	var map_zip_code = intersites_zip_code;


	/***************** Not currently in use...
	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
	*****************/

	// The main function for the map. Should be called when the page is loaded, either by the <BODY > tag's onLoad="" event or some other mechanism.
	function makeMap() {
		map = new GMap2(document.getElementById("restaurant_gmap")); // Create a map using the div named "restaurant_gmap"
		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

		//$m.cookies.get("blackbook_coords");
		/*
		if cookie
			setCenter on cookie coords
		else
			setCenter on default
		*/

		map.setCenter(new GLatLng(map_latitude, map_longitude), 11); // Set the center over Intersites office and zoom to a level likely to encompass the some Chicagoland markers

		geolocation_request = GXmlHttp.create(); // Prepare to make an asynchronous call to get the user's location
		geolocation_request.open("GET", "geolocate_ip.php", true); // Make the call to get the user's location, synchronously, so we know it before the map opens
		geolocation_request.onreadystatechange = geolocateUser; // When data is returned, call the function to process the data
		geolocation_request.send(null); // Close the connection

		map_data_request = GXmlHttp.create(); // Prepare to make an asynchronous call to get the map data
		map_data_request.open("GET", "restaurants.php", true); // Make the call to get the map data
		map_data_request.onreadystatechange = processXML; // When data is returned, call the function to process the data
		map_data_request.send(null); // Close the connection

		geocoder = new GClientGeocoder(); // Create a geocoder so we can translate an address the user enters
	}


	function geolocateUser() {
		if (geolocation_request.readyState == 4) { // If we have a final response from the server
			if (geolocation_request.status != 200) { //	and it's a file not found
				alert("File not found: " + geolocation_request.status); // let the user know
				return; // and get out
			}
			var xmlDoc = geolocation_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
			}

			users_latitude_element = xmlDoc.documentElement.getElementsByTagName("Latitude")[0].childNodes;
			if (users_latitude_element.length > 0) {
				users_latitude = users_latitude_element[0].nodeValue; // Parse the file to find the latitude
			}
			users_longitude_element = xmlDoc.documentElement.getElementsByTagName("Longitude")[0].childNodes;
			if (users_longitude_element.length > 0) {
				users_longitude = users_longitude_element[0].nodeValue; // Parse the file to find the latitude
			}
			zip_postal_code_element = xmlDoc.documentElement.getElementsByTagName("ZipPostalCode")[0].childNodes;
			if (zip_postal_code_element.length > 0) {
				users_zip_code = zip_postal_code_element[0].nodeValue; // Parse the file to find the latitude
			}
		}
	}



	// 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 (map_data_request.readyState == 4) { // If we have a final response from the server
			if (map_data_request.status != 200) { //	and it's a file not found
				alert("File not found: " + map_data_request.status); // let the user know
				return; // and get out
			}
			var xmlDoc = map_data_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
			}

			$m.t.intersites.restaurants.populate(xmlDoc);
			$m.t.intersites.restaurants.write();

			var	restaurant_tab_html = "";
			var notes_tab_html = "";
			var directions_tab_html = "";

			markers_data = xmlDoc.documentElement.getElementsByTagName("marker"); // Parse the file by markers/restaurants

			// for (var i=0; i < 2; i++) { // For just a couple of times to debug
			for (var i=0; i < markers_data.length; i++) { // For each restaurant

				// Build the HTML for the first tab
				restaurant_tab_html = ""; // clear it first
				restaurant_tab_html += '<div style="width:350px; font-family:arial;">';
					if (markers_data[i].getAttribute("picture") !== "") { restaurant_tab_html += '<img src="' + markers_data[i].getAttribute("picture") + '" alt="' + markers_data[i].getAttribute("name") + '" title="" style="float: right; margin-left: 5px;">'; }
					restaurant_tab_html += '<strong>' + markers_data[i].getAttribute("name") + '</strong><br>';
					if (markers_data[i].getAttribute("tagline") !== "") { restaurant_tab_html += '<em>&ldquo;' + markers_data[i].getAttribute("tagline") + '&rdquo;</em><br>'; }
					if (markers_data[i].getAttribute("address1") !== "") { restaurant_tab_html += markers_data[i].getAttribute("address1"); }
					if (markers_data[i].getAttribute("address2") !== "") { restaurant_tab_html += ', ' + markers_data[i].getAttribute("address2"); }
					if (markers_data[i].getAttribute("city") !== "") { restaurant_tab_html += ', ' + markers_data[i].getAttribute("city"); }
					if (markers_data[i].getAttribute("state") !== "") { restaurant_tab_html += ', ' + markers_data[i].getAttribute("state"); }
					if (markers_data[i].getAttribute("phone") !== "") { restaurant_tab_html += '<br>' + markers_data[i].getAttribute("phone"); }
					if (markers_data[i].getAttribute("web_address") !== "") { restaurant_tab_html += '<br><a href="http://' + markers_data[i].getAttribute("web_address") + '" target="_blank">' + markers_data[i].getAttribute("web_address") + '</a>'; }
					if (markers_data[i].getAttribute("food_type") !== "") { restaurant_tab_html += '<br><br>' + markers_data[i].getAttribute("food_type"); }
					if (markers_data[i].getAttribute("hours") !== "") { restaurant_tab_html += '<br><br>' + markers_data[i].getAttribute("hours"); }

					restaurant_tab_html += '<br><br><img src="/resources/images/indicators/price_level/' + markers_data[i].getAttribute("price_level") + '.png" class="valign_middle" alt="' + markers_data[i].getAttribute("price_level") + '" title=""> &ndash; ' + markers_data[i].getAttribute("price_level_description");
					restaurant_tab_html += '<img src="/resources/images/indicators/attractiveness/' + markers_data[i].getAttribute("attractiveness") + '.png" class="valign_middle" alt="' + markers_data[i].getAttribute("attractiveness") + '" title="" style="margin-left: 5px;"> &ndash; ' + markers_data[i].getAttribute("attractiveness_description");

					restaurant_tab_html += '<br><br>Introduced By: ';
					if (markers_data[i].getAttribute("source") !== null)
					{
						if (markers_data[i].getAttribute("source_url") === null || markers_data[i].getAttribute("source_url") == "")
						{
							restaurant_tab_html += markers_data[i].getAttribute("source");
						}
						else
						{
							if (markers_data[i].getAttribute("source_url").match("http"))
								restaurant_tab_html += '<a href="' + markers_data[i].getAttribute("source_url") + '" target="_blank">' + markers_data[i].getAttribute("source") + '</a>';
							else
								restaurant_tab_html += markers_data[i].getAttribute("source") + ', ' + markers_data[i].getAttribute("source_url");
						}
					}
				restaurant_tab_html += '</div>';
				all_restaurant_tabs_html[all_markers_array_index] = restaurant_tab_html;


				 // Build the HTML for the second ('Notes') tab
				notes_tab_html = ""; // Clear it first
				notes_tab_html += '<div style="width:350px; font-family:arial;">';
					if (markers_data[i].getAttribute("notes") !== "") { notes_tab_html += (markers_data[i].getAttribute("notes")).replace(/\.\s/g, ".<br><br>"); } else {notes_tab_html += "None so far."}
				notes_tab_html +=	'</div>';
				all_notes_tabs_html[all_markers_array_index] = notes_tab_html;


				 // Build the HTML for the third ('Directions') tab
				directions_tab_html = ""; // Clear it first
				var to_here_id = "to_here_" + new Date().getTime();
				var from_here_id = "from_here_" + new Date().getTime();
				directions_tab_html += '<div style="width:350px; font-family:arial;">' +
					'<div id="' + to_here_id + '" style="display: block;">Directions: <b>To here</b> - <a href="javascript:get_directions(\'' + from_here_id + '\',\'' + to_here_id + '\')">From here</a><br>' +
					'<br>Start address:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
					'<input type="text" size="40" maxlength="40" name="saddr" id="saddr" value="" class="input_text"><br><br>' +
					'<input value="Get Directions" type="submit" class="input_submit"> <span class="helper_text">(opens in a new window)</span>' +
					'<input type="hidden" name="daddr" value="' + markers_data[i].getAttribute("lat") + ',' + markers_data[i].getAttribute("lng") + "(" + name + ")" + '"></form></div>' +

					'<div id="' + from_here_id + '" style="display: none;">Directions: <a href="javascript:get_directions(\'' + to_here_id + '\',\'' + from_here_id + '\')">To here</a> - <b>From here</b><br>' +
					'<br>End address:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
					'<input type="text" size="40" maxlength="40" name="daddr" id="daddr" value="" class="input_text"><br><br>' +
					'<input value="Get Directions" type="submit" class="input_submit"> <span class="helper_text">(opens in a new window)</span>' +
					'<input type="hidden" name="saddr" value="' + markers_data[i].getAttribute("lat") + ',' + markers_data[i].getAttribute("lng") + "(" + name + ")" + '"></form></div>';
				directions_tab_html +=	'</div>';
				all_directions_tabs_html[all_markers_array_index] = directions_tab_html;

				 // Call the function to add the marker to the map

				var point = new GLatLng(parseFloat(markers_data[i].getAttribute("lat")), parseFloat(markers_data[i].getAttribute("lng"))); // Create a point at the latitude and longitude of our office
				bounds.extend(point); // Extend the bounds of the map to include the point

				var icon = createCategoryIcon(markers_data[i].getAttribute("icon"));
				var marker = new GMarker(point, icon); // Create a marker at this location and with the right color
				marker.code = markers_data[i].getAttribute("code");
				marker.price_level = markers_data[i].getAttribute("price_level");
				marker.attractiveness = markers_data[i].getAttribute("attractiveness");


				var do_it_where = 'function';

				if (do_it_where == 'function') {
					addMarkerToMap(
						marker,
						restaurant_tab_label,
						restaurant_tab_html,
						notes_tab_label,
						notes_tab_html,
						directions_tab_label,
						directions_tab_html
					);
				} else {

					// Not sure how GEvent.addListener() is assigning the onclick to the marker
					// since the marker itself isn't an HTML element but a JavaScript object.

					// Even though the marker is being "var"ed in the loop, GEvent.addListener()
					// sees it as having the same map bubble.

					// When it's called by passing the marker object to another function,
					// it works. Probably because it's passing a copy that's uniquely identified.

					// Trying to track down GEvent.addListener() and other "G" objects is a headache. :-)

					// If/when we figure this out, we can probably use the means to uniquely identify
					// a marker and use the "all_markers" array to store only an ID instead of the whole marker object

					GEvent.addListener(marker, "click", function() { // Create the function to call if the user clicks on the marker
						marker.openInfoWindowTabsHtml([
							 new GInfoWindowTab(restaurant_tab_label, restaurant_tab_html)
							,new GInfoWindowTab(notes_tab_label, notes_tab_html)
							,new GInfoWindowTab(directions_tab_label, directions_tab_html)
						]);
					});
				}

				map.addOverlay(marker); // Add the marker to the map! Yeah!
				marker.displayed = true;
				all_markers[i] = marker; // Store the marker into the array
				all_markers_array_index++; // Increment the array index
			}


			// Add Intersites to the map

			var point = new GLatLng(intersites_latitude, intersites_longitude); // Create a point at the latitude and longitude of our office
			bounds.extend(point); // Extend the bounds of the map to include the point
			var icon = createCategoryIcon('intersites'); // Get our icon
			var marker = new GMarker(point, icon); // Create a marker at this location and with the right color

			// Build the HTML to display on the info window
			var to_here_id = "to_here_" + new Date().getTime();
			var from_here_id = "from_here_" + new Date().getTime();
			var intersites_marker_html = '<div style="width:350px; font-family:arial;">' +
				'<img src="/resources/images/blackbook/intersites.jpg" alt="Intersites, Inc." title="" style="float: right; margin-left: 5px;">' +
				'<strong>Intersites, Inc.</strong><br>' +
				'333 N Randall Rd, Suite 131<br>St Charles, IL  60174<br>' +
				'630-762-8469<br>' +
				'<br>' +
				'</div>' +
				'<div id="' + to_here_id + '" style="display: block;">Directions: <b>To here</b> - <a href="javascript:get_directions(\'' + from_here_id + '\',\'' + to_here_id + '\')">From here</a><br>' +
				'<br>Start address:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
				'<input type="text" size=40 maxlength=40 name="saddr" id="saddr" value="" class="input_text"><br><br>' +
				'<input value="Get Directions" type="submit" class="input_submit"> <span class="helper_text">(opens in a new window)</span>' +
				'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + "(Intersites)" + '"></form></div>' +

				'<div id="' + from_here_id + '" style="display: none;">Directions: <a href="javascript:get_directions(\'' + to_here_id + '\',\'' + from_here_id + '\')">To here</a> - <b>From here</b><br>' +
				'<br>End address:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
				'<input type="text" size="40" maxlength="40" name="daddr" id="daddr" value="" class="input_text"><br><br>' +
				'<input value="Get Directions" type="submit" class="input_submit"> <span class="helper_text">(opens in a new window)</span>' +
				'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() + "(Intersites)" + '"></form></div>';
				'</div>';

			GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(intersites_marker_html)}); // Create the function to call if the user clicks on the marker
			map.addOverlay(marker); // Add the marker to the map! Yeah!

			// Now that we've processed every marker in the data file and added Intersites to the map...
			// If we couldn't get a good location for the user
			if (users_latitude == 0 || users_longitude == 0 || (users_latitude == 38 || users_longitude == -97)) {
				map.setZoom(map.getBoundsZoomLevel(bounds)); // Set the zoom to encompass the bounds
				var latitude_center_of_bounds = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2; // Figure out the latitude of the center of the map
				var longitude_center_of_bounds = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2; // and the longitude
				map.setCenter(new GLatLng(latitude_center_of_bounds, longitude_center_of_bounds)); // and set the map's center to that location
			} else {
				map.setCenter(new GLatLng(users_latitude, users_longitude), 13); // Set the center over the user's geolocated position and zoom to a level likely to encompass their zip code
				document.getElementById("filter_by_zip").value = users_zip_code;
			}
		}
	}


	function addMarkerToMap(marker, first_tab_label, all_restaurant_tabs_html, second_tab_label, all_notes_tabs_html, third_tab_label, all_directions_tabs_html) {
		// Create the function to call if the user clicks on the marker
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowTabsHtml([
				 new GInfoWindowTab(first_tab_label, all_restaurant_tabs_html)
				,new GInfoWindowTab(second_tab_label, all_notes_tabs_html)
				,new GInfoWindowTab(third_tab_label, all_directions_tabs_html)
			]);
		});
	}



	// 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(base_icon); // create a new icon based off the base icon
			icon.image = "http://www.intersites.com/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 toggles the display of the directions
	function get_directions(in_show, in_hide) {
		document.getElementById(in_show).style.display = "block";
		document.getElementById(in_hide).style.display = "none";
	}


	/***************** Not currently in use...
	// 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) {
		all_markers[i].openInfoWindowTabsHtml([new GInfoWindowTab(restaurant_tab_label, to_htmls[i]), new GInfoWindowTab(notes_tab_label, to_htmls_details[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) {
		all_markers[i].openInfoWindowTabsHtml([new GInfoWindowTab(restaurant_tab_label, from_htmls[i]), new GInfoWindowTab(notes_tab_label, from_htmls_details[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 attribute
// 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(filter_type, filter_value, filter_checked) {

	// $m.de.add_item("filter_type = " + filter_type + " AND filter_value = " + filter_value + " AND filter_checked = " + filter_checked);

	if (map && typeof map == 'object') { // First check to see if the map exists
		map.closeInfoWindow(); // Close any open info windows

		if (filter_checked === false) { // The user has unchecked the category's checkbox
			for (var i=0; i < all_markers.length; i++) { // Iterate over all the markers
				if (all_markers[i][filter_type] == filter_value) { // If the marker is in this category,
					map.removeOverlay(all_markers[i]);  // remove it from the map
				}
			}
		} else { // The user has checked the category's checkbox
			for (var i=0; i < all_markers.length; i++) { // Iterate over all the markers
				if (all_markers[i][filter_type] == filter_value) { // If the attribute for this marker matches the value,
					map.addOverlay(all_markers[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<all_markers.length; i++) { // Iterate over all the markers
			if (all_markers[i].code == marker) { // If this is the marker we're looking for

				//all_markers[i].openInfoWindowTabsHtml(htmls[i]);  // open its window
				all_markers[i].openInfoWindowTabsHtml([
					 new GInfoWindowTab(restaurant_tab_label, all_restaurant_tabs_html[i])
					,new GInfoWindowTab(notes_tab_label, all_notes_tabs_html[i])
					,new GInfoWindowTab(directions_tab_label, all_directions_tabs_html[i])
				]);

				break;
			}
		}
	}
}


