//<![CDATA[		   
/*----------------------------------------------------------------------------\
|                                  Climate Maps 1.0                           |
|-----------------------------------------------------------------------------|
|                          Created by Max Sylvester                           |
|                        (http://www.energymatters.com.au)                    |
|-----------------------------------------------------------------------------|
| Climate data with google maps                                               |
|-----------------------------------------------------------------------------|
|                      Copyright (c) 2007 Energy = MC2 Pty Ltd                |
|- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -|
| please Contact Energy Matters if you wish to use this script                 |
|-----------------------------------------------------------------------------|
| Created 2006-09-24                                                          |
\----------------------------------------------------------------------------*/

		var map;
    	var geocoder;
		var the_address;
		var text_address;
		var station_id;
		var station_marker_id;
		var show_data = false;

function onLoad(town) {
  map = new GMap(document.getElementById("div_map"));
  geocoder = new GClientGeocoder();
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  map.setCenter(new GLatLng(-37.97,145.1), 8);
  if(town != 0) {
	geocoder.getLocations(town, addAddressToMap);
  } else {
	geocoder.getLocations("Sydney, Australia", addAddressToMap);  
  }
GEvent.addListener(map, "moveend", function() {
	getMarkers(map.getBounds());
	});
	
GEvent.addListener(map, "zoomend", function() {
	remove_overlays();
	//getMarkers(map.getBounds());
	});
GEvent.addListener(map, "click", function(overlay, point) {
	if (overlay){
		show_data = false;
		overlay.openInfoWindowHtml(overlay.infowindow);
		get_monthly_data(overlay.db_id);
	} else if (point) {
		  
	}
	});
  
}
	
function remove_overlays() {
	map.clearOverlays();
	if (the_address) {
		map.addOverlay(the_address);
	}
}
	
function addAddressToMap(response) {
  map.clearOverlays();
  	
	var homeIcon = new GIcon(G_DEFAULT_ICON);
	homeIcon.image = "http://www.energymatters.com.au/calc/address.png";
	homeIcon.iconSize = new GSize(32, 32);
	markerOptions = { icon:homeIcon };
	
  if (!response || response.Status.code != 200) {
	alert("Sorry, we were unable to find that address. Please check the spelling, or try being less specific. Eg. 'South Melbourne, Australia' instead of '122 Bank St, South Melbourne, 3205, VIC, Australia'");
  } else {
    show_data = true;
	place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]);
	marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);	
	marker.infowindow = place.address + '<br>' +
	  '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode;//+ '<br> If this isn\'t the place you were expecting, try adding your country or state to the search' ;	
	//getMarkers(map.getBounds());
	marker.openInfoWindow(place.address + '<br>' +
	  '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode+ '<br>Click on the  red markers <br>to obtain weather information.<br><br>If this isn\'t the place you were<br> expecting, try including your <br>country or state in the search') ;	
		map.setCenter(new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]), 8);
  }
  the_address = marker;
  text_address = place.address;
}

function showLocation() {
  var address = document.forms[0].q.value;
  geocoder.getLocations(address, addAddressToMap);
}

function get_monthly_data(marker_id) {
		var urlstr="includes/getdata.php?id="+marker_id+"&address="+text_address;
		var request = GXmlHttp.create();
		request.open('GET', urlstr , true);	// request XML from PHP with AJAX call
		request.onreadystatechange = function () {
			if (request.readyState == 4) {
				var xmlDoc = request.responseXML;
				climates = xmlDoc.documentElement.getElementsByTagName("climate");
				//var polyOptions = {geodesic:true};
				if (climates.length == 1){						
						var solar = [climates[0].getAttribute("solar_jan"), climates[0].getAttribute("solar_feb"), climates[0].getAttribute("solar_mar"), climates[0].getAttribute("solar_apr"), climates[0].getAttribute("solar_may"), climates[0].getAttribute("solar_jun"), climates[0].getAttribute("solar_jul"), climates[0].getAttribute("solar_aug"), climates[0].getAttribute("solar_sep"), climates[0].getAttribute("solar_oct"), climates[0].getAttribute("solar_nov"), climates[0].getAttribute("solar_dec")];
						var wind = [climates[0].getAttribute("wind_jan"), climates[0].getAttribute("wind_feb"), climates[0].getAttribute("wind_mar"), climates[0].getAttribute("wind_apr"), climates[0].getAttribute("wind_may"), climates[0].getAttribute("wind_jun"), climates[0].getAttribute("wind_jul"), climates[0].getAttribute("wind_aug"), climates[0].getAttribute("wind_sep"), climates[0].getAttribute("wind_oct"), climates[0].getAttribute("wind_nov"), climates[0].getAttribute("wind_dec")];
						var air = [climates[0].getAttribute("air_jan"), climates[0].getAttribute("air_feb"), climates[0].getAttribute("air_mar"), climates[0].getAttribute("air_apr"), climates[0].getAttribute("air_may"), climates[0].getAttribute("air_jun"), climates[0].getAttribute("air_jul"), climates[0].getAttribute("air_aug"), climates[0].getAttribute("air_sep"), climates[0].getAttribute("air_oct"), climates[0].getAttribute("air_nov"), climates[0].getAttribute("air_dec")];
						var EarthT = [climates[0].getAttribute("EarthT_jan"), climates[0].getAttribute("EarthT_feb"), climates[0].getAttribute("EarthT_mar"), climates[0].getAttribute("EarthT_apr"), climates[0].getAttribute("EarthT_may"), climates[0].getAttribute("EarthT_jun"), climates[0].getAttribute("EarthT_jul"), climates[0].getAttribute("EarthT_aug"), climates[0].getAttribute("EarthT_sep"), climates[0].getAttribute("EarthT_oct"), climates[0].getAttribute("EarthT_nov"), climates[0].getAttribute("EarthT_dec")];
						var hum = [climates[0].getAttribute("hum_jan"), climates[0].getAttribute("hum_feb"), climates[0].getAttribute("hum_mar"), climates[0].getAttribute("hum_apr"), climates[0].getAttribute("hum_may"), climates[0].getAttribute("hum_jun"), climates[0].getAttribute("hum_jul"), climates[0].getAttribute("hum_aug"), climates[0].getAttribute("hum_sep"), climates[0].getAttribute("hum_oct"), climates[0].getAttribute("hum_nov"), climates[0].getAttribute("hum_dec")];
						var press = [climates[0].getAttribute("press_jan"), climates[0].getAttribute("press_feb"), climates[0].getAttribute("press_mar"), climates[0].getAttribute("press_apr"), climates[0].getAttribute("press_may"), climates[0].getAttribute("press_jun"), climates[0].getAttribute("press_jul"), climates[0].getAttribute("press_aug"), climates[0].getAttribute("press_sep"), climates[0].getAttribute("press_oct"), climates[0].getAttribute("press_nov"), climates[0].getAttribute("press_dec")];				
										
						document.getElementById("distance").innerHTML = 
				"<strong>Current weather station:</strong>" + climates[0].getAttribute("name") + "(" + Math.round(the_address.getLatLng().distanceFrom(new GLatLng(climates[0].getAttribute("lat"),climates[0].getAttribute("lng")))/1000) + " km)";
				document.getElementById("message").innerHTML = "";
				draw(solar,wind,air,EarthT, hum, press);
				} 
				
			}
		} 
		request.send(null);
	return solar;
}
	
	
function get_max(arr) {
	if (arr == 0) return undefined;
	var n = Number(arr[0]);
	for (var i=1; i<arr.length; i++) {n = Math.max(n, arr[i])};
	return n;
}

function get_min(arr) {
	if (arr == 0) return undefined;
	var n = Number(arr[0]);
	for (var i=1; i<arr.length; i++) {n = Math.min(n, arr[i])};
	return n;
}

function draw(sol,wind,air,EarthT, humidity, press ) { //
	var solar = new Chart(document.getElementById('solar'));
	var temp = new Chart(document.getElementById('temp'));
	var pressure = new Chart(document.getElementById('pressure'));
	var height = sol.concat(wind);
		
		solar.setDefaultType(CHART_AREA );
		solar.setGridDensity(12, 5);
		solar.setVerticalRange(0, parseInt(get_max(height))+2);
		solar.setHorizontalLabels(['jan', 'feb', 'mar', 'apr', 'may','jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']);
		solar.add('Solar kW/m2/d',     '#A5A5FF', sol);
		solar.add('Wind m/s', 'red', wind, CHART_LINE);
		solar.draw();

		height = air.concat(EarthT);	
		temp.setDefaultType(CHART_AREA );
		temp.setGridDensity(12, 5);
		temp.setVerticalRange(parseInt(get_min(height))-2, parseInt(get_max(height))+2);
		temp.setHorizontalLabels(['jan', 'feb', 'mar', 'apr', 'may','jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']);
		temp.add('air temp C',     '#A5A5FF', air);
		temp.add('ground temp C', 'red', EarthT, CHART_LINE);
		temp.draw();
		
		height = press.concat(humidity);	
		pressure.setDefaultType(CHART_AREA );
		pressure.setGridDensity(12, 5);
		pressure.setVerticalRange(0, parseInt(get_max(height)));
		pressure.setHorizontalLabels(['jan', 'feb', 'mar', 'apr', 'may','jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']);
		pressure.add('Humidity %',     '#A5A5FF', humidity);
		pressure.add('Pressure kPa', 'red', press, CHART_LINE);
		pressure.draw();		

}

function getMarkers(bounds){
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var leftMAX = southWest.lng();
	var bottomMAX = southWest.lat();
	var topMAX = northEast.lat();
	var rightMAX = northEast.lng();
	var station_name = false;
	var distance = false;
	var urlstr="includes/read.php?left="+leftMAX+"&right="+rightMAX+"&top="+topMAX+"&bottom="+bottomMAX;
	var request = GXmlHttp.create();
	request.open('GET', urlstr , true);	// request XML from PHP with AJAX call
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			locations = xmlDoc.documentElement.getElementsByTagName("location");
			markers = [];
			lines = [];
			var n = 100000;	
			var old_n = 100000;		
			//var polyOptions = {geodesic:true};
			if (locations.length){
				for (var i = 0; i < locations.length; i++) { // cycle thru locations
					markers[i] = new GMarker(new GLatLng(locations[i].getAttribute("lat"),locations[i].getAttribute("lng")));
					// Add attributes to the marker so we can poll them later.
					// When clicked, an overlay will have these properties.
					markers[i].infowindow = "<strong>"+locations[i].getAttribute("name") + "</strong><br>" + 
					"Elevation: " + locations[i].getAttribute("elevation")+ " m<br><br>" +
					"<strong>Climate Averages:</strong><br>" + 
					"Solar Irradiation: "+ locations[i].getAttribute("solar") + " kW/m<sup>2</sup>/d<br>" + 
					"Wind Speed: "+ locations[i].getAttribute("wind") + " m/s <br>" + 
					"Humidity: "+ locations[i].getAttribute("humidity")+ " %<br>" +
					"Earth Temp: "+ locations[i].getAttribute("earth")+ " &deg;C<br>" +
					"Air Temp: "+ locations[i].getAttribute("air")+ " &deg;C<br>" +
					"Pressure: "+ locations[i].getAttribute("pressure")+ " kPa<br>" +
					Math.round(the_address.getLatLng().distanceFrom(markers[i].getLatLng())/1000) +" km"
					;
					old_n = n;
					n = Math.min(n, the_address.getLatLng().distanceFrom(markers[i].getLatLng()));
					if (old_n > n) {
						station_id = locations[i].getAttribute("id");	
						station_marker_id = i;
						station_name = locations[i].getAttribute("name");
						distance = Math.round(the_address.getLatLng().distanceFrom(markers[i].getLatLng())/1000);
					}
					markers[i].markerindex = i;
					markers[i].db_id = locations[i].getAttribute("id");
					map.addOverlay(markers[i]);
				}
				if (show_data ) {
					get_monthly_data(station_id);				
				}
				if (distance) {
				document.getElementById("message").innerHTML = 
				"<strong>Nearest weather station:</strong>" + station_name + "(" + distance + " km)<br>";
				} else {
					document.getElementById("message").innerHTML = "";
				}
				;
			}
		}
	}
	request.send(null);
}
	
		//]]>