// ==UserScript==
// @name          Accu Weather
// @namespace     http://iescripts.org
// @description	  Display the local weather in the statusbar, Copy from Windows vista accu weather gadgets
// @statussize    180
// ==/UserScript==

(function()
{
  var plugin = PRO_plugin(@name);
  var currentWeather = ""; 
  var currentIcon = "ie7pro://pluginpath/images/01.png";  
  var currentTip = "";

  var WeatherUnits;
  var CurrentLocation;
  var CurrentConditions;
  var CurrentImages;
  var CurrentForecasts;
  var CurrentWatches;
  var CurrentLinks;
  var ErrorString="";
  var DataComplete=false;
  var UseDate;
  var mySplitDate;
  var LocRadar;
  var tempmin;

  var LANG_chs = new Array("设置地点和选项",
			"美国卫星云图",
			"本地区卫星云图(未必存在)",
			"刷新数据",
			"访问AccuWeather.com",
			"查看本地天气预报",
			"天气预报",
			"一","二","三","四","五","六","日"," 最高气温:"," 最低气温:");
  var LANG_eng = new Array("Set Location and Options",
			"U.S. Radar Image",
			"Your Regional Radar Image (If available)",
			"Refresh Data",
			"Go to AccuWeather.com",
			"Weather Warnings in your area",
			"Weather Forecast",
			"Mon","Tue","Wed","Thu","Fri","Sat","Sun"," Hi:"," Lo:");	
  var lng = PRO_getLang();
  switch(lng){
	case "eng":
	case "chs":
                eval("var LANG = LANG_" + lng + ";");
	        eval("var CONF = \"findLocation." + lng + ".html\"");
		break;
	default:
		var LANG = LANG_eng;
		var CONF = "findLocation.eng.html";
		break;
  }

  plugin.registerContextMenu(LANG[0], menuSetLocation);
  plugin.registerContextMenu("separator"); // add an separator for menu 
  plugin.registerContextMenu(LANG[1], menuShowRadar);
  plugin.registerContextMenu(LANG[2], menuShowLocRadar);
  plugin.registerContextMenu(LANG[3], UpdateWeather);
  plugin.registerContextMenu(LANG[4], menuShowAWPage);
  plugin.registerContextMenu(LANG[5], menuShowWarnPage);
  plugin.ontabcreate = handleTabCreate;
  plugin.onpopupclose = handlePopupClose;

  var reqObj = new Object();
  reqObj.request = function(callback, cookie, url, userAgent, lastModify,qtype) {
	  var req;
	  req = PRO_xmlhttpRequest();
	  req.onreadystatechange = function() {
		  if (req.readyState == 4) {// completed
			  if (req.status < 400) {// only if "OK"
				  try {
					  callback(req, cookie);
				  } catch(err) {
				  }
			  } else {
				  // PRO_log("There was a problem loading data :\n" + req.status+ "/" + req.statusText);
			  }
			  setTimeout(function() {req.forceClean();req = null;}, 1000);
		  }
	  }
	  try {
		  req.open(qtype, url);
		  req.setRequestHeader( "User-Agent", userAgent);
		  if(lastModify.length > 0)
			  req.setRequestHeader( "If-Modified-Since", lastModify);
		  req.send(null);

	  } catch(err){ 
	  }
	  return req;
  }

  UpdateWeather();
// updates every 30 minutes
  setInterval(UpdateWeather, 1000*60*30 );

  function menuSetLocation(cookie,url) {
	  plugin.popupWindow("ie7pro://pluginpath/" + CONF,"","dialogWidth:500;dialogHeight:600;resizable:yes",cookie);
  }

  function menuShowAWPage(cookie,url) {
		PRO_openInTab(CurrentConditions.url,1);
	}

  function menuShowWarnPage(cookie,url) {
		PRO_openInTab(CurrentWatches.url,1);
	}

// possible future addition
//  function ShowWarnPopup(cookie,url) {
//	  plugin.popupWindow("ie7pro://pluginpath/warning.html","","dialogWidth:500;dialogHeight:600;resizable:no",cookie);
//	}

  function menuShowRadar(cookie,url) {
	  plugin.popupWindow("http://sirocco.accuweather.com/nx_mosaic_400x300c/SIR/inmSIRus_.gif","","dialogWidth:452;dialogHeight:398;resizable:no",cookie);
//	  plugin.popupWindow("http://sirocco.accuweather.com/nx_mosaic_400x300c/SIR/inmSIRKY_.gif","","dialogWidth:500;dialogHeight:400;resizable:yes",cookie);
  }

  function menuShowLocRadar(cookie,url) {
	  LocRadar=CurrentImages.radar;
	  LocRadar=LocRadar.replace(/108x81/, "400x300");
	  plugin.popupWindow(LocRadar,"","dialogWidth:452;dialogHeight:398;resizable:yes",cookie);
  }

  function handleTabCreate(cookie) {
	  plugin.setStatusInfo(currentIcon, currentWeather, currentTip);
  }

  function handlePopupClose(cookie, url, returnVal) {
	  UpdateWeather();
  }

  function processWeatherData(req, cookie) {
	  parseData(req.responseXML.documentElement);
  }

  function UpdateWeather() {
// Use "tempmin" to put a number at the end of the url to thwart the 30 minute lifespan of the document
// accuweather.com sets a pages "Expires" date in the http header for 30 minutes after serving page
// the extraneous parameter(ie. &extra=01) at the end of the url is 
// ignored by accuweather, but prevents this script from just accessing the page in cache
// the extra parameter gives it a unique url, as far as the cache is concerned
// allowing for a refresh every minute if desired, rather than 30 minutes.
	  tempmin=0;
	  var tempday = new Date();
	  tempmin=tempday.getMinutes();
// end - except for...  "." + tempmin +  ...down a few lines
	  var mylocation=PRO_getValue("weather_Location","10001");
	  var mymetric=PRO_getValue("weather_Unit","metric");
	  var met = 1;
	  if(mymetric == "english")  met = 0;
	  var queryurl = "http://vwidget.accuweather.com/widget/vista1/weather_data_v2.asp?location=" + mylocation + "&metric=" + met + "&extra=" + tempmin;
	  reqObj.request(processWeatherData, "", queryurl, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; Alexa Toolbar)", "Thu, 26 Aug 2002 08:24:16 GMT","GET");    
  }

function Images(xmlNode) {
	this.radar=xmlNode.getElementsByTagName('radar').item(0).firstChild.data;
}

function Units(xmlNode) {
	this.tempUnit=xmlNode.getAttribute('temp');
	this.speedUnit=xmlNode.getAttribute('speed');
	this.distUnit=xmlNode.getAttribute('dist');
	this.presUnit=xmlNode.getAttribute('pres');
	this.precUnit=xmlNode.getAttribute('prec');
}

function Watches(xmlNode) {
	this.zone=xmlNode.getAttribute('zone');
	this.county=xmlNode.getAttribute('county');
	this.isactive=xmlNode.getAttribute('isactive');
	if (xmlNode.getElementsByTagName('url').item(0).firstChild!=null) {
		this.url=xmlNode.getElementsByTagName('url').item(0).firstChild.data;
	} else {
		this.url="";
	}
}

function Location(xmlNode) {
	this.city=xmlNode.getAttribute('city');
	this.state=xmlNode.getAttribute('state');
	this.time=xmlNode.getAttribute('time');
}

function Conditions(xmlNode) {
	this.url=xmlNode.getElementsByTagName('url').item(0).firstChild.data;
	tempNode=xmlNode.getElementsByTagName('wxc').item(0);
	this.temperature=tempNode.getAttribute('temp');
	this.realFeel=tempNode.getAttribute('rft');
	this.humidity=tempNode.getAttribute('hum');
	this.text=tempNode.getAttribute('text');
	this.icon=tempNode.getAttribute('icon');
	this.windGust=tempNode.getAttribute('wgus');
	this.windSpeed=tempNode.getAttribute('wspd');
	this.windDir=tempNode.getAttribute('wdir');
	this.visibility=tempNode.getAttribute('vis');
	this.precip=tempNode.getAttribute('prec');
	this.uvindex=tempNode.getAttribute('uvi');
	this.uvtext=tempNode.getAttribute('uvt');
	this.radarUrl=xmlNode.getElementsByTagName('radurl').item(0).firstChild.data;
}

function Links(xmlNode) {
	this.promo1Link=xmlNode.getElementsByTagName('promo1').item(0).getAttribute('url');
	this.promo1Name=xmlNode.getElementsByTagName('promo1').item(0).getAttribute('name');
	this.homeLink=xmlNode.getElementsByTagName('home').item(0).getAttribute('url');	
}

function Forecasts(xmlNode) {
	tempNodes=xmlNode.getElementsByTagName('day');
	tempArray=new Array(tempNodes.length);
	for (count=0;count<tempNodes.length;count++) {
		tempArray[count]=new ForecastDay(tempNodes[count]);
	}
	this.forecastArray=tempArray;
}

function ForecastDay(xmlNode) {
	this.dayNumber=xmlNode.getAttribute('number');
	this.date=xmlNode.getAttribute('date');
	this.weekDay=xmlNode.getAttribute('wday');
	switch (this.weekDay) {
		case "Monday" : this.shortWeekDay=LANG[7];break;
		case "Tuesday" : this.shortWeekDay=LANG[8];break;
		case "Wednesday" : this.shortWeekDay=LANG[9];break;
		case "Thursday" : this.shortWeekDay=LANG[10];break;
		case "Friday" : this.shortWeekDay=LANG[11];break;
		case "Saturday" : this.shortWeekDay=LANG[12];break;
		case "Sunday" : this.shortWeekDay=LANG[13];break;
	}
	this.url=xmlNode.getElementsByTagName('url').item(0).firstChild.data;
	
	//Daytime forecast data
	this.daytimeTextShort=xmlNode.getElementsByTagName('./daytime/txtshort').item(0).firstChild.data;
	this.daytimeTextLong=xmlNode.getElementsByTagName('./daytime/txtlong').item(0).firstChild.data;
	this.daytimeIcon=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('icon');
	this.daytimeHigh=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('htmp');
	this.daytimeRealFeelHigh=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('rfh');
	this.daytimeWindSpeed=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('wspd');
	this.daytimeWindDirection=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('wdir');
	this.daytimeWindGust=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('wgus');
	this.daytimeMaxUV=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('mxuv');
	this.daytimeRain=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('rain');
	this.daytimeSnow=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('snow');
	this.daytimePrecip=xmlNode.getElementsByTagName('./daytime/wxf').item(0).getAttribute('prec');
	
	//Nighttime forecast data
	this.nighttimeTextShort=xmlNode.getElementsByTagName('./nighttime/txtshort').item(0).firstChild.data;
	this.nighttimeTextLong=xmlNode.getElementsByTagName('./nighttime/txtlong').item(0).firstChild.data;
	this.nighttimeIcon=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('icon');
	this.nighttimeLow=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('ltmp');
	this.nighttimeRealFeelLow=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('rfl');
	this.nighttimeWindSpeed=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('wspd');
	this.nighttimeWindDirection=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('wdir');
	this.nighttimeWindGust=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('wgus');
	this.nighttimeRain=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('rain');
	this.nighttimeSnow=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('snow');
	this.nighttimePrecip=xmlNode.getElementsByTagName('./nighttime/wxf').item(0).getAttribute('prec');
}

function parseData(xmlData) {
	try {
		CurrentLocation=new Location(xmlData.getElementsByTagName("./local").item(0));
		WeatherUnits=new Units(xmlData.getElementsByTagName("./units").item(0));
		CurrentConditions=new Conditions(xmlData.getElementsByTagName("./currentconditions").item(0));
		CurrentImages=new Images(xmlData.getElementsByTagName("./images").item(0));
		CurrentForecasts=new Forecasts(xmlData.getElementsByTagName("./forecast").item(0));
		CurrentWatches=new Watches(xmlData.getElementsByTagName("./watchwarnareas").item(0));
		CurrentLinks=new Links(xmlData.getElementsByTagName("./links").item(0));
		DataComplete=true;
		var mymetric=PRO_getValue("weather_Unit","metric");
		if(mymetric == "metric" ) 
// degree symbol doesn't show in all browsers
// if you prefer to lose the C or F, swap the rem slashes around on the lines below
//			met = " ";
			met = "C";
		else
//			met = " ";
			met = "F";

// display city name in statusbar?
	  	var displaycity=PRO_getValue("weather_city_display","showcity");
		if(displaycity == "hidecity" ) {
			currentWeather = "Now: " + CurrentConditions.text + ", " + CurrentConditions.temperature + met;
		}else{ 
			currentWeather = "Now: " + CurrentConditions.text + ", " + CurrentConditions.temperature + met + "(" + CurrentLocation.city + ")";
		} 
		currentIcon = "ie7pro://pluginpath/images/" + CurrentConditions.icon  + ".png";           
// use proportional(default) or monospaced(Courier New) font?
	  	var usefont=PRO_getValue("weather_font",0);
		if(usefont==1) {
			var tipfont='</font><font size="4" face="Courier New">';
		}else{
			var tipfont="";
		}
		currentTip = '<font size="4"><B>' + CurrentLocation.city + LANG[6] + ' </B> (' + CurrentLocation.time + ')<br>' + tipfont;
// which date format is used?
	  	var displaydate=PRO_getValue("weather_date_format","usdate");
		for(i=0;i<5;i++) {
			UseDate = CurrentForecasts.forecastArray[i].date;
			if(displaydate == "shtusdate" ) {
				mySplitDate = UseDate.split("/");
				UseDate = mySplitDate[0] + "/" + mySplitDate[1];
			}
			if(displaydate == "intdate" ) {
				mySplitDate = UseDate.split("/");
				UseDate = mySplitDate[1] + "/" + mySplitDate[0] + "/" + mySplitDate[2];
			}
			if(displaydate == "shtintdate" ) {
				mySplitDate = UseDate.split("/");
				UseDate = mySplitDate[1] + "/" + mySplitDate[0];
			}
			currentTip += UseDate + " " + CurrentForecasts.forecastArray[i].shortWeekDay + LANG[14] + CurrentForecasts.forecastArray[i].daytimeHigh + met + LANG[15] + CurrentForecasts.forecastArray[i].nighttimeLow +met + " \- " + CurrentForecasts.forecastArray[i].daytimeTextShort + "<br>";
		}     
		currentTip += " </font>";
// show flag icon in statusbar and warning message in tooltip if active warning in set location
		if(CurrentWatches.isactive > 0){
			currentTip += '<font size="4"><B>*** SEVERE WEATHER WARNING!! ***<br>Check AccuWeather.com Warnings Page!</B></font>';
			currentIcon = 'ie7pro://pluginpath/images/flag.png';
// potential future addition don't use now, it will hang your browser
//			ShowWarnPopup();
		}
		plugin.setStatusInfo(currentIcon, currentWeather,currentTip)
	} catch (e) {

	}
}

}
)();
