'Scriptversion:3


'Station List Variables
Dim locList()
Dim locID()
Dim locDistKM()
Dim locDistMI()
'Other Variables
Dim PortCodes()
Dim PortCity()
Dim PortStates()
Dim PortCountry()
Dim CamNeighborhood()
Dim CamAddress()
Dim CamZip()
Dim CamCity()
Dim CamState()
Dim CamCountry()
Dim CamUpdated()
Dim CamImage()
Dim CamURL()
Dim RadarImage
Dim RadarURL
'Current Condition Variables
Dim WeatherUnits
Dim dispFull
Dim dispCity 
Dim dispState 
Dim dispSName 
Dim dispCountry 
Dim dispZip 
Dim dispLat 
Dim dispLong 
Dim dispElv 
Dim obsLoc 
Dim obsFull 
Dim obsCity 
Dim obsState 
Dim obsCountry 
Dim obsLat 
Dim obsLong 
Dim obsElv 
Dim statID 
Dim obsTimeGMT 
Dim localTime 
Dim curWeather 
Dim curTempF 
Dim curTempC 
Dim curHumidity 
Dim curPressureMB 
Dim curPressureIN 
Dim curDewpointF 
Dim curDewpointC 
Dim curHeatindexF 
Dim curHeatindexC 
Dim curWindchillF 
Dim curWindchillC 
Dim curVisibleMI 
Dim curVisibleKM 
Dim curIconbase 
Dim curIconExtension 
Dim curIcon 
Dim curForecastURL 
Dim curHistoryURL 
Dim curObservationURL
'PWS extra Variables 
Dim credText 
Dim credURL 
Dim credLogo 
Dim curWind 
Dim curWindDir 
Dim curWindDeg 
Dim curWindMPH 
Dim curWindGust 
Dim dispNhood 
Dim curSolarRadiation 
Dim curUV 
Dim curPrecipIN 
Dim curPrecipMetric 
Dim curPrecipTodayIN 
Dim curPrecipTodayMetric
'Daypart Variables
Dim DaypartIcon(1)
Dim DaypartTitle(1)
Dim DaypartWeather(1)
'Forecast Variables
Dim ForecastAltText(5)
Dim ForecastDate(5)
Dim ForecastMonth(5) 
Dim ForecastWeekday(5) 
Dim ForecastHighF(5) 
Dim ForecastHighC(5)
Dim ForecastLowF(5)
Dim ForecastLowC(5) 
Dim ForecastConditions(5)
Dim ForecastIcon(5)
Dim ForecastSkyIcon(5)
Dim ForecastMoonIlluminated
Dim ForecastMoonAge
Dim ForecastSunset
Dim ForecastSunrise
Dim ForecastCurrentTime
'Alert Variables
Dim AlertDescription()
Dim AlertMessage()
'File Locations
Dim cacheFile : cacheFile = Object.Directory  & "\NOAAWU_Cache_Forecast.xml"
Dim cacheCCFile : cacheCCFile = Object.Directory  & "\NOAAWU_Cache_Current.xml"
Dim cacheSFile : cacheSFile = Object.Directory  & "\NOAAWU_Cache_Stations.xml"
Dim cacheAFile : cacheAFile = Object.Directory  & "\NOAAWU_Cache_Alerts.xml"
'
Dim CycleTextArray
Dim cycleT

'====================================
'  CHANGE/SAVE/CHECK CURRENT WEATHER MODE
'====================================
Function changeMode(cmode)
	Object.Comments = cmode
End Function

Function checkMode
	checkMode = Object.Comments
End Function


'====================================
'  CHANGE/SAVE/CHECK REFRESH MODE
'====================================

Function changeRefreshMode(rmode)
	object.PersistStorage("refreshmode") = rmode
End Function

Function checkRefreshMode
	checkRefreshMode = object.PersistStorage("refreshmode")
End Function

'=======================
'     ON START UP
'=======================
Sub Startup
	If object.PersistStorage("forecast") = "" Then 
		changeMode("default")
 		object.PersistStorage("location") = "10001"
 		object.PersistStorage("forecast") = "10001"
 		object.PersistStorage("pws") = "MDC010"
 		changeRefreshMode("new") 'are we getting a new or saved location?
	End If 
	
	If Object.PersistStorage("unit") <> "" Then
		WeatherUnits = Object.PersistStorage("unit")
	Else
		WeatherUnits = "s"
		Object.PersistStorage("unit") = WeatherUnits
	End If
	Object.SetTimer 22, 2700000
	Object_Ontimer22
End Sub

'=======================
'    UPDATE TIMER 
'=======================

Sub Object_OnTimer22
	If system.InternetConnected Then
		LocationSearch(object.PersistStorage("forecast"))
	Else
		setStatus("nonet")
		Call GetCacheCCWeather
		Call GetCacheWeather
		Call GetCacheStations
		Call GetCacheAlerts
	End If	
End Sub

'-------Called when L-click on object or its children-------
Function ButtonClicked(obj)
	'--Various Buttons
	Select Case obj
		Case "WeatherFunction_SetLocation", "WeatherFunction_SetLocation2"
			SearchBox
		Case "WeatherFunction_ToggleUnits", "WeatherFunction_ToggleUnits2"
			SetUnits
		Case "Weather_ToggleInfo"
			If DesktopX.IsObject("Weather_infoback") = True Then
				If DesktopX.Object("Weather_infoback").visible = False Then
					DesktopX.Object("Weather_infoback").visible = True
				Else
					DesktopX.Object("Weather_infoback").visible = False
				End If
			End If
		Case "Weather_Search_cancel"
			DesktopX.Object("Weather_Search_cancel").visible = False
			setStatus("ready")
			DesktopX.Object("Weather_Search_back").visible = False
			DesktopX.Object("Weather_Search_combo").visible = False
	End Select
End Function

'--------On Mouse Enter---------
Sub IconOver(obj)
	If Instr(obj, "weather_image_fc") > 0 Then
		mynum=right(obj,1)
		If DesktopX.IsObject("weather_forecaststatus") Then 
			If Weatherunits = "s" Then
				Desktopx.Object("weather_forecaststatus").text= ForecastAltText(mynum-1)
			Else
				Desktopx.Object("weather_forecaststatus").text= ForecastAltText(mynum-1)
			End If
		End If
	End If
End Sub

'--------On Mouse Leave---------
Sub IconAway(obj)
	If Instr(obj, "weather_image_fc") > 0 Then
		If DesktopX.IsObject("weather_forecaststatus") Then desktopx.Object("weather_forecaststatus").text= ""
	End If
End Sub

'============================
'  LOCATION SEARCH FUNCTIONS
'============================

Function SearchBox
	Dim Input
	Input = InputBox("Enter a location name or US/Canadian zipcode" & vbcrlf & vbcrlf & "e.g. 10001; New York; London, United Kingdom; Canada", "Location Search...", object.PersistStorage("forecast")) 
	If Input <> "" Then
		If strCheck(Input) = "t" Then
			If system.InternetConnected Then
				LocationSearch(Input)
				changeRefreshMode("new")
			Else
				setStatus("nonet")
			End If
		End If
	End If
End Function

Function DisplayMatches(loList)
	DesktopX.ScriptObject("Weather_Search_combo").populate(loList)
	DesktopX.Object("Weather_Search_combo").visible = True	
	DesktopX.Object("Weather_Search_back").visible = True	
	DesktopX.Object("Weather_Search_cancel").visible = True
End Function

Function GetICAO(string)
	changeMode("default")
	changeRefreshMode("new")
	LocationSearch(string)
End Function

'=============================
'      REQUEST FINISH
'=============================

'--- Status Text ---
Function setStatus(stype)
	StatusText = "Weather_status"
	If DesktopX.IsObject(StatusText) Then
		If stype = "search" Then
			DesktopX.Object(StatusText).text = "Status: searching..."
		ElseIf stype = "forecast" Then
			DesktopX.Object(StatusText).text = "Status: retrieving forecast..."
		ElseIf stype = "current" Then
			DesktopX.Object(StatusText).text = "Status: retrieving current weather..."
		ElseIf stype = "alert" Then
			DesktopX.Object(StatusText).text = "Status: retrieving alerts..."
		ElseIf stype = "ready" Then
			DesktopX.Object(StatusText).text = "Status: ready"
		ElseIf stype = "nonet" Then
			DesktopX.Object(StatusText).text = "Status: no internet connection"
		ElseIf stype = "serror" Then
			DesktopX.Object(StatusText).text = "Status: site unavailable"
		End If
	End If
End Function

'=================================
'        DISPLAY WEATHER
'=================================

'======= CURRENT WEATHER =======
Function OutputCurrent(ctype)
	'Check time diff between now and sunset/rise
	nowtoset = DateDiff("n",ForecastCurrentTime,ForecastSunset) 
	nowtorise = DateDiff("n",ForecastCurrentTime,ForecastSunrise)
	'Default to night
	timeofday = "night"
	'Set to day if after sunrise & before sunset
	If Sgn(nowtoset) = 1  And Sgn(nowtorise) = -1 Then timeofday = "day"
	
	'--General Current Weather--
	If ctype = "default" Then
		'Set icon 
		If timeofday = "night" Then picsuffix = "PM.png" Else picsuffix = ".png"
		Set fso = CreateObject("Scripting.FileSystemObject")
		pic = Object.Directory & curIcon & picsuffix
		'If no nightime icon exists set day icon
		If fso.fileexists(pic) = False Then pic = Object.Directory & curIcon & ".png"
		If DesktopX.IsObject("WeatherOutput_Image") Then DesktopX.Object("WeatherOutput_Image").picture = pic
		If DesktopX.IsObject("WeatherOutput_Image2") Then DesktopX.Object("WeatherOutput_Image2").picture = pic
		
		'Location text
		If DesktopX.IsObject("WeatherFunction_SetLocation") Then DesktopX.Object("WeatherFunction_SetLocation").text = dispFull
		If DesktopX.IsObject("WeatherFunction_SetLocation2") Then DesktopX.Object("WeatherFunction_SetLocation2").text = dispFull
		
		'Temperature
		If WeatherUnits = "s" Then curTemp = curTempF & Chr(176) & " F" Else curTemp = curTempC & Chr(176) & " C"
		If DesktopX.IsObject("WeatherFunction_ToggleUnits") Then DesktopX.Object("WeatherFunction_ToggleUnits").text = curTemp
		If DesktopX.IsObject("WeatherFunction_ToggleUnits2") Then DesktopX.Object("WeatherFunction_ToggleUnits2").text = curTemp
		
		'Output Timestamp
		If DesktopX.IsObject("Weather_Timestamp") Then DesktopX.Object("Weather_Timestamp").text = "Last Update: " & localTime

		'Cyclical Display
		If WeatherUnits = "s" Then
			CycleTextArray = Array("Weather: "&curWeather,"Humidity: "&curHumidity,"Pressure: "&curPressureIN&" in","Dewpoint: "&Int(curDewpointF)& Chr(176),"Visiblity: "&curVisibleMI&" mi","Heat Index: "&curHeatindexF& Chr(176),"Wind: "&curWindDir&" "&curWindMPH&" mph", "Windgust: "&curWindGust&" mph", "Windchill: "&curWindchillF& Chr(176),"Sunrise: "&FormatDateTime(ForecastSunrise,3),"Sunset: "&FormatDateTime(ForecastSunset,3))
		Else
			CycleTextArray = Array("Weather: "&curWeather,"Humidity: "&curHumidity,"Pressure: "&curPressureMB&" mb","Dewpoint: "&Int(curDewpointC)& Chr(176),"Visiblity: "&curVisibleKM&" km","Heat Index: "&curHeatindexc& Chr(176),"Wind: "&curWindDir&" "& curWindMPH&" mph", "Windgust: "&curWindGust&" mph", "Windchill: "&curWindchillC& Chr(176),"Sunrise: "&FormatDateTime(ForecastSunrise,3),"Sunset: "&FormatDateTime(ForecastSunset,3))
		End If		
		If DesktopX.IsObject("Weather_ccText") Then
			startCycle
		End If
		
	'--Personal Weather Station Current Weather--
	ElseIf ctype = "pws" Then
		'Set Icon
		If DesktopX.IsObject("WeatherOutput_Image") Then DesktopX.Object("WeatherOutput_Image").picture = pic
		If DesktopX.IsObject("WeatherOutput_Image2") Then DesktopX.Object("WeatherOutput_Image2").picture = pic
		'Set Location
		If DesktopX.IsObject("WeatherFunction_SetLocation") Then DesktopX.Object("WeatherFunction_SetLocation").text = dispFull
		If DesktopX.IsObject("WeatherFunction_SetLocation2") Then DesktopX.Object("WeatherFunction_SetLocation2").text = dispFull
		'Temperature
		If WeatherUnits = "s" Then curTemp = Int(curTempF) & Chr(176) & " F" Else curTemp = Int(curTempC) & Chr(176) & " C"
		If DesktopX.IsObject("WeatherFunction_ToggleUnits") Then DesktopX.Object("WeatherFunction_ToggleUnits").text = curTemp
		If DesktopX.IsObject("WeatherFunction_ToggleUnits2") Then DesktopX.Object("WeatherFunction_ToggleUnits2").text = curTemp
		'Output Timestamp
		If DesktopX.IsObject("Weather_Timestamp") Then DesktopX.Object("Weather_Timestamp").text = "Last Update: " & localTime
		'Cyclical Display
		If WeatherUnits = "s" Then
				CycleTextArray = Array("Weather: "&curWeather,"Humidity: "&curHumidity,"Pressure: "&curPressureIN&" in","Dewpoint: "&Int(curDewpointF)& Chr(176),"Visiblity: "&curVisibleMI&" mi","Heat Index: "&curHeatindexF& Chr(176),"Wind: "&curWindDir&" "&curWindMPH&" mph", "Windgust: "&curWindGust&" mph", "Windchill: "&curWindchillF& Chr(176),"Sunrise: "&FormatDateTime(ForecastSunrise,3),"Sunset: "&FormatDateTime(ForecastSunset,3))
		Else
				CycleTextArray = Array("Weather: "&curWeather,"Humidity: "&curHumidity,"Pressure: "&curPressureMB&" mb","Dewpoint: "&Int(curDewpointC)& Chr(176),"Visiblity: "&curVisibleKM&" km","Heat Index: "&curHeatindexc& Chr(176),"Wind: "&curWindDir&" "& curWindMPH&" mph", "Windgust: "&curWindGust&" mph", "Windchill: "&curWindchillC& Chr(176),"Sunrise: "&FormatDateTime(ForecastSunrise,3),"Sunset: "&FormatDateTime(ForecastSunset,3))
		End If		
		If DesktopX.IsObject("Weather_ccText") Then
			startCycle
		End If
	End If
End Function

Function startCycle
	cycleT = 0
	Object.SetTimer 12, 5000
	Object_OnTimer12
End Function

Sub Object_OnTimer12
	maxArray = UBound(CycleTextArray)
	If cycleT => maxArray+1 Then cycleT=0
	If Instr(CycleTextArray(cycleT),"N/A") Or CycleTextArray(cycleT) = "" Then
		cycleT=cycleT+1
		Object_OnTimer12
	Else
		DesktopX.Object("Weather_ccText").Text = CycleTextArray(cycleT)
		cycleT = cycleT + 1
	End If
End Sub

'====== FORECAST ======
Function OutputForecast
	'Icons
	For x = 0 To 5
		If DesktopX.IsObject("weather_image_fc"&x+1) Then DesktopX.Object("weather_image_fc"&x+1).picture = ForecastIcon(x) & ".png"
	Next
	
	'Day
	For x = 0 To 5
		If DesktopX.IsObject("Weather_dayname"&x+1) Then DesktopX.Object("Weather_dayname"&x+1).text = Left(ForecastWeekday(x),3)
	Next
	
	'More Text
	For x = 0 To 5
		If WeatherUnits = "s" Then hilo = ForecastHighF(x) &" / " & ForecastLowF(x) Else hilo = ForecastHighC(x) &" / " & ForecastLowC(x) 
		ForecastAltText(x) = hilo & vbcrlf & ForecastConditions(x)
	Next
End Function

'====== TOGGLE UNITS ==========
Function SetUnits
	If WeatherUnits = "m" Then
		WeatherUnits = "s"
	Else
		WeatherUnits = "m"
	End If
	Object.persiststorage("unit") = WeatherUnits
	' Refresh the weather information
	OutputCurrent(checkMode)	
	OutputForecast
End Function


'====== ALERTS =========
Function OutputAlerts
	
End Function

'======== STATIONS ========
Function OutputStations
	
End Function

'========= AIRPORTS =========
Function OutputAirports
	
End Function

'======= WEBCAMS & RADAR ========
Function OutputWebcams
	
End Function

Function saveWebcam(url)
	Object.PersistStorage("webcam") = url
End Function

Function getWebcam
	getWebcam = Object.PersistStorage("webcam")
End Function


'=================================================
'            MULTI-USE FUNCTIONS
'=================================================

'--Check if input is not blank (or spaces) ---
Function strCheck(strg)
	Dim abet, nums
	strg2 = LCase(strg)
	abet = "abcdefghijklmnopqrstuvwxyz"
	nums = "0123456789"
	chk = "f"
	For x = 1 To len(abet)
		g =Mid(abet,x,1)
		If  Instr(strg2,g) > 0 Then	chk = "t"
	Next
	If chk = "f" Then
		For y = 1 To len(nums)
			g =Mid(nums,y,1)
			If Instr(strg2,g) > 0 Then chk = "t"
		Next
	End If
	strCheck = chk
End Function


'============================
'  LOCATION SEARCH FUNCTIONS
'============================
Function LocationSearch(strg)
	setStatus("search")			
	searchURL = "http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=" & strg
	searchResults = System.SendRequest(searchURL, "POST", True)	
End Function

Function ListMatches(info)
	locCount = countStr(info,"</location>")
	locCount = locCount - 1
	locdata = info
	locCurrent = -1
	ReDim loList(locCount)
	For x = 0 To locCount		' Loop for each match	
		locName = xmlstripper("<name>", locdata)
		If locName <> "N/A" And locName <> ""  And Instr(locName,",") Then
			locCurrent = locCurrent + 1
			loList(locCurrent) = locName
		End If			
		locdata = Right(locdata, Len(locdata) - InStr(locdata, "</location>"))
	Next	
	Call DisplayMatches(loList)
End Function

Function ListStations(info)
	Call CacheStations(info)
	t = -1	
	locdata = xmlstripper("<pws>", info)
	locCount = countStr(info,"</station>") : locCount = locCount - 1
	cTagEnd = "]" & "]" & ">"
	cTagStart = "<" & "!" & "[" & "CDATA" & "["	
	ReDim locList(-1)
	ReDim locID(-1)
	ReDim locDistKM(-1)
	ReDim locDistMI(-1)	
	For x = 0 To locCount		' Loop for each match	
		'neighborhood
		locName = xmlstripper("<neighborhood>", locdata)
		locName = Replace(locName, cTagStart, "")
		locName = Replace(locName, cTagEnd, "")
		If Instr(locName, "   ") Then
			lNparts = split(locName,"   ")
			locName = lNparts(0)
		End If
		locName = Trim(locName)
		If locName <> "N/A" And locName <> "" And strCheck(locName) = "t" Then
			ReDim Preserve locList(UBound(locList)+1)
			ReDim Preserve locID(UBound(locID)+1)
			ReDim Preserve locDistKM(UBound(locDistKM)+1)
			ReDim Preserve locDistMI(UBound(locDistMI)+1)	
			locList(UBound(locList)) = locName			
		End If	
		'station id
		locIDs = xmlstripper("<id>", locdata)
		locIDs = Replace(locIDs, cTagStart, "")
		locIDs = Replace(locIDs, cTagEnd, "")
		locIDs = Trim(locIDs)
		If locIDs <> "N/A" And locIDs <> "" And strCheck(locName) = "t" Then	locID(UBound(locID)) = locIDs
		'distance kilometer
		locKM = xmlstripper("<distance_km>", locdata)
		locKM = Replace(locKM, cTagStart, "")
		locKM = Replace(locKM, cTagEnd, "")
		locKM = Trim(locKM)
		If locKM <> "N/A" And locKM <> "" And strCheck(locName) = "t" Then	locDistKM(UBound(locDistKM)) = locKM
		'distance miles
		locMI = xmlstripper("<distance_mi>", locdata)
		locMI = Replace(locMI, cTagStart, "")
		locMI = Replace(locMI, cTagEnd, "")
		locMI = Trim(locMI)
		If locMI <> "N/A" And locMI <> "" And strCheck(locName) = "t" Then	locDistMI(UBound(locDistMI)) = locMI		
		locdata = Right(locdata, Len(locdata) - InStr(locdata, "</station>"))
	Next
	Call OutputStations
End Function

Function ListAirports(info)
	portdata = xmlstripper("<airport>", info)
	portcount = countStr(portdata, "</station>") : portcount = portcount - 1
	ReDim PortCodes(portcount)
	ReDim PortCity(portcount)
	ReDim PortStates(portcount)
	ReDim PortCountry(portcount)
	For x = 0 To portcount
		PortCodes(x) = xmlstripper("<icao>",portdata)
		PortCity(x) = xmlstripper("<city>",portdata)
		PortStates(x) = xmlstripper("<state>",portdata)
		PortCountry(x) = xmlstripper("<country>",portdata)
		portdata = Right(portdata, Len(portdata) - InStr(portdata, "</station>"))
	Next
	Call OutputAirports
End Function

Function ListWebcams(info)
	cTagEnd = "]" & "]" & ">"
	cTagStart = "<" & "!" & "[" & "CDATA" & "["	
	wcdata = xmlstripper("<webcams>",info)
	camcount = countStr(wcdata, "</cam>") : camcount = camcount - 1
	ReDim CamNeighborhood(camcount)
	ReDim CamAddress(camcount)
	ReDim CamZip(camcount)
	ReDim CamCity(camcount)
	ReDim CamState(camcount)
	ReDim CamCountry(camcount)
	ReDim CamUpdated(camcount)
	ReDim CamImage(camcount)
	ReDim CamURL(camcount)
	For x = 0 To camcount
		CamNeighborhood(x) = xmlstripper("<neighborhood>",wcdata)
		CamAddress(x) = xmlstripper("<address>",wcdata)
		CamZip(x) = xmlstripper("<zip>",wcdata)
		CamCity(x) = xmlstripper("<city>",wcdata)
		CamState(x) = xmlstripper("<state>",wcdata)
		CamCountry(x) = xmlstripper("<country>",wcdata)
		CamUpdated(x) = xmlstripper("<updated>",wcdata)
		CamImage(x) = xmlstripper("<CURRENTIMAGEURL>",wcdata)
		CamURL(x) = xmlstripper("<CAMURL>",wcdata)
		wcdata = Right(wcdata, Len(wcdata) - InStr(wcdata, "</cam>"))
	Next
	radardata = xmlstripper("<radar>",info)
	RadarImage = xmlstripper("<image_url>",radardata) : RadarImage = Replace(RadarImage, cTagEnd, "") : RadarImage = Replace(RadarImage, cTagStart,"")
	RadarURL = xmlstripper("<url>",radardata) : RadarURL = Replace(RadarURL, cTagEnd, "") : RadarURL = Replace(RadarURL, cTagStart, "")
	
	Call OutputWebcams
End Function

'=============================
'    GET WEATHER FUNCTIONS
'=============================

Function GetCurrent(strg)
	setStatus("current")
	searchURL = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" & strg
	searchResults = System.SendRequest(searchURL, "POST", True)	
End Function

Function GetCurrentPWS(strg)
	setStatus("current")
	searchURL = "http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=" & strg
	searchResults = System.SendRequest(searchURL, "POST", True)	
End Function

Function GetForecast(strg)
	setStatus("forecast")			
	searchURL = "http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=" & strg
	searchResults = System.SendRequest(searchURL, "POST", True)	
End Function

Function GetAlerts(strg)
	setStatus("alert")			
	searchURL = "http://api.wunderground.com/auto/wui/geo/AlertsXML/index.xml?query=" & strg
	searchResults = System.SendRequest(searchURL, "POST", True)	
End Function

'=============================
'   URL REQUEST FINISH
'=============================

Sub System_OnRequestFinish(url, pagecontent)
	'--Search Page Results---
	If instr(url,"GeoLookupXML") > 0 Then
		If Instr(pagecontent, "<locations>") Then
			ListMatches(pagecontent)
			setStatus("ready")
		ElseIf Instr(pagecontent,"<pws>") Then
			'Reset webcam if new location
			If checkRefreshMode = "new" Then
				saveWebcam("")
				changeMode("default")
				changeRefreshMode("refresh")
			End If
			ListAirports(pagecontent)
			ListWebcams(pagecontent)
			spURL = split(url,"=")
			'Save locations
			Object.PersistStorage("location") = spURL(1)
			Object.PersistStorage("forecast") = spURL(1)
			ListStations(pagecontent)
			'Get weather
			GetForecast(Object.PersistStorage("forecast"))
			setStatus("ready")
		ElseIf Instr(pagecontent, "<wui_error>") Then
			errMsg = xmlstripper("<title>",pagecontent)
			msgbox errMsg
			setStatus("ready")		
		Else
			setStatus("serror")
		End If
	'--Forecast Page Results---
	ElseIf instr(url, "ForecastXML") > 0 Then
		If Instr(pagecontent, "<simpleforecast>") Then
			spURL = split(url,"=")
			'Save locations
			Object.PersistStorage("forecast") = spURL(1)
			ParseForecast(pagecontent)
			setStatus("ready")
		Else
			setStatus("serror")
		End If
		'Get Current (default or pws)
		If checkMode = "default" Then
			GetCurrent(Object.PersistStorage("location"))
		ElseIf Object.Comments = "pws" Then
			GetCurrentPWS(Object.PersistStorage("pws"))
		End If
	'---Current General Results---
	ElseIf instr(url, "WXCurrentObXML/index.xml") > 0 Then
		If Instr(pagecontent, "<icon>") Then
			ParseCurrent(pagecontent)
			setStatus("ready")
		ElseIf Instr(pagecontent, "<wui_error>") Then
			errMsg = xmlstripper("<title>",pagecontent)
			msgbox errMsg
			setStatus("ready")
		Else
			setStatus("serror")
		End If
	'---Current Personal Weather Station Results---
	ElseIf instr(url, "weatherstation") > 0 Then
		If Instr(pagecontent, "<current_observation>") Then
			spURL = split(url,"=")
			Object.PersistStorage("pws") = spURL(1)
			ParseCurrentPWS(pagecontent)
			setStatus("ready")
		ElseIf Instr(pagecontent, "<wui_error>") Then
			errMsg = xmlstripper("<title>",pagecontent)
			msgbox errMsg
			setStatus("ready")
		Else
			setStatus("serror")
		End If
	'---Alert Results--
	ElseIf instr(url, "AlertsXML") > 0 Then
		If Instr(pagecontent,"<alerts>") Then
			ParseAlerts(pagecontent)
			setStatus("ready")
		End If
	End If
End Sub

'==========================
' PARSE WEATHER FUNCTIONS 
'==========================

Function ClearCurrentVars
	Clear dispLoc
	Clear dispFull
	Clear dispCity 
	Clear dispState 
	Clear dispSName 
	Clear dispCountry 
	Clear dispZip 
	Clear dispLat 
	Clear dispLong 
	Clear dispElv 
	Clear obsLoc 
	Clear obsFull 
	Clear obsCity 
	Clear obsState 
	Clear obsCountry 
	Clear obsLat 
	Clear obsLong 
	Clear obsElv 
	Clear statID 
	Clear obsTimeGMT 
	Clear localTime 
	Clear curWeather 
	Clear curTempF 
	Clear curTempC 
	Clear curHumidity 
	Clear curPressureMB 
	Clear curPressureIN 
	Clear curDewpointF 
	Clear curDewpointC 
	Clear curHeatindexF 
	Clear curHeatindexC 
	Clear curWindchillF 
	Clear curWindchillC 
	Clear curVisibleMI 
	Clear curVisibleKM 
	Clear curIconbase 
	Clear curIconExtension 
	Clear curIcon 
	Clear curForecastURL 
	Clear curHistoryURL 
	Clear curObservationURL 
	Clear credText 
	Clear credURL 
	Clear credLogo 
	Clear curWind 
	Clear curWindDir 
	Clear curWindDeg 
	Clear curWindMPH 
	Clear curWindGust 
	Clear dispNhood 
	Clear curSolarRadiation 
	Clear curUV 
	Clear curPrecipIN 
	Clear curPrecipMetric 
	Clear curPrecipTodayIN 
	Clear curPrecipTodayMetric 	
End Function

Function ParseCurrent(info)
	Call CacheCCWeather(info)
	'Display Location
	dispLoc = xmlstripper("<display_location>", info)
	dispFull = xmlstripper("<full>", dispLoc)
	dispCity = xmlstripper("<city>", dispLoc)
	dispState = xmlstripper("<state>", dispLoc)
	dispSName = xmlstripper("<state_name>", dispLoc)
	dispCountry = xmlstripper("<country>", dispLoc)
	dispZip = xmlstripper("<zip>", dispLoc)
	dispLat = xmlstripper("<latitude>", dispLoc)
	dispLong = xmlstripper("<longitude>", dispLoc)
	dispElv = xmlstripper("<elevation>", dispLoc)
	'Observation Location
	obsLoc = xmlstripper("<observation_location>", info)
	obsFull = xmlstripper("<full>", obsLoc)
	obsCity = xmlstripper("<city>", obsLoc)
	obsState = xmlstripper("<state>", obsLoc)
	obsCountry = xmlstripper("<country>", obsLoc)
	obsLat = xmlstripper("<latitude>", obsLoc)
	obsLong = xmlstripper("<longitude>", obsLoc)
	obsElv = xmlstripper("<elevation>", obsLoc)
	'Conditions
	statID = xmlstripper("<station_id>", info) 'station/airport id
	obsTimeGMT = xmlstripper("<observation_time_rfc822>", info) 'observation time
	localTime = xmlstripper("<local_time>", info) 'local time
	curWeather = xmlstripper("<weather>", info) 'current conditions
	curTempF = xmlstripper("<temp_f>", info) 'farenheit
	curTempC = xmlstripper("<temp_c>", info) 'celsius
	curHumidity = xmlstripper("<relative_humidity>", info) 'humidity
	curWind = xmlstripper("<wind_string>", info) 'wind strength
	curWindDir = xmlstripper("<wind_dir>", info) 'wind direction
	curWindDeg = xmlstripper("<wind_degrees>", info) 'degrees
	curWindMPH = xmlstripper("<wind_mph>", info) 'speed mph
	curWindGust = xmlstripper("<wind_gust_mph>", info) 'gust speed
	curPressureMB = xmlstripper("<pressure_mb>", info) 'pressure mb
	curPressureIN = xmlstripper("<pressure_in>", info) 'pressure in
	curDewpointF = xmlstripper("<dewpoint_f>", info) 'farenheit
	curDewpointC = xmlstripper("<dewpoint_c>", info) 'celsius
	curHeatindexF = xmlstripper("<heat_index_f>", info) 'farenheit
	curHeatindexC = xmlstripper("<heat_index_c>", info) 'celsius
	curWindchillF = xmlstripper("<windchill_f>", info) 'farenheit
	curWindchillC = xmlstripper("<windchill_c>", info) 'celsius
	curVisibleMI = xmlstripper("<visibility_mi>", info) 'visibility mi
	curVisibleKM = xmlstripper("<visibility_km>", info) 'visibility km
	'Icon
	curIconbase = xmlstripper("<icon_url_base>", info) 'icon url base
	curIconExtension = xmlstripper("<icon_url_name>", info) 'icon extension
	curIcon = xmlstripper("<icon>", info) 'icon name
	'URLs
	curForecastURL = xmlstripper("<forecast_url>", info)
	curHistoryURL = xmlstripper("<history_url>", info)
	curObservationURL = xmlstripper("<ob_url>", info)
	'Credit
	credText = xmlstripper("<credit>", info)
	credURL = xmlstripper("<credit_URL>", info)
	credLogo = xmlstripper("<url>", info)
	'Save Data
	Object.PersistStorage("pws") = ""
	Object.PersistStorage("location") = dispFull
	'Output Data
	Call OutputCurrent("default")
	'Get Alerts
	Call GetAlerts(dispFull)
End Function


Function ParseCurrentPWS(info)
	Call CacheCCWeather(info)
	'Display Location
	dispLoc = xmlstripper("<location>", info)
	dispFull = xmlstripper("<full>", dispLoc)
	dispNhood = xmlstripper("<neighborhood>", dispLoc)
	dispCity = xmlstripper("<city>", dispLoc)
	dispState = xmlstripper("<state>", dispLoc)
	dispCountry = xmlstripper("<country>", dispLoc)
	dispZip = xmlstripper("<zip>", dispLoc)
	dispLat = xmlstripper("<latitude>", dispLoc)
	dispLong = xmlstripper("<longitude>", dispLoc)
	dispElv = xmlstripper("<elevation>", dispLoc)
	'Conditions
	statID = xmlstripper("<station_id>", info) 'station/airport id
	obsTimeGMT = xmlstripper("<observation_time_rfc822>", info) 'observation time
	localTime = xmlstripper("<local_time>", info) 'local time
	curWeather = xmlstripper("<weather>", info) 'current conditions
	curTempF = xmlstripper("<temp_f>", info) 'farenheit
	curTempC = xmlstripper("<temp_c>", info) 'celsius
	curHumidity = xmlstripper("<relative_humidity>", info) 'humidity
	curWind = xmlstripper("<wind_string>", info) 'wind strength
	curWindDir = xmlstripper("<wind_dir>", info) 'wind direction
	curWindDeg = xmlstripper("<wind_degrees>", info) 'degrees
	curWindMPH = xmlstripper("<wind_mph>", info) 'speed mph
	curWindGust = xmlstripper("<wind_gust_mph>", info) 'gust speed
	curPressureMB = xmlstripper("<pressure_mb>", info) 'pressure mb
	curPressureIN = xmlstripper("<pressure_in>", info) 'pressure in
	curDewpointF = xmlstripper("<dewpoint_f>", info) 'farenheit
	curDewpointC = xmlstripper("<dewpoint_c>", info) 'celsius
	curHeatindexF = xmlstripper("<heat_index_f>", info) 'farenheit
	curHeatindexC = xmlstripper("<heat_index_c>", info) 'celsius
	curWindchillF = xmlstripper("<windchill_f>", info) 'farenheit
	curWindchillC = xmlstripper("<windchill_c>", info) 'celsius
	curVisibleMI = xmlstripper("<visibility_mi>", info) 'visibility mi
	curVisibleKM = xmlstripper("<visibility_km>", info) 'visibility km
	curSolarRadiation = xmlstripper("<solar_radiation>", info)
	curUV = xmlstripper("<UV>", info)
	curPrecipIN = xmlstripper("<precip_1hr_in>", info)
	curPrecipMetric = xmlstripper("<precip_1hr_metric>", info)
	curPrecipTodayIN = xmlstripper("<precip_today_in>", info)
	curPrecipTodayMetric = xmlstripper("<precip_today_metric>", info)
	'URLs
	curHistoryURL = xmlstripper("<history_url>", info)
	curObservationURL = xmlstripper("<ob_url>", info)
	'Credit
	credText = xmlstripper("<credit>", info)
	credURL = xmlstripper("<credit_URL>", info)
	credLogo = xmlstripper("<url>", info)	
	'Output Data
	Call OutputCurrent("pws")
	'Get Alerts
	Call GetAlerts(Object.PersistStorage("forecast"))
End Function

Function ParseForecast(info)
	Call CacheWeather(info)
	' Day part forecast
	forecastdata = xmlstripper("<txt_forecast>", info)
	For x = 0 To 1
		DaypartIcon(x) = xmlstripper("<icon>", forecastdata)
		DaypartTitle(x) = xmlstripper("<title>", forecastdata)
		DaypartWeather(x) = xmlstripper("<fcttext>", forecastdata)
		forecastdata = Right(forecastdata, Len(forecastdata) - InStr(forecastdata, "</forecastday>"))
	Next
	' 6-Day Forecast
	forecastdata = xmlstripper("<simpleforecast>", info)
	For x = 0 To 5		' Loop for each day	
		'Date	
		ForecastDate(x) = xmlstripper("<day>", forecastdata)
		ForecastMonth(x) = xmlstripper("<monthname>", forecastdata)
		ForecastWeekday(x) = xmlstripper("<weekday>", forecastdata)
		'High temps
		hightemp = xmlstripper("<high>", forecastdata)
		ForecastHighF(x) = xmlstripper("<fahrenheit>", hightemp) &Chr(176)
		ForecastHighC(x) = xmlstripper("<celsius>", hightemp) &Chr(176)
		'Low temps
		lowtemp = xmlstripper("<low>", forecastdata)
		ForecastLowF(x) = xmlstripper("<fahrenheit>", lowtemp) &Chr(176)
		ForecastLowC(x) = xmlstripper("<celsius>", lowtemp) &Chr(176)
		'Conditions
		ForecastConditions(x) = xmlstripper("<conditions>", forecastdata)
		ForecastIcon(x) = xmlstripper("<icon>", forecastdata)
		ForecastSkyIcon(x) = xmlstripper("<skyicon>", forecastdata)
		
		forecastdata = Right(forecastdata, Len(forecastdata) - InStr(forecastdata, "</forecastday>"))
	Next
	'Sun and Moon data
	moondata = xmlstripper("<moon_phase>", info)
	ForecastMoonIlluminated = xmlstripper("<percentIlluminated>", moondata)
	ForecastMoonAge = xmlstripper("<ageOfMoon>", moondata)
	sunset = xmlstripper("<sunset>", moondata)
	ForecastSunset = xmlstripper("<hour>", sunset) & ":" & xmlstripper("<minute>", sunset)
	sunrise = xmlstripper("<sunrise>", moondata)
	ForecastSunrise = xmlstripper("<hour>", sunrise) & ":" & xmlstripper("<minute>", sunrise)
	fcurrenttime = xmlstripper("<current_time>", moondata)
	ForecastCurrentTime = xmlstripper("<hour>", fcurrenttime) & ":" & xmlstripper("<minute>", fcurrenttime)
	'Output Data
	Call OutputForecast
End Function

Function ParseAlerts(info)
	Call CacheAlerts(info)
	forecastdata = xmlstripper("<alerts>", info)
	alertcount = countStr(forecastdata, "</AlertItem>") - 1
	ReDim AlertDescription(alertcount)
	ReDim AlertMessage(alertcount)
	For x = 0 To alertcount
		AlertDescription(x) = xmlstripper("<description>", forecastdata)
		AlertMessage(x) = xmlstripper("<message>", forecastdata)
		forecastdata = Right(forecastdata, Len(forecastdata) - InStr(forecastdata, "</AlertItem>"))
	Next
	Call OutputAlerts
End Function

'==========================
'     CACHE WEATHER
'==========================

'Write 5-day cache
Function CacheWeather(info)
	Call writeFile(info,cacheFile)
End Function

'Write current conditions cache
Function CacheCCWeather(info)
	Call writeFile(info,cacheCCFile)
End Function

'Write stations cache
Function CacheStations(info)
	Call writeFile(info,cacheSFile)
End Function

'Write alerts cache
Function CacheAlerts(info)
	Call writeFile(info,cacheAFile)
End Function

'Read 5-day cache
Function GetCacheWeather
	Set fso = CreateObject("Scripting.FileSystemObject")
	If fso.fileexists(cacheFile) Then
		t = readFile(cacheFile)
		Call ParseForecast(t)
	End If
End Function

'Read current conditions cache
Function GetCacheCCWeather
	Set fso = CreateObject("Scripting.FileSystemObject")
	If fso.fileexists(cacheCCFile) Then
		t = readFile(cacheCCFile)
		If Instr(t,"display_location") Then Call ParseCurrent(t) Else Call ParseCurrentPWS(t)
	End If
End Function

'Read stations cache
Function GetCacheStations
	Set fso = CreateObject("Scripting.FileSystemObject")
	If fso.fileexists(cacheSFile) Then
		t = readFile(cacheSFile)
		Call ListStations(t)
		Call ListAirports(t)
		Call ListWebcams(t)
	End If
End Function

'Read alerts cache
Function GetCacheAlerts
	Set fso = CreateObject("Scripting.FileSystemObject")
	If fso.fileexists(cacheAFile) Then
		t = readFile(cacheAFile)
		Call ParseAlerts(t)
	End If
End Function

'=================================================
'            MULTI-USE FUNCTIONS
'=================================================

'------Basic function to strip XML tags--------
Function xmlstripper(param, string)
	If Instr(string, param) Then
		datastart = InStr(string, param) + Len(param)
		datalength = Instr(string, "</" & Right(param, Len(param) - 1)) - datastart
		dataresult = Mid(string, datastart, datalength)
		If dataresult = "" Or dataresult = "NA" Or strCheck(dataresult) = "f" Then xmlstripper = "N/A" Else xmlstripper = dataresult
	Else
		xmlstripper = "N/A"
	End If
End Function

'----Basic function to count instances of a string---
Function countStr(info,strg)
	spaceStr = 1
	wCount = 0		
	While iend < len(info)
			x = Instr(spaceStr, info , strg)
			If x > 0 Then 
				wCount = wCount + 1
				spaceStr = x+1
				y = x
			Else
				y = len(info)
			End If
			iend = y
	Wend
	countStr = wCount
End Function

'--- Read a file----
Function readFile(textfile)
	Set fso = CreateObject("Scripting.FileSystemObject")
	'Check if file exists
	If fso.FileExists(textfile) Then
		Set f = fso.OpenTextFile(textfile, 1)
		fileinfo = f.readall
		f.Close
	End If
	readFile = fileinfo
	Set fso = nothing
End Function

'--- Write to file----
Function writeFile(info, textfile)
	Set fso = CreateObject("Scripting.FileSystemObject")
	Set f = fso.OpenTextFile(textfile, 2, True)
	f.Write info
	f.Close
	Set fso = nothing
End Function