/* ====================================================== */
/* =========   Google Maps API / JNID Mapping   ========= */
/* ==========        Version A09.07.17          ========= */
/* ====================================================== */

if (GBrowserIsCompatible()) {
	
// ===========================================
// JMap Global Variables =====================
	
	var jmap_markers = []; // 2-dimensional array containing all the markers (2nd dimension) in each category (1st dimension)
	var jmap_shapes = []; // 2-dimensional array containing all the shapes (2nd dimension) in each category (1st dimension)
	var jmap_icons = []; // associative array holding GIcons for each category of markers
	var jmap_bounds = new GLatLngBounds(); // used to fit the map zoom and center to the markers displayed
	var categories_shown = 0; // used to set map zoom and center back to initial values if no categories are shown
	var lastLinkID = ""; // used with highlighting/unhighlighting markers in the menu when selected
	var lastArrowID = ""; // used with highlighting/unhighlighting markers in the menu when selected
			
	// Set padding for map to ensure markers/shapes don't appear under the map menu, map controls, or too near the map edge
	var jmap_paddingTop = 80;
	var jmap_paddingRight = 50;
	var jmap_paddingBottom = 100;
	var jmap_paddingLeft = 250;

// ===========================================
// JMap Functions ============================

	// Set icon
	function setIcon(type,color,number){
		number++;
		var icon = new GIcon();
		icon.image = jmap_iconPath + type + "_" + color + ".png";
		icon.iconSize = new GSize(27, 27);
		icon.iconAnchor = new GPoint(14, 15);
		icon.infoWindowAnchor = new GPoint(14, 15);
		icon.imageMap = [2,11, 10,11, 14,1, 18,11, 26,11, 20,18, 21,26, 14,22, 7,26, 8,19];
		icon.transparent = jmap_iconPath + type + "_transparent.png"; 
		icon.label = {"url":jmap_iconPath + type + "_" + number + ".png",
					 "anchor":new GPoint(0,0),
					 "size":new GSize(27,27)};
		return icon;
	}
	
	// Set the map zoom and center	
	function setBounds(){
		// Clear jmap_bounds of markers
		jmap_bounds = new GLatLngBounds();
		// If no categories are selected, reset the map zoom and center to initial values
		if (categories_shown == 0) {
			jmap_initialZoom();
		} else {
			// For each category...
			for (var i = 0; i < Math.max(jmap_markers.length,jmap_shapes.length); i++) {
				// If this category is displayed and has markers...
				if (jmap_markers[i] && jmap_markers[i][3]) {
					// Add the markers to the jmap_bounds
					for (var j = 4; j < jmap_markers[i].length; j++) {
						jmap_bounds.extend(jmap_markers[i][j].latLong); // marker [j]
						}
					}
				// If this category is displayed and has shapes...
				if (jmap_shapes[i] && jmap_shapes[i][3]) {
					// For each shape..
					for (var j = 4; j < jmap_shapes[i].length; j++) {
						// Add each vertex to the jmap_bounds
						for (var k = 0; k < jmap_shapes[i][j].getVertexCount(); k++){ // shape [j]
							jmap_bounds.extend(jmap_shapes[i][j].getVertex(k)); // vertex [k]
							}
						}
					}
				}
			
			// Set the map zoom to fit the markers displayed with padding
			var jmap_size = jmap.getSize();
			var jmap_type = jmap.getCurrentMapType();
			var jmap_paddedBounds = new GSize(jmap_size.width - jmap_paddingLeft - jmap_paddingRight, jmap_size.height - jmap_paddingTop - jmap_paddingBottom);
			var jmap_paddedZoom = jmap_type.getBoundsZoomLevel(jmap_bounds, jmap_paddedBounds);
			jmap.setZoom(jmap_paddedZoom);
			
			// Set the map center to fit the markers displayed with padding
			var xOffset = (jmap_paddingLeft - jmap_paddingRight)/2;
			var yOffset = (jmap_paddingTop - jmap_paddingBottom)/2;
			var jmap_boundsCenter = jmap.fromLatLngToDivPixel(jmap_bounds.getCenter());
			var jmap_newCenter = jmap.fromDivPixelToLatLng(new GPoint(jmap_boundsCenter.x - xOffset, jmap_boundsCenter.y - yOffset));
			jmap.setCenter(jmap_newCenter);
			}
	}
	
	// Create the marker and set up the event window (returns the marker)
	function createMarker(i,j,type,color,number,this_name,this_lat,this_long,this_tab_names,this_tab_contents) {
		var currentLinkID = 'jmap_menu_marker' + i + '_' + (j + 4);
		var currentArrowID = 'jmap_menu_arrow' + i + '_' + (j + 4);
		var this_icon = setIcon(type,color,number);
		var this_marker = new GMarker(new GLatLng(this_lat,this_long),this_icon); // i is the category number
		var this_tabs = [];
		for (var k = 0; k < this_tab_names.length; k++) {
			this_tabs.push(new GInfoWindowTab(this_tab_names[k],this_tab_contents[k]));
			}
		// Marker properties: marker name and position
		this_marker.name = this_name;
		this_marker.latLong = new GLatLng(this_lat,this_long);
		GEvent.addListener(this_marker, "click", function() {
			this_marker.openInfoWindowTabsHtml(this_tabs);
			window.setTimeout( function () {
				jmap.setZoom(zoomLevel_marker);
				var jmap_markerCenter = jmap.fromLatLngToDivPixel(this_marker.latLong);
				var jmap_newCenter = jmap.fromDivPixelToLatLng(new GPoint(jmap_markerCenter.x, jmap_markerCenter.y - 100));
			    jmap.setCenter(jmap_newCenter);
				},50);
			document.getElementById(currentLinkID).className = "jmap_menu_entries jmap_menu_entries_highlight";
			document.getElementById(currentArrowID).style.display = "inline-block";
			lastLinkID = currentLinkID;
			lastArrowID = currentArrowID;
			});
		return this_marker;
	}
	
	// Show all markers of a particular category
	function show_category(category_number) {
		categories_shown++;
		if (jmap_markers[category_number]) {
			for (var j = 4; j < jmap_markers[category_number].length; j++) {
				jmap_markers[category_number][j].show();
				}
			}
		if (jmap_shapes[category_number]) {
			for (var j = 4; j < jmap_shapes[category_number].length; j++) {
				jmap_shapes[category_number][j].show();
				}
			}
		// Highlight the category and show the icon in the menu
		document.getElementById("jmap_menu_category" + category_number).className  = "jmap_menu_category jmap_menu_category_highlight";
		document.getElementById("jmap_menu_category_icon" + category_number).style.display  = "inline-block";
		// Ensure the category checkbox is checked
		document.getElementById("checkbox" + category_number).checked = true;
		// Display the markers in the map menu
		document.getElementById("jmap_menu_contents" + category_number).style.display = "block";
		// Set the category "displayed" value to true
		if (jmap_markers[category_number]) { jmap_markers[category_number][3] = 1; }
		if (jmap_shapes[category_number]) { jmap_shapes[category_number][3] = 1; }
		// Set map zoom and center for new array of displayed markers
		setBounds();
	}
	
	// Hide all markers of a particular category
	function hide_category(category_number) {
		if (categories_shown != 0) { categories_shown--; }
		if (jmap_markers[category_number]) {
			for (var j = 4; j < jmap_markers[category_number].length; j++) {
				jmap_markers[category_number][j].hide();
				}
			}
		if (jmap_shapes[category_number]) {
			for (var j = 4; j < jmap_shapes[category_number].length; j++) {
				jmap_shapes[category_number][j].hide();
				}
			}
		// Un-highlight the category and hide the icon in the menu
		document.getElementById("jmap_menu_category" + category_number).className  = "jmap_menu_category";
		document.getElementById("jmap_menu_category_icon" + category_number).style.display  = "none";
		// Ensure the category checkbox is not checked
		document.getElementById("checkbox" + category_number).checked = false;
		// Display the markers in the map menu
		document.getElementById("jmap_menu_contents" + category_number).style.display = "none";
		// Set the category "displayed" value to false
		if (jmap_markers[category_number]) { jmap_markers[category_number][3] = 0; }
		if (jmap_shapes[category_number]) { jmap_shapes[category_number][3] = 0; }
		// Close the info window in case its open on a marker that we just hid
		jmap.closeInfoWindow();
		// Set map zoom and center for new array of displayed markers
		setBounds();
	}
	
	// When a checkbox is clicked
	function jmap_checkClick(check_box,category_number) {
		if (check_box.checked) {
		  show_category(category_number);
		} else {
		  hide_category(category_number);
		}
	}
	
	function jmap_clickMarker(category_number, marker_number) {
		GEvent.trigger(jmap_markers[category_number][marker_number],"click");
	}
	
	function jmap_loadData(xml_file) {
		GDownloadUrl(xml_file, function(data) {
			var xml = GXml.parse(data);
			var this_category = [];
			var jmap_categoryHtml = "";
			var jmap_markersHtml = "";
			var jmap_shapesHtml = "";
			
			// Category name
			this_category[0] = xml.getElementsByTagName("category_name")[0].childNodes[0].nodeValue;
			// Category icon type
			this_category[1] = xml.getElementsByTagName("category_icon_type")[0].childNodes[0].nodeValue;
			// Category icon color
			this_category[2] = xml.getElementsByTagName("category_icon_color")[0].childNodes[0].nodeValue;
			// Category displayed
			this_category[3] = parseInt(xml.getElementsByTagName("category_default_display")[0].childNodes[0].nodeValue);
			// Category contains markers?
			var contains_markers = parseInt(xml.getElementsByTagName("contains_markers")[0].childNodes[0].nodeValue);
			// Category contains shapes?
			var contains_shapes = parseInt(xml.getElementsByTagName("contains_shapes")[0].childNodes[0].nodeValue);
				
			// Create category HTML for map menu
			var jmap_categoryHtml = '<div id="jmap_menu_category' + i + '" class="jmap_menu_category">' + "\n" +
				'<p><img id="jmap_menu_category_icon' + i + '" src="' + jmap_iconPath + this_category[1] + '_' + this_category[2] + '.png" style="display:none; margin:3px 0px;"/>' +
				'<input type="checkbox" id="checkbox' + i + '" onclick="jmap_checkClick(this,' + i + '); jmap.closeInfoWindow();" />' + this_category[0] +
				'</p></div>' + "\n" +
			    '<div id="jmap_menu_contents' + i + '" class="jmap_menu_entries">' + "\n";
			
			// If this category contains markers, load them
			if (contains_markers) {
				var xmlMarkers = xml.getElementsByTagName("marker");	
				for (var j = 0; j < xmlMarkers.length; j++) {
					// Obtain the information for each marker
					var this_name = xmlMarkers[j].getElementsByTagName("marker_name")[0].childNodes[0].nodeValue;
					var this_lat = parseFloat(xmlMarkers[j].getElementsByTagName("marker_lat")[0].childNodes[0].nodeValue);
					var this_long = parseFloat(xmlMarkers[j].getElementsByTagName("marker_long")[0].childNodes[0].nodeValue);
					var xmlMarker_tabs = xmlMarkers[j].getElementsByTagName("marker_tab");
					var this_tab_names = [];
					var this_tab_contents = [];
					for (var k = 0; k < xmlMarker_tabs.length; k++) {
						this_tab_names.push(xmlMarker_tabs[k].getAttribute("name"));
						this_tab_contents.push(xmlMarker_tabs[k].childNodes[0].nodeValue);
						}
					// Create the marker
					var this_marker = createMarker(i,j,this_category[1],this_category[2],j,this_name,this_lat,this_long,this_tab_names, this_tab_contents);
					// Add the marker to the map
					jmap.addOverlay(this_marker);
					// Add marker to category array ([4] - [x] category markers)
					this_category.push(this_marker);
					}
				// Add category array to jmap_markers array
				jmap_markers[i] = this_category;
				// Add category markers to map menu
				for (var j = 4; j < this_category.length; j++) {
					// Add category markers to menu
					jmap_markersHtml += '<a id="jmap_menu_marker' + i + '_' + j + '" onclick="jmap_clickMarker(' + i + ', ' + j + ')">' +
						'<img id="jmap_menu_arrow' + i + '_' + j + '" src="' + jmap_iconPath + 'menu_arrow_' + this_category[2] + '.png" style="display:none;"/>' +
						'<b>' + (j - 3) + '.</b> ' + this_category[j].name + '</a>' + "\n";
					}
			}
			
			// If this category contains shapes, load them
			if (contains_shapes) {
				// If this category contains markers, reset this_category so that first shape goes into this_category[4]
				// otherwise, the first marker will go into this_category[4 + number_of_markes]...
				if (contains_markers) {
					var temp_array = this_category;
					var this_category = [];
					this_category[0] = temp_array[0];
					this_category[1] = temp_array[1];
					this_category[2] = temp_array[2];
					this_category[3] = temp_array[3];
					}
				var xmlShapes = xml.getElementsByTagName("shape");	
				for (var j = 0; j < xmlShapes.length; j++) {
					// Obtain the information for each shape
					var this_name = xmlShapes[j].getElementsByTagName("shape_name")[0].childNodes[0].nodeValue;
					var this_type = xmlShapes[j].getElementsByTagName("shape_type")[0].childNodes[0].nodeValue;
					var this_lineColor = xmlShapes[j].getElementsByTagName("shape_line_color")[0].childNodes[0].nodeValue;
					var this_lineWidth = xmlShapes[j].getElementsByTagName("shape_line_width")[0].childNodes[0].nodeValue;
					var this_lineOpacity = xmlShapes[j].getElementsByTagName("shape_line_opacity")[0].childNodes[0].nodeValue;
					if (this_type == "polygon") {
						var this_fillColor = xmlShapes[j].getElementsByTagName("shape_fill_color")[0].childNodes[0].nodeValue;
						var this_fillOpacity = xmlShapes[j].getElementsByTagName("shape_fill_opacity")[0].childNodes[0].nodeValue;
						}
					var xmlShape_vertices = xmlShapes[j].getElementsByTagName("vertex");
					var this_vertices = [];
					for (var k = 0; k < xmlShape_vertices.length; k++) {
						this_vertices.push(new GLatLng(parseFloat(xmlShape_vertices[k].getElementsByTagName("vertex_lat")[0].childNodes[0].nodeValue),
													   parseFloat(xmlShape_vertices[k].getElementsByTagName("vertex_long")[0].childNodes[0].nodeValue)));
						}
					// If the shape is a polygon, create it
					if (this_type == "polygon") {
						var this_shape = new GPolygon(this_vertices,this_lineColor,this_lineWidth,this_lineOpacity,this_fillColor,this_fillOpacity);
					} else {
						var this_shape = new GPolyline(this_vertices,this_lineColor,this_lineWidth,this_lineOpacity);
						}
					this_shape.type = this_type;
					// Add the marker to the map
					jmap.addOverlay(this_shape);
					// Add marker to category array ([4] - [x] category markers)
					this_category.push(this_shape);
					}
				// Add category array to jmap_shapes array
				jmap_shapes[i] = this_category;
				// Add category shapes to map menu
				for (var j = 4; j < this_category.length; j++) {
					jmap_shapesHtml += '<a id="jmap_menu_shape' + i + '_' + j + '"><img src="' + jmap_iconPath + 'menu_' + this_category[j].type + '_' + this_category[2] + '.png" class="jmap_menu_shape" /> ' +  this_name + '</a>' + "\n";
					}
			}
			// Add this category to the map menu
			jmap_menuContents.innerHTML += jmap_categoryHtml + jmap_markersHtml + jmap_shapesHtml + '</div>' + "\n";
			// Finally, if this category should be displayed initially...
			if (this_category[3]) {
				show_category(i);
			// Otherwise...
			} else {
				hide_category(i); 
			    }
			previousFileLoaded = true;
			});
		}
		
	function jmap_setTypeButton(imageName) {
		jmap_currentType = imageName;
		document.getElementById('jmap_political_button').src = Cpath_toJnidImages + "jmap-ui/political_up.png";
		document.getElementById('jmap_satellite_button').src = Cpath_toJnidImages + "jmap-ui/satellite_up.png";
		document.getElementById('jmap_hybrid_button').src = Cpath_toJnidImages + "jmap-ui/hybrid_up.png";
		document.getElementById('jmap_physical_button').src = Cpath_toJnidImages + "jmap-ui/physical_up.png";
	    document.getElementById('jmap_' + imageName + '_button').src = Cpath_toJnidImages + "jmap-ui/" + imageName + "_down.png";
	}
		
	function jmap_buttonOver(imageName) {
		document.getElementById('jmap_' + imageName + '_button').src = Cpath_toJnidImages + "jmap-ui/" + imageName + "_down.png";
	}
		
	function jmap_buttonOut(imageName) {
		if (jmap_currentType != imageName) {
		document.getElementById('jmap_' + imageName + '_button').src = Cpath_toJnidImages + "jmap-ui/" + imageName + "_up.png";
		}
	}
	
	function jmap_showAll() {
		for (var i = 0; i < Math.max(jmap_markers.length,jmap_shapes.length); i++) {
			show_category(i);
		}
	}
	
	function jmap_showNone() {
		for (var i = 0; i < Math.max(jmap_markers.length,jmap_shapes.length); i++) {
			hide_category(i);
		}
	}

// ===========================================
// Load map and data =========================
	
	// Load map name
	document.getElementById("jmap_title").innerHTML = jmap_title + " Map";
	// Initialize map canvas
	var jmap = new GMap2(document.getElementById("jmap_canvas"));
	jmap.addMapType(G_PHYSICAL_MAP);
	// Set map type and controls, as specified in jmap-params.js
	jmap_inits();
	
	// Insert map menu title and "loading" message
	var jmap_menuContents = document.getElementById("jmap_menu");
	jmap_menuContents.innerHTML = '<div id="jmap_menu_title">' + jmap_menu_title + '</div>';
	jmap_menuContents.innerHTML += '<div id="jmap_menu_loading" class="jmap_menu_category">' + "\n" +
						 '<p id="jmap_menu_loading_text">Files are loading.<br />Please be patient...</p>' + "\n" +
						 '</div>' + "\n";
	jmap_menuContents.innerHTML += '<div id="jmap_menu_buttons"><button type="submit" onclick="jmap_showAll();">Show All</button> &nbsp; <button type="submit" onclick="jmap_showNone();">Show None</button></div>';

	// Makes the text "Files are loading, please be patient" blink to attract user's attention					 
	var jmap_menuBlinkingText = window.setInterval( function () {
		if (document.getElementById('jmap_menu_loading_text').style.visibility == "visible") {
			document.getElementById('jmap_menu_loading_text').style.visibility = "hidden";
		} else { document.getElementById('jmap_menu_loading_text').style.visibility = "visible"; }
		if (allFilesLoaded) {
			document.getElementById('jmap_menu_loading').style.backgroundColor = "#CCFFCC";
			document.getElementById('jmap_menu_loading').innerHTML = '<p id="jmap_menu_loading_text">Successfully loaded files!</p>';
			setTimeout( function () {
				document.getElementById('jmap_menu_loading').style.display = "none";
				clearInterval(jmap_menuBlinkingText);
				} ,1500);
			}
		}, 500);
	
	// Load the data
	var i = 0;
	var previousFileLoaded = false;
	var allFilesLoaded = false;
	// Load first marker file (put markers on map and create category in map menu)
	jmap_loadData(jmap_files[i]);
	// Load rest of files (1 per second)
	var interval = window.setInterval( function () { 
		if (previousFileLoaded) {
			i++;
			if (i == (jmap_files.length)) {
				allFilesLoaded = true;
				clearInterval(interval);
				}
			previousFileLoaded = false;
		    jmap_loadData(jmap_files[i]);
			}
		}, 50);
	
	GEvent.addListener(jmap,"infowindowclose", function() {
		document.getElementById(lastLinkID).className = "jmap_menu_markers";
		document.getElementById(lastArrowID).style.display = "none";
		});
}

else {
  document.getElementById("this_map_name").innerHTML = jmap_name + "Sorry, the Google Maps API is not compatible with this browser.<br />  We recommend that you use Internet Explorer 8, Mozilla Firefox 3, or Chrome 2.";
  alert("Sorry, the Google Maps API is not compatible with this browser. We recommend that you use Internet Explorer 8, Mozilla Firefox 3, or Chrome 2.");
}