var Gmap = {
  
	map: null,
	hash: null,
  	mapContainer: null,
  	navContainer: null,
	addrContainer: null,
	welcomeContainer: null,
	XML: null,
	marker: [],
  	markers: [],
	infowindows: [],
	infowindow: null,
	data: false,
	navBar: null,
  
	init: function() {
		this.hash = document.location.hash.substring(1);
    	Gmap.createMap();
    	
    	switch(this.hash)
    	{
    		case 'library':
				Gmap.clearWelcomeMsg();
				setTimeout("Gmap.createMarkers('library')", 1000);
    			break;
    			
			default:
    			Gmap.welcome();
		}
	},
	
	createMap: function() {
	  var startLatLng = null;
		
		this.mapContainer = document.getElementById("map_canvas");
		startLatLng = new google.maps.LatLng(41.873076,-72.669797);//(41.85058, -72.644099);
		this.map = new google.maps.Map(Gmap.mapContainer, {
		  zoom: 12,
			center: startLatLng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false,
			mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
			navigationControlOptions: { style: google.maps.NavigationControlStyle.ZOOM_PAN }
		});
	},
	
	welcome: function() {
		var msg = [];
		Gmap.welcomeContainer = document.getElementById("welcomeMsg");
		
		msg[0] = document.createElement("p");
		msg[0].className = "title";
		msg[0].appendChild(document.createTextNode("Getting Started"));
		msg[1] = document.createElement("p");
		msg[1].appendChild(document.createTextNode("This applet is designed to help find key locations around Windsor. Across the top is a menu containing categorized locations. Click on an item to view locations of that type."));
		msg[2] = document.createElement("img");
		msg[2].setAttribute("src", "/images/gmap/usageMenu.png");
		msg[3] = document.createElement("p");
		msg[3].appendChild(document.createTextNode("Once the results are displayed you can find information such as the address, phone number or driving directions by either clicking a marker on the map or viewing the listed results found below the map on this page."));
		msg[4] = document.createElement("div");
		msg[4].className = "button";
		msg[4].appendChild(document.createTextNode("OK"));
		
		Core.addEventListener(msg[4], "click", Gmap.msgRead);
		
		for(i in msg){
		  Gmap.welcomeContainer.appendChild(msg[i]);
		}
	},
	
	clearWelcomeMsg: function() {
		Gmap.welcomeContainer = document.getElementById("welcomeMsg");	
    	Gmap.msgRead();
	},
	
	msgRead: function() {
		Gmap.welcomeContainer.className = "hidden";
		Gmap.loadNav();
		Gmap.getXMLData();
		Gmap.closeClickListener(Gmap.map);
	},
	
	getXMLData: function() {
		var requester = Core.XMLHttpRequest();
		requester.open("GET", "/pages/towninfo/markerdata.xml", true);
		requester.onreadystatechange = function()
		{
			if (requester.readyState == 4)
			{
				if (requester.status == 200 || requester.status == 304)
				{
					Gmap.XML = requester.responseXML;
					Gmap.createMarkers('townhall');
					Gmap.displayNav();
				}
				else
				{
					Gmap.XMLError("The locations could not be found. Please try refreshing your page.");
				}
			}
		};
		requester.send(null);
	},

	createMarkers: function (filter)
	{
		Gmap.markers = Gmap.XML.documentElement.getElementsByTagName("marker");
		if(filter != null)
		{
			// Closes all the info windows
			Gmap.closeAll();
			
			// Required to remove markers from the map
			for(var i = 0; i < Gmap.marker.length; i++){
			    Gmap.marker[i].setMap(null);
				Gmap.addrContainer.removeChild(Gmap.marker[i]._address);
			};
			Gmap.marker = [];
			
			if(filter !== "all"){
		    // performs a check and adds only the required markers to the map.
				var passed = [];
		    for (var i = 0; i < Gmap.markers.length; i++) {
				  var tags = Gmap.markers[i].getAttribute("tags").split(",");
				  if (Core.in_array(filter, tags)) {
					  passed.push(Gmap.markers[i]);
				  };
			  };
			  Gmap.markers = passed;
			};
		};
    if (Gmap.markers.length >= 1) {
		  for (var i = 0; i < Gmap.markers.length; i++)
		  {	
			  var addr = null;
			  var phone = null;
			  var latlng = new google.maps.LatLng(
		     	parseFloat(Gmap.markers[i].getAttribute("lat")),
          		parseFloat(Gmap.markers[i].getAttribute("lng"))
			  );
			
			  Gmap.marker[i] = new google.maps.Marker
			  ({
			    position: latlng,
				  map: Gmap.map,
				  title: Gmap.markers[i].getAttribute("name"),
				  icon: Gmap.iconSelect(Gmap.markers[i].getAttribute("icon"))
			  });
			  Gmap.marker[i].form = "<form method='get' action='http://maps.google.com/maps' target='_blank'>" +
						"<label for='saddr'>Driving Directions <span>(your&nbsp;address)</span></label><br />" +
						"<input class='saddr' type='text' name='saddr'/>" +
						"<input class='dirSub' type='submit' value='Go' />" +
						"<input type='hidden' value='" + Gmap.markers[i].getAttribute("lat") + ", " + Gmap.markers[i].getAttribute("lng") + "' name='daddr'/>" +
						"</form>";
				
				if(Gmap.markers[i].getAttribute("addr") == '')
				{
				  addr = '';
				}
				else
				{
					addr = Gmap.markers[i].getAttribute("addr") + "<br />Windsor CT, 06095<br />";
				};
				
				if(Gmap.markers[i].getAttribute("phone") == '')
				{
					phone = '';
				}
				else
				{
					phone = "Phone: " + Gmap.markers[i].getAttribute("phone") + "<br />";
				}
				
			  Gmap.marker[i].infowindow = new google.maps.InfoWindow({
			    content: "<div class='bubble'><div class='head'>" + 
				    Gmap.markers[i].getAttribute("name") + "</div><div class='info'>" + Gmap.image(Gmap.markers[i].getAttribute("img")) +
						addr + phone +
						Gmap.marker[i].form + "</div></div>"
		    });
				
				if (typeof(maxLat) == "undefined") { var maxLat = parseFloat(Gmap.markers[i].getAttribute("lat")); }
				if (typeof(maxLng) == "undefined") { var maxLng = parseFloat(Gmap.markers[i].getAttribute("lng")); }
				if (typeof(minLat) == "undefined") { var minLat = parseFloat(Gmap.markers[i].getAttribute("lat")); }
				if (typeof(minLng) == "undefined") { var minLng = parseFloat(Gmap.markers[i].getAttribute("lng")); }
			  maxLat = Gmap.calcMax(maxLat, parseFloat(Gmap.markers[i].getAttribute("lat")));
				maxLng = Gmap.calcMax(maxLng, parseFloat(Gmap.markers[i].getAttribute("lng")));
				minLat = Gmap.calcMin(minLat, parseFloat(Gmap.markers[i].getAttribute("lat")));
				minLng = Gmap.calcMin(minLng, parseFloat(Gmap.markers[i].getAttribute("lng")));
				
				Gmap.addressList(Gmap.markers[i], Gmap.marker[i]);
			  Gmap.clickListener(Gmap.marker[i]);
		  };	
			newLat = (maxLat + minLat) / 2;
			newLng = (maxLng + minLng) / 2;
			//alert(Gmap.map.getCenter());
			//alert(new google.maps.LatLng(newLat,newLng));
			Gmap.map.panTo(new google.maps.LatLng(newLat,newLng));
			//Gmap.map.setCenter(new google.maps.LatLng(newLat,newLng));
    };
	},
	
	loadNav: function()
	{
		Gmap.navContainer = document.getElementById("map_nav");
		Gmap.addrContainer = document.getElementById("map_address");
		var loading = document.createElement("div");
		loading.className = "loading";
		var loadingText = document.createTextNode("Loading...");
		var loadingImage = document.createElement("img");
		loadingImage.setAttribute("src", "/images/progressIndicator_roller.gif");
		loadingImage.setAttribute("alt", "loading progress image");
		loadingImage.className = "loading_img";
		loading.appendChild(loadingImage);
		loading.appendChild(loadingText);
		Gmap.loading = loading;
		Gmap.navContainer.appendChild(loading);
	},
	
	displayNav: function()
	{
		Gmap.navBar = document.createElement("div");
		Gmap.navBar.setAttribute("id", "navbar");
		Gmap.navBar._buttons = [];
		
		var townFacilities = document.createElement("div");
		townFacilities.setAttribute("id", "townfacilities");
		townFacilities.className = "menuButton";
		townFacilities.appendChild(document.createTextNode("Town Facilities"));
		
		var menu = document.createElement("div");
		menu.className = "menuList hidden";
		var linkTitles = ["Town Hall","Public Works","Landfill","Libraries","Firehouses","Police Station"];
		var linkTags = ["townhall","publicworks","landfill","library","fire","police"];
		var menuItem = [];
		for (var i = 0; i < linkTitles.length; i++) {
			menuItem[i] = document.createElement("a");
			menuItem[i].appendChild(document.createTextNode(linkTitles[i]));
			menuItem[i]._tag = linkTags[i];
			menu.appendChild(menuItem[i]);
		}
		townFacilities._menu = menu;
		townFacilities.appendChild(townFacilities._menu);
		
		var schools = document.createElement("div");
		schools.setAttribute("id", "schools");
		schools.className = "menuButton";
		schools.appendChild(document.createTextNode("Schools"));
		
		var menu = document.createElement("div");
		menu.className = "menuList hidden";
		var linkTitles = ["Elementary Schools","Middle School","High School","Child Care/Montessori","Board of Education"];
		var linkTags = ["elementary","middle","high","montessori","admin"];
		var menuItem = [];
		for (var i = 0; i < linkTitles.length; i++) {
			menuItem[i] = document.createElement("a");
			menuItem[i].appendChild(document.createTextNode(linkTitles[i]));
			menuItem[i]._tag = linkTags[i];
			menu.appendChild(menuItem[i]);
		}
		schools._menu = menu;
		schools.appendChild(schools._menu);
		
		var recreation = document.createElement("div");
		recreation.setAttribute("id", "recreation");
		recreation.className = "menuButton";
		recreation.appendChild(document.createTextNode("Recreation"));
		
		var menu = document.createElement("div");
		menu.className = "menuList hidden";
		var linkTitles = ["Community Centers", "Pools", "Parks", "Trails"];
		var linkTags = ["comcenter","pool","park","trail"];
		var menuItem = [];
		for (var i = 0; i < linkTitles.length; i++) {
			menuItem[i] = document.createElement("a");
			menuItem[i].appendChild(document.createTextNode(linkTitles[i]));
			menu.appendChild(menuItem[i]);
			menuItem[i]._tag = linkTags[i];
		}
		recreation._menu = menu;
		recreation.appendChild(recreation._menu);		
		
		var misc = document.createElement("div");
		misc.setAttribute("id", "misc");
		misc.className = "menuButton";
		misc.appendChild(document.createTextNode("Misc"));
		
		var menu = document.createElement("div");
		menu.className = "menuList hidden";
		var linkTitles = ["Commuter Lots", "Train Station", "Boat Launches", "Voting Locations", "Show All"];
		var linkTags = ["parking", "train", "boat", "vote", "all"];
		var menuItem = [];
		for (var i = 0; i < linkTitles.length; i++) {
			menuItem[i] = document.createElement("a");
			menuItem[i].appendChild(document.createTextNode(linkTitles[i]));
			menuItem[i]._tag = linkTags[i];
			menu.appendChild(menuItem[i]);
		}
		misc._menu = menu;
		misc.appendChild(misc._menu);
		
		Gmap.navBar._buttons = [townFacilities, schools, recreation, misc];
		for (i = 0; i < Gmap.navBar._buttons.length; i++)
		{
			Gmap.navBar.appendChild(Gmap.navBar._buttons[i]);
		};
		
		Gmap.navContainer.removeChild(Gmap.loading);
		Gmap.navContainer.appendChild(Gmap.navBar);
		
	  for (var i in Gmap.navBar._buttons) {
			Core.addEventListener(Gmap.navBar._buttons[i], "mouseover", Gmap.navHoverListener);
			Core.addEventListener(Gmap.navBar._buttons[i], "mouseout", Gmap.navUnhoverListener);
			
			var buttons = Gmap.navBar._buttons[i].getElementsByTagName("a");
			for (var j = 0; j < buttons.length; j++) {
				Core.addEventListener(buttons[j], "click", Gmap.navClickListener);
			}
			
		}
	},
	
	addressList: function(data, marker)
	{
		var info = [];
		info.push(data.getAttribute("name"));
		info.push(address = data.getAttribute("addr"));
		info.push(data.getAttribute("phone"));
		
		var addr_container = document.getElementById("map_address");
		var location = document.createElement("div");
		location.className = "address";
		
		var title = document.createElement("p");
		title.appendChild(document.createTextNode(info[0]));
		title.className = "title";
		var addr = document.createElement("p");
		addr.appendChild(document.createTextNode(info[1]));
		addr.className = "addr";
		var phonenum = document.createElement("p");
		phonenum.appendChild(document.createTextNode(info[2]));
		phonenum.className = "phone";
		var form = document.createElement("p");
		form.className = "addrDirForm";
		form.innerHTML = marker.form;
		location.appendChild(title);
		location.appendChild(addr);
		location.appendChild(phonenum);
		location.appendChild(form);
		
		Gmap.addrContainer.appendChild(location);
		marker._address = location;
		
	},
	
	calcMax: function(orig, newer)
	{
	  if (orig < newer)
		{
		  return newer;
		}
		else
		{
			return orig;
		}
	},
	
	calcMin: function(orig, newer)
	{
		if (orig > newer)
		{
			return newer;
		}
		else
		{
			return orig;
		}
	},
	
	image: function(img)
  {
		if(img)
		{
			return "<img src='" + img + "' width='180' height='150'/><br />";
		}
		else
		{
			return '';
		}
	},
	
	iconSelect: function (icon)
	{
		if (icon == 'townhall') {
			return '/images/gmap/townhall.png';
		} else if (icon == 'recreation') {
			return '/images/gmap/recreation.png';
		} else if (icon == 'pworks') {
			return '/images/gmap/publicworks.png';
		} else if (icon == 'landfill') {
			return '/images/gmap/landfill.png';
		} else if (icon == 'library') {
			return '/images/gmap/library.png';
		} else if (icon == 'police') {
			return '/images/gmap/police.png';
		} else if (icon == 'fire') {
			return '/images/gmap/fire.png';
		} else if (icon == 'education') {
			return '/images/gmap/education.png';
		} else if (icon == 'pool') {
			return '/images/gmap/pool.png';
		} else if (icon == 'boat') {
			return '/images/gmap/boat.png';
		} else if (icon == 'train') {
			return '/images/gmap/train.png';
		} else if (icon == 'park') {
			return '/images/gmap/park.png';
		} else if (icon == 'parking') {
			return '/images/gmap/parking.png';
		} else if (icon == 'trail') {
			return '/images/gmap/trail.png';
		} else {
		  return null;
		};
	},
	
	closeAll: function ()
	{
		for (var i = 0; i < Gmap.marker.length; i++){	Gmap.marker[i].infowindow.close(); }
	},
	
	closeClickListener: function (element)
	{
	  google.maps.event.addListener(element, 'click', function(){ Gmap.closeAll(); });
	},
	
	clickListener: function (marker)
	{
	  google.maps.event.addListener(marker, 'click', function() {
		  Gmap.closeAll();
	    marker.infowindow.open(Gmap.map,marker);
			Gmap.infowindow = true;
	  });
	}, 
	
	navHoverListener: function ()
	{
		var e = this.firstChild;
		while (e.nodeType != 1) {
			e = e.nextSibling;
		}
		Core.removeClass(e, "hidden");
		Core.addClass(this, "hover");
	},
	
	navUnhoverListener: function ()
	{
		var e = this.firstChild;
		while (e.nodeType != 1) {
			e = e.nextSibling;
		}
		Core.addClass(e, "hidden");
		Core.removeClass(this, "hover");
	},
	
	navClickListener: function ()
	{
		Core.addClass(this.parentNode, "hidden");
		Gmap.createMarkers(this._tag);
	}
	
};

Core.start(Gmap);

