<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Wunderground Weather" 
	height="300" 
	author="Weather Underground, Inc." 
	author_email="support@wunderground.com" 
	author_affiliation="Weather Underground, Inc." 
	author_location="San Francisco, CA" 
	description="The official Weather Underground gadget.  Weather station data from wunderground.com presented on a Google map."
	scaling="true"
	thumbnail="http://icons.wunderground.com/graphics/gmod_thumb.png"
	screenshot="http://icons.wunderground.com/graphics/gmod_screenshot2.png"
	title_url="http://www.wunderground.com"/>
<UserPref name="loc" display_name="Location" />
<UserPref name="zoom" display_name="Zoom" default_value="City" datatype="enum">
  <EnumValue value="City" />
  <EnumValue value="Metro" />
  <EnumValue value="Region" />
  <EnumValue value="Nation" />
</UserPref>
<UserPref name="units" display_name="Units" default_value="English" datatype="enum">
  <EnumValue value="English" />
  <EnumValue value="Metric" />
</UserPref>
  <Content type="html"><![CDATA[ 

<script src="http://maps.google.com/maps?file=api&amp;v=2.s" type="text/javascript"></script>

<div id="premap" style="width:100%; background-color: white; font-size: 12px;"></div>
<div id="map" style="width: 100%; height: 100%;"></div>


<script type="text/javascript">
var infowindowinprogress=false;
var ignoremoveend=false;
var iconmode='tw';
var units='english';
var current_marker;
var googlemap;

var m;

 _IG_RegisterOnloadHandler(function() { LoadMap(); }); 

GMap2.prototype.addOverlays=function(a){
	for (i=0;i<a.length;i++) {
		this.addOverlay(a[i]);
	}
};

// function logoCtrl() {}
// logoCtrl.prototype = new GControl();
// logoCtrl.prototype.initialize = function(){
//   var container = document.createElement("div");
//   var image = document.createElement("img");
//   container.appendChild(image);
//   container.setAttribute("id","wunderlogo");
//   container.setAttribute("style","cursor:hand;");
//   image.src = "http://icons.wunderground.com/graphics/wunderTransparent.gif";
//   GEvent.addDomListener(container, "click", function() {
//     //alert('clicked link');
//   } );
//   googlemap.getContainer().appendChild(container);
//   return container;
// }
// logoCtrl.prototype.getDefaultPosition = function() {
//   return new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(0,0));
// }

function lookupWindString(n) {
	var s="-";

	if (n > 360) n = n%360;

	if (n >= 0      && n < 11.25 ) s="N";
	else if (n >= 11.25  && n < 33.75 ) s="NNE";
	else if (n >= 33.75  && n < 56.25 ) s="NE";
	else if (n >= 67.5   && n < 78.75 ) s="ENE";
	else if (n >= 78.75  && n < 101.25) s="E";
	else if (n >= 101.25 && n < 123.75) s="ESE";
	else if (n >= 123.75 && n < 146.25) s="SE";
	else if (n >= 146.2  && n < 168.75) s="SSE";
	else if (n >= 168.75 && n < 191.25) s="S";
	else if (n >= 191.25 && n < 213.75) s="SSW";
	else if (n >= 213.75 && n < 236.25) s="SW";
	else if (n >= 236.25 && n < 258.75) s="WSW";
	else if (n >= 258.75 && n < 281.25) s="W";
	else if (n >= 281.25 && n < 303.75) s="WNW";
	else if (n >= 303.75 && n < 326.25) s="NW";
	else if (n >= 326.25 && n < 348.75) s="NNW";
	else if (n >= 348.75) s="N";

	return s;
}

function convertTempIntoUnits(u,t) {
	if (t =='-999' || t =='-9999') return '-';
	if (u=='both' || u=='english') return t;
	return parseInt((t-32)/1.8);
}

function convertWindIntoUnits(u,w) {
	var m = w/2.237*3.6;
	if (u=='metric')
		return parseInt(m);
	else
		return w;
}

function  convertPressureIntoUnits(u,p) {
	if (u=='metric')
		return parseInt(p* 33.86);
	else
		return p;
}

function convertRainIntoUnits(u,r) {
	if (u=='metric')
		return parseInt(r*2.54*10)/10.0;
	else
		return r;
}

function LoadMap() {
	var lat = 37.8; 
	var lon = -122.4; 
	var zoom = 6;

	document.getElementById("map").style.height = "300px";
	document.getElementById("map").innerHTML = "Loading &hellip;";

	var prefs = new _IG_Prefs(__MODULE_ID__);

	var zoomPref = prefs.getString("zoom");
	if (zoomPref == "City")
		zoom = 11;
	else if (zoomPref == "Metro")
		zoom = 9;
	else if (zoomPref == "Region")
		zoom = 6;
	else if (zoomPref == "Nation")
		zoom = 3;

	unitsPref = prefs.getString("units");
	if (unitsPref == "Metric")  {
		units = 'metric';
	} else {
		units = 'english';
	}

	// YAZ 20090612 - the 'location' userpref data type has been deprecated, do a geocoder lookup instead
	var defaultPoint = new GLatLng(lat, lon);
	var geocoder = new GClientGeocoder();
	var loc = prefs.getString("loc");
	if (loc && loc.length > 0) {
		// lookup the location of the pref
		geocoder.getLatLng(loc, function(point) {
			if (point) {
				ShowMap(point, zoom);
			} else {
				document.getElementById("premap").innerHTML = "<div style='margin:5px;font-weight: bold; color: #333;'>Could not find your location</div>";
				ShowMap(defaultPoint, zoom);
			}
		});
	}
	else {
		// no pref
		document.getElementById("premap").innerHTML = "<div style='margin:5px;font-weight: bold; color: #333;'>Please enter a location in the gadget's settings.</div>";
		ShowMap(defaultPoint, zoom);
	}
}

function ShowMap(point, zoom) {
	googlemap = new GMap2(document.getElementById("map"));
	googlemap.addControl(new GSmallMapControl());
	//googlemap.addControl(new GMapTypeControl());
	//googlemap.addControl(new logoCtrl());
	googlemap.setCenter(point, zoom);

	GEvent.addListener(googlemap, "moveend", function() { if (ignoremoveend==true) ignoremoveend=false; else  DoMap(googlemap);});
	GEvent.addListener(googlemap, "movestart", function() { if (infowindowinprogress==true) ignoremoveend=true;});
	GEvent.addListener(googlemap, "infowindowopen", function() {  infowindowinprogress=false;});

	DoMap(googlemap);
}


function createMarker(point, html, html_forecast, mode, tu,t, wsu,ws, wd, tdu,td, h, ru,r, wx) {

        var icon = new GIcon();
        icon.iconSize = new GSize(64, 64);
        icon.shadowSize = new GSize(64, 64);
        icon.iconAnchor = new GPoint(32, 32);
        icon.infoWindowAnchor = new GPoint(32,32);
        icon.infoShadowAnchor = new GPoint(32,32);
        icon.image = "http://stationicon.wunderground.com/cgi-bin/gmapicon?mode=" + mode + "&t=" + t +"&tu="+tu + "&ws=" + ws +"&wsu="+wsu + "&wd=" + wd + "&td="+td+ "&tdu="+tdu+"&h="+h+"&r="+r +"&ru="+ru+ "&wx=" + wx +"&format=.png";
        icon.shadow= "http://stationicon.wunderground.com/gmapshadow.png";
        icon.imageMap = new Array(22,22,38,22,38,38,22,38,22,22);
        icon.transparent= "http://stationicon.wunderground.com/gmapicon.png";
        var marker = new GMarker(point, icon);
        marker.myclickfunction= function() { current_marker = marker; infowindowinprogress=true;
                                        ignoremoveend=true; marker.html=html; marker.html_forecast=html_forecast; marker.openInfoWindowHtml(html, {maxWidth: 150}); };
        GEvent.addListener(marker, "click", marker.myclickfunction);

        return marker;
}



function DoMap(map) {

	
	//var bounds = map.getBoundsLatLng();
	
	var bounds = map.getBounds();

  var southwest = bounds.getSouthWest();
  var northeast = bounds.getNorthEast();
 
 	bounds.maxY = northeast.lat();
  bounds.minY = southwest.lat();
  bounds.maxX = northeast.lng();
  bounds.minX = southwest.lng();
	
	var frag='http://stationdata.wunderground.com/cgi-bin/stationdata?maxlat='+bounds.maxY+'&minlat='+bounds.minY+'&maxlon='+ bounds.maxX+'&minlon='+ bounds.minX +'&iframe=1&module=1&maxage=3600';

	// default cache is 1 hour, now changed to 2 mins
	// although it is unlikely that the exact same request will come in twice
	_IG_FetchContent(frag, function (responseText) {
		eval(responseText);
	}, { refreshInterval: 120 });
}




function MapCallback(weatherStations) {
	
				var numStations = weatherStations.length;

        var map = googlemap;
        //var bounds = map.getBoundsLatLng();

        var now = new Date();
        var year = now.getYear() + 1900;
        var month = now.getMonth();
        var day = now.getDate();

        if (!weatherStations || !numStations) {
                return;
        }
        var markers = new Array(numStations);
        var html = new Array(numStations);
				var html_forecast = new Array(numStations);

				m = new Array( numStations );

        //  clear the overlays at the last possible moment so we don't have as much of a flash
        map.clearOverlays(m);

				for (i=0; i<numStations; i++) {

					var lat = parseFloat(weatherStations[i]['lat']).toFixed(5);
					var lon = parseFloat(weatherStations[i]['lon']).toFixed(5);
					var id = weatherStations[i]['id'];

					var neighborhood = weatherStations[i]['neighborhood'];
					var adm1 = weatherStations[i]['adm1'];
					var name;
					var type = weatherStations[i]['type'];
					var weather = "";
					var histlink = "http://www.wunderground.com";
					if(type != 'PWS') {
						name = weatherStations[i]['name'];
						if(weatherStations[i]['weather'] == '' || !weatherStations[i]['weather']) {
							weather = '';
						} else {
							weather = weatherStations[i]['weather'];
						}
						histlink += "/history/airport/" + id + "/" + year + "/" + (month+1) + "/" + day + "/DailyHistory.html";
					} else {
						if(neighborhood == '' || !neighborhood) {
							name = adm1;
						} else {
							name = neighborhood;
						}
						histlink += "/weatherstation/WXDailyHistory.asp?ID=" + id;
					}

					// for if we don't know
					var NA = '<span style="color: #555;">N/A</span>';

					// temperature
					var tempf = weatherStations[i]['tempf'];
					var temp = convertTempIntoUnits(units,tempf);
					var tempUnit = (units =='metric') ? 'C' : 'F';
					var finaltemp = temp+'&deg; '+tempUnit;
					// YAZ 20111212 - skip all the N/A stations
					if (tempf===null || typeof(tempf)=="undefined" || tempf=='-999' || tempf=='-9999' || parseFloat(tempf)<=-999) continue;

					// dewpoint
					var dewpointf = weatherStations[i]['dewptf'];
					var dewpoint= convertTempIntoUnits(units,dewpointf);
					var dewpointUnit= (units =='metric') ? 'C' : 'F';
					var finaldewpoint;
					if(dewpoint == '-') {
						finaldewpoint = NA;
					} else {
						finaldewpoint = dewpoint+'&deg; '+dewpointUnit;
					}

					// humidity
					var humidity = weatherStations[i]['humidity'];
					if (humidity =='-999') humidity = '-';
					if (humidity =='N/A') humidity = '-';
					var finalhumidity;
					if(humidity == '-' || humidity < 0) {
						finalhumidity = NA;
					} else {
						finalhumidity = humidity+'%';
					}

					// pressure
					var pressurein = weatherStations[i]['baromin'];
					var pressure = convertPressureIntoUnits(units,pressurein);
					var pressureUnit = (units=='metric') ? 'hPa' : 'in';
					var finalpressure;
					if(pressure == '-' || pressurein == undefined || pressure < 0) {
						finalpressure = NA;
					} else {
						finalpressure = pressure+' '+pressureUnit;
					}

					// rain
					var rainin = weatherStations[i]['rainin'];
					var rain = convertRainIntoUnits(units,rainin);
					var rainUnit = (units=='metric') ? 'cm' : 'in';
					var finalrain;
					if(rainin <= -999) {
						finalrain = NA;
					} else {
						if(rainin == 0) {
							finalrain = '0 '+rainUnit;
						} else {
							finalrain = rain+' '+rainUnit+'/hr';
						}
					}

					// daily rain
					var dailyrainin = weatherStations[i]['dailyrainin'];
					var dailyrain = convertRainIntoUnits(units,dailyrainin);
					var finaldailyrain;
					if(dailyrainin <= -999 || dailyrainin == undefined) {
						finaldailyrain = NA;
					} else {
						if(dailyrain == 0) {
							finaldailyrain = '0 '+rainUnit;
						} else {
							finaldailyrain = dailyrain+' '+rainUnit;
						}
					}

					// wind
					var winddir = weatherStations[i]['winddir'];
					var winddirstring=lookupWindString(winddir);
					var windspdmph = weatherStations[i]['windspeedmph'];
					var windspd = convertWindIntoUnits(units,windspdmph);
					var windspdUnit = (units =='metric') ? 'km/h' : 'mph';
					var finalwind;
					if (windspdmph == 0) {
						finalwind = 'calm';
					} else {
						if(winddir == undefined || winddir == '-' || windspdmph == undefined || windspdmph == '-' || windspdmph < 0) {
							finalwind = NA;
						} else {
							finalwind = winddirstring+' at '+windspd+' '+windspdUnit;
						}
					}

					var tdkeystyle = '"padding: 2px 10px 2px 2px; color: #333; font-size: 12px;"';
					var tdvaluestyle = '"font-weight: normal; padding: 2px; font-size: 12px;"';

					html[i] = '';

					html[i] += '<div style="width: 210px;">' +
					'<div style="font-size: 14px; cursor: pointer; line-height: 1.1em; font-weight: bold; margin: 0 0 5px 0;"><a title="Click for forecast" href="' + histlink + '" target="top" style="color: #333; text-decoration: none;">' + name + '</a></div>' +
					'<table cellspacing="0" cellpadding="0">' +
					'<tr><td style='+tdkeystyle+'>Temperature</td><td style='+tdvaluestyle+'>'+finaltemp+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Dewpoint</td><td style='+tdvaluestyle+'>'+finaldewpoint+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Humidity</td><td style='+tdvaluestyle+'>'+finalhumidity+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Wind</td><td style='+tdvaluestyle+'>'+finalwind+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Pressure</td><td style='+tdvaluestyle+'>'+finalpressure+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Precipitation</td><td style='+tdvaluestyle+'>'+finalrain+'</td></tr>' +
					'<tr><td style='+tdkeystyle+'>Daily Precipitation</td><td style='+tdvaluestyle+'>'+finaldailyrain+'</td></tr>' +
					'</table>';

					// add the graph

					// html[i]+='<div style="margin: 5px 0 0 0;">';
					// if (iconmode == 'tw') {
					// 	if(type == 'ICAO' || type == 'SYNOP') {
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/histGraphAll?ID='+id+'&type=3&showtemp=1&showtitle=0&width=350" height="120" width="350">';
					// 	} else if (type=='PWS') {
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/wxStationGraphAll?ID='+id+'&type=3&showtemp=1&showtitle=0&width=350" height="120" width="350">';
					// 	}
					// } else if (iconmode == 'tdh') {
					// 	if(type == 'ICAO' || type == 'SYNOP') {
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/histGraphAll?ID='+id+'&type=3&showtemp=1&showtitle=0&width=350" height="120" width="350">';
					// 	} else if (type=='PWS'){
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/wxStationGraphAll?ID='+id+'&type=3&showtemp=1&showtitle=0&width=350" height="120" width="350">';
					// 	}
					// } else {
					// 	if(type == 'ICAO' || type == 'SYNOP') {
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/histGraphAll?ID='+id+'&type=3&showrain=1&showtitle=0&width=350" height="120" width="350">';
					// 	} else if (type=='PWS'){
					// 		html[i] += '<img src="http://www.wunderground.com/cgi-bin/wxStationGraphAll?ID='+id+'&type=3&showrain=1&showtitle=0&width=350" height="120" width="350">';
					// 	}
					// }
					// html[i]+='</div>';
					
					html[i]+='</div>';

					html_forecast[i] = '';

					markers[i] = new GLatLng(lat, lon);

					m[i] = createMarker(markers[i], html[i], html_forecast[i], iconmode, temp,tempf,  windspd,windspdmph, winddir, dewpoint,dewpointf, humidity, rain,rainin, weather, id);
					
					map.addOverlay(m[i]);

				}
	
        //map.addOverlays(m);

        for(var i=0; i<weatherStations.length; ++i) {
					delete weatherStations[i];
				}
				
}

</script>
]]>

</Content>
</Module>

