/**
 * @author Jim Battin of TR Mandigo & Company - jimbattin@trmandigo.com
 */

	// When a property from the table is clicked we jump to the map and open its info window
	function tableclick(i) {
			// Webkit Browser work-around:  Compensate for window.location.hash Bug
			    window.location.hash = "notcontent";
			    window.location.hash = "content";
				GEvent.trigger(gmarkers[i], "click");
				map.setZoom(16);
			}

	// Legend pin click function to show/hide viability/status markers
	function clickpin(category) {
			var thepin = document.getElementById('' + category + '');
			if(thepin.src != "http://www.trmandigo.com/static/mapicons/no.png") {
				thepin.src = "static/mapicons/no.png";
				hide(category);
			} else {
				switch(category) {
					case "complete":
						thepin.src="static/mapicons/darkgreen-small.png";
						break;
					case "under construction":
						thepin.src="static/mapicons/lightgreen-small.png";
						break;
					case "likely":
						thepin.src="static/mapicons/yellow-small.png";
						break;
					case "unlikely":
						thepin.src="static/mapicons/orange-small.png";
						break;
					case "cancelled":
						thepin.src="static/mapicons/red-small.png";
						break;
				}
				show(category);
			}
			
		}
		
		
		function createproptable() {
			var table_html = '';
			
			table_html = "<table id='proptable5'><tr><td><b>Property Name</b></td><td><b>Address</b></td><td><b>Status</b></td><td><b>Open Date</b></td></tr>";
			
			for (eachmarker in gmarkers) {
				table_html += '<tr><td><a href="javascript:tableclick(' + eachmarker + ')">' + gmarkers[eachmarker].data["name"] +
					"</a></td><td>" +
					gmarkers[eachmarker].data["address"].split(",", 1) +
					"</td><td>" +
					getstatus(gmarkers[eachmarker].data) +
					"</td><td>" +
					getopendate(gmarkers[eachmarker].data) +
					"</td>" +
					"</tr>";
				}
				table_html += "</table>";
				
				document.getElementById('proptable').innerHTML = table_html;
				

		}
	if (GBrowserIsCompatible()) {
		
		// Global Variable to store our markers' properties
		var gmarkers = [];

	
		// Hide Markers
		function hide(category){
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i].mycategory === category) {
					gmarkers[i].hide();
				}
			}
			map.closeInfoWindow();
		}
		
		// Show Markers
		function show(category) {
			for (var i = 0; i < gmarkers.length; i++) {
				if (gmarkers[i].mycategory == category) {
					gmarkers[i].show();
				}
			}
		}
		
		// Base Icon prep
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		// Legend Pane	
		function LegendPane() {}
		LegendPane.prototype = new GControl;
		LegendPane.prototype.initialize = function(map) {
			var me = this;
			me.panel = document.createElement("div");
			me.panel.style.width = "auto";
			me.panel.style.height = "auto";
			me.panel.style.padding = "4px 4px";
			me.panel.style.border = "1px solid black";
			me.panel.style.background = "white";
			me.panel.style.opacity = "0.75";
			me.panel.style.filter = "alpha(opacity=75)"; // IE7 opacity
			me.panel.style.fontSize = "0.9em";
			me.panel.innerHTML = "<center><b>Legend</b></center>\
					<a href='#content' onclick='clickpin(\"complete\")'><img src='static/mapicons/darkgreen-small.png' id='complete'> Completed</a><br />\
					<a href='#content' onclick='clickpin(\"under construction\")'><img src='static/mapicons/lightgreen-small.png' id='under construction'> Under Construction</a><br />\
					<a href='#content' onclick='clickpin(\"likely\")'><img src='static/mapicons/yellow-small.png' id='likely'> Likely</a><br />\
					<a href='#content' onclick='clickpin(\"unlikely\")'><img src='static/mapicons/orange-small.png' id='unlikely'> Unlikely</a><br />\
					<a href='#content' onclick='clickpin(\"cancelled\")'><img src='static/mapicons/red-small.png' id='cancelled'> Cancelled</a>";
			map.getContainer().appendChild(me.panel);
			return me.panel;
		};
		
		LegendPane.prototype.getDefaultPosition = function() {
			return new GControlPosition(
			G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
		};
		
		LegendPane.prototype.getPanel = function() {
			return me.panel;
		}
		
		// Tooltips
		function Tooltip(marker, text, padding){
			this.marker_ = marker;
			this.text_ = text;
			this.padding_ = padding;
		}

		Tooltip.prototype = new GOverlay();

		Tooltip.prototype.initialize = function(map){
			var div = document.createElement("div");
			div.appendChild(document.createTextNode(this.text_));
			div.className = 'tooltip';
			div.style.position = 'absolute';
			div.style.visibility = 'hidden';
			map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
			this.map_ = map;
			this.div_ = div;
		}
		
		Tooltip.prototype.remove = function(){
			this.div_.parentNode.removeChild(this.div_);
		}
		
		Tooltip.prototype.copy = function(){
			return new Tooltip(this.marker_,this.text_,this.padding_);
		}
		
		Tooltip.prototype.redraw = function(force){
			if (!force) return;
			var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
			var iconAnchor = this.marker_.getIcon().iconAnchor;
			var xPos = Math.round(markerPos.x - this.div_.clientWidth / 2);
			var yPos = markerPos.y - iconAnchor.y - this.div_.clientHeight - this.padding_;
			this.div_.style.top = yPos + 'px';
			this.div_.style.left = xPos + 'px';
		}
		
		Tooltip.prototype.show = function(){
			this.div_.style.visibility = 'visible';
		}
		
		Tooltip.prototype.hide = function(){
			this.div_.style.visibility = 'hidden';
		}
		
		// Create and Center a Map
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(41.8924060, -87.6319796), 13);
		// Map Controls
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		// map.enableScrollWheelZoom();
		map.addControl(new LegendPane);
		
		// Gets opendate
		function getopendate(data) {
			switch(data["opendateknown"]) {
				case "NA":
					return "Unknown";
					break;
				case "YE":
					return data["opendate"].substr(0,4) + " (Estimate)";
					break;
				case "MY":
					return data["opendate"].substr(0,7) + " (Estimate)";
					break;
				case "DA":
					return data["opendate"];
					break;
			}
		}
		
		// Gets Status
		function getstatus(data) {
			switch(data["status"]) {
				case "RC":
					return "Recently Completed";
					break;
				case "UC":
					return "Under Construction";
					break;
				case "AN":
					return "Announced";
					break;
				case "PL":
					return "Planning";
					break;
				case "ID":
					return "In Discussion";
					break;
				case "CA":
					return "Cancelled";
					break;
				case "DE":
					return "Delayed"
					break;
					
				return "Unknown"
					
			}
		}
		
		// Gets Viability
		function getviability(data) {
			if(data["status"] == "CA") {
				return "Cancelled";
			}
			switch(data["viability"]) {
				case "CP":
					if(data["status"] == "RC") {
						return "Recently Completed";
					} else {
						return "In Progress";
					}
					break;
				case "SL":
					return "Likely";
					break;
				case "LL":
					return "Unlikely";
					break;
				case "UL":
					return "Cancelled";
					break;
			}
		}
		
		// Marker Creation
		function createMarker(point, data) {
			var codedicon = new GIcon(baseIcon);
			var category = ''
			switch(data["viability"]) {
				case "CP":
					if(data["status"] == "RC") {
						codedicon.image = "static/mapicons/darkgreen.png";
						category = "complete"
					} else {
						codedicon.image = "static/mapicons/lightgreen.png";
						category = "under construction"
					}
					break;
				
				case "SL":
					codedicon.image = "static/mapicons/yellow.png";
					category = "likely"
					break;
				case "LL":
					codedicon.image = "static/mapicons/orange.png";
					category = "unlikely"
					break;	
				case "UL":
					codedicon.image = "static/mapicons/red.png";
					category = "cancelled"
					break;
			}
			
			markerOptions = { icon:codedicon };
			var marker = new GMarker(point, markerOptions);
			marker.mycategory = category
			
			var tooltip = new Tooltip(marker,data["name"],2);
			marker.tooltip = tooltip;
			GEvent.addListener(marker, "click", function() {
				information = "<div class='infowin'> <b>Hotel: </b>" + data["name"] + "<br /><b>Developer: </b>" + data["developer"] + 
					"<br /><b>Rooms: </b>" + data["rooms"] + "<br /><b>Address: </b>" + data["address"] +
					"<br /><b>Status: </b>" + getstatus(data) + "<br /><b>Viability: </b>" + getviability(data) +
					"<br /><b>Open Date: </b>" + getopendate(data) + "<br /><b>Hotel Style: </b>" + data["hoteltype"] +
					"<br /><b>Position: </b>" + data["position"] + "<br /><b>Notes: </b>" + data["notes"] + "</div>";
				marker.openInfoWindowHtml(information);
			});
			GEvent.addListener(marker,'mouseover', function() {
				this.tooltip.show();
			});
			
			GEvent.addListener(marker,'mouseout', function() {
				this.tooltip.hide();
			});

			map.addOverlay(tooltip);
			marker.data = data;
			gmarkers.push(marker);
			return marker;
		}
		
		// Request a JSON file, parse it, and place icons on the map canvas
		var jsonurl="propdata.json";
  		var request = GXmlHttp.create();
  		request.open("GET", jsonurl, true);
  		request.onreadystatechange = function(){
			if (request.readyState == 4) {
				if (request.status == 200) {
					var output = JSON.parse(request.responseText);
					for (hotel in output) {
						var lat = parseFloat(output[hotel]["fields"]["lat"]);
						var lng = parseFloat(output[hotel]["fields"]["lng"]);
						var point = new GLatLng(lat,lng);
						map.addOverlay(createMarker(point, output[hotel]["fields"]));
					}
					createproptable();
				}
				else {
					alert("Failed to load proposed properties.");
				}
			}
		}
		request.send(null);
		
	}
