var map;

var geoXml_1; 
var geoXml_2; 

// Empty GLatLngBounds object, used to determine initial Centre and Zoom   
var bounds = new GLatLngBounds();

var deselectCurrent = function() {};

// Custom control for legend
function MyPane() {}
MyPane.prototype = new GControl;
MyPane.prototype.initialize = function(map) {
  var me = this;
  me.panel = document.createElement("div");
  me.panel.id = 'map-legend';
//  me.panel.innerHTML = '<table border="0" cellspacing="0" cellpadding="5"><tr><td><div style="width: 20px; height: 20px; background-color: #1ac64d;"></div></td><td>AMLRNRMB Boundary</td></tr><tr><td><div style="width: 20px; height: 2px; background-color: #ff1500;"></div></td><td>River Catchments</td></tr></table>';
  me.panel.innerHTML = '<table border="0" cellspacing="0" cellpadding="5"><tr><td><div style="width: 20px; height: 20px; background-color: #1ac64d;"></div></td><td>AMLRNRMB Boundary</td></tr></table>';
  map.getContainer().appendChild(me.panel);
  return me.panel;
};

MyPane.prototype.getDefaultPosition = function() {
  return new GControlPosition(
      G_ANCHOR_TOP_RIGHT, new GSize(10, 50));
      //Should be _ and not &#95;
};

MyPane.prototype.getPanel = function() {
  return me.panel;
}	

function initializePoint(pointData) {
	
	// Set Icon
	
	var icon = new GIcon();
	icon.image = "/www/img/map/orb-icon.png";
	icon.iconSize = new GSize(18, 24);
	icon.iconAnchor = new GPoint(13, 35);
	icon.infoWindowAnchor = new GPoint(13, 0);
	
	// Set Marker
	var point = new GLatLng(pointData.latitude, pointData.longitude);
	var marker = new GMarker(point, icon);
	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";
	listItemLink.innerHTML = '<strong>' + pointData.site_name + ' </strong><span>' + pointData.site_no + '</span>';
	
	// Define content for the Info Window Tabs
	
	if (loadOverlay == 'filter') {
		
		// Check if we should include Monthly Flow and Monthly Load links (if data exist)
		if (pointData.flow_mly == 'available')
		{
			var flow_mly = "<a title='Flow - Monthly YearToDate' class='thickbox' href='/sites/gd/flow_mly/" + pointData.id + "'><img src='/www/img/map/monthly-flow.png' border='0' /></a>";
		}
		else
		{
			var flow_mly = "";
		}
		
		if (pointData.wq_mly == 'available')
		{
			var wq_mly = "&nbsp;<a title='Water Quality - Monthly Results YearToDate' class='thickbox' href='/sites/gd/wq_mly/" + pointData.id + "'><img src='/www/img/map/monthly-loads.png' border='0' /></a>";
		}
		else
		{
			var wq_mly = "";
		}
			
		var infoTabContent = '<strong>' + pointData.site_name + '</strong><br/><span>' + 
		pointData.site_no + '</span><br/><br/>';
		/*
		// For the basin summary
		var infoTabContent = '<strong>' + pointData.site_name + '</strong><br/><span>' + 
								pointData.site_no + '</span><br/><br/>Totals to date from ' + pointData.from + '<br/><br/>';
		if (pointData.flow_value != 'Insufficient Data') {
			infoTabContent += '<strong>Flow Volume</strong>: ' + pointData.flow_value + '<br/>';
		}
		if (pointData.rainfall_value != 'Insufficient Data') {
			infoTabContent += '<strong>Rainfall</strong>: ' + pointData.rainfall_value + '<br/>';
		}
		if (pointData.tds_value != 'Insufficient Data') {
			infoTabContent += '<strong>TDS</strong>: ' + pointData.tds_value + '<br/>';
		}
		if (pointData.totp_value != 'Insufficient Data') {
			infoTabContent += '<strong>Tot P</strong>: ' + pointData.totp_value + '<br/>';
		}
		*/
		var infoTabs = [
		    new GInfoWindowTab('Overview', 
								infoTabContent + '<br/><span>' + flow_mly + wq_mly + '</span><br/><br/><span><a href="/sites/view/' + pointData.id + '"><img src="/www/img/map/view-site.png" border="0"/></a></span>')
		];
	}
	else
	{
		// For the main map
		var infoTabs = [
            new GInfoWindowTab('Overview', '<strong>' + pointData.site_name + ' </strong><br /><span>' + pointData.site_no + '</span><br /><br /><span><a href="/sites/view/' + pointData.id + '"><img src="/www/img/map/view-site.png" border="0" /></a></span>')
		];
	}
	
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		deselectCurrent = function() { listItem.className = ''; }
		marker.openInfoWindowTabsHtml(infoTabs, {
			selectedTab: 0,
			maxWidth: 300
		});
		map.panTo(point);
		return false;
	}

	GEvent.addListener(marker, 'click', focusPoint);	
	listItemLink.onclick = focusPoint;
	listItemLink.ondblclick = function() {window.location.href = "/sites/view/" + pointData.id;};

	document.getElementById('sidebar-list').appendChild(listItem);

	map.addOverlay(marker);
	
	// ==== Extent bounds to include point =====
    bounds.extend(point);

}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	var height = windowHeight() - document.getElementById('toolbar').offsetHeight;
	document.getElementById('map').style.height = height + 'px';
	document.getElementById('sidebar').style.height = height + 'px';
}

function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}

function init() {
	document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	handleResize();
	
	map = new GMap2(document.getElementById("map"));
	
	map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    // ==== It is necessary to make a setCenter call of some description before adding markers ====
    // ==== At this point we dont know the real values ====
    map.setCenter(new GLatLng(-35.024082,138.599739),9);
	
	// Loop through array of markers, initializing each one as a point on the map
	if (markers.length > 0) {
		
		// Define location of XML file(s) for map overlay
		
			// Load filter items
		if (loadOverlay == 'filter')
		{
			geoXml_1 = new GGeoXml("http://www.wdapp.com/www/xml/DWLBC_Basin.kmz");
			map.addOverlay(geoXml_1);
		} else {
			// Load default items
			map.addControl(new MyPane());
			
			geoXml_1 = new GGeoXml("http://www.wdapp.com/www/xml/DWLBC_Catchments.kmz");
			geoXml_2 = new GGeoXml("http://www.wdapp.com/www/xml/AMLRNRMB_Boundary.kmz");
			map.addOverlay(geoXml_1);
	 		map.addOverlay(geoXml_2);
		}
			
		for (id in markers) {
			initializePoint(markers[id]);
		}
	} else {
	// Otherwise, if the array is empty (no results) - display an appropriate message
		var listItem = document.createElement('li');
		listItem.innerHTML = '<p>Your search returned no results.</p>';
		document.getElementById('sidebar-list').appendChild(listItem);
	}
	
	// ===== Determine the zoom level from the bounds =====
    //map.setZoom(map.getBoundsZoomLevel(bounds));

    // ===== Determine the centre from the bounds ======
    // map.setCenter(bounds.getCenter());
	 
	 // Set Hybrid as default map type
	 map.setMapType(G_HYBRID_MAP); 
	 
}

window.onresize = handleResize;
