CmdUtils.CreateCommand({
	name: "forecast",
	homepage: "http://dothejustice.com/forecast/",
	author: {name: "Brad McNair", email: "bradlby@dothejustice.com"},
	takes: {"location": noun_arb_text},
	modifiers: {in: noun_arb_text},
	icon: "http://www.wunderground.com/favicon.ico",
	description: "Displays the 5 day forecast for a given location.",
	help: "Works with both zip codes and city names.  Append &quot;in c&quot; for Celsius temperatures and &quot;in f&quot; for Fahrenheit.  If no units are specified the user's geolocation determines the units.",
	execute: function( directObj, mods ) {
		var location = directObj.text;
		var units = mods.in.text;
		var url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=";
		url += escape( location );
		
		Utils.openUrlInBrowser( url );
		},
	
	preview: function( pblock, directObj, units ) {
		var location = directObj.text;
		if( location.length < 1 ) {
			pblock.innerHTML = "Displays the weather forecast for a zip code/city.";
			return;
		}
		
		//Set the temperature units based on geolocation if nothing is specified by the user 
		
		var tempunits = 'c';
		if(!units.in.text){
			var cc = CmdUtils.getGeoLocation().country_code;
			if(["US", "UM", "BZ"].indexOf(cc) != -1){
				tempunits = 'f';
			}
		}else{
			tempunits = units.in.text;
		}
				
		// Let's get the forecast data from Wunderground's forecast XML feed
	
		var url = "http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml";
		jQuery.get( url, {query: location}, function(xml) {
			var forecastData = [];
			var el = jQuery(xml).find("simpleforecast");
			if( el.length == 0 ) return;
	
		// If there is data, let's loop through and get the day and status icon
		
			el.find("forecastday").each(function(i){
				var period = jQuery(this);
				var icon = period.find("icon").text();
				forecastData.push({
					day: period.find("weekday").text(),
					fhigh: period.find("high fahrenheit").text(),
					flow: period.find("low fahrenheit").text(),
					chigh: period.find("high celsius").text(),
					clow: period.find("low celsius").text(),
					image: "http://icons-pe.wxug.com/i/c/a/" + icon + ".gif"
				});
			});

			var previewTemplate = "{for day in d}" +
			"<div style=\"float: left; text-align: center; width: 80px; height: 90px;\">" +
			"${day.day}" +
			"<br />" +
			"<img src=\"${day.image}\" />" +
			"<br />" +
			
			// If the unit is defined as Celsius, switch to that.  Otherwise stay with Fahrenheit
			
			"{if unit[0] == \"c\"}"+
			"H: ${day.chigh}&deg;C <br /> L: ${day.clow}&deg;C" +
			"{else}" + 
			"H: ${day.fhigh}&deg;F <br /> L: ${day.flow}&deg;F" +
			"{/if}" +
			"</div>" +
			"{/for}" +
			"<div style=\"clear: both;\">&nbsp;</div>";

			var previewData = {
				loc: directObj.text,
				d: forecastData,
				unit: tempunits,
			};

			pblock.innerHTML = CmdUtils.renderTemplate(previewTemplate, previewData);
		});
	}

});