//	Javascript file for the WeatherCenter gadget
//	(c) 2009
//	WeatherCenter Gadget Team
//	Development: hadj 
//	Graphics: Tex
//	Testing: Digital	
////////////////////////////////////////////////////////////////////////


function parseForecastNOAA(Xml,ForecastXml)
{
	var parametrsArray = [{"name":"nothing", "capt":"", "span":""}]

	
	var locName = System.Gadget.Settings.read("NOAAlastSearch");
	if ((locName+"").search(/\d/) > -1) locName = locName + ", US";
	setLocation(locName);
	
	
	if (Xml.indexOf("<weather>") > -1) var current = Xml.substring(Xml.indexOf("<weather>") + 9, Xml.indexOf("</weather>"));
	else var current = "";


	timeupdate = Xml.substring(Xml.indexOf("<observation_time_rfc822>") + 25, Xml.indexOf("</observation_time_rfc822>"));	//time last update
	timeupdate = timeupdate.slice(timeupdate.indexOf(":") - 2, timeupdate.lastIndexOf(":"));
	if ((System.Gadget.Settings.read("showLastTimeUpdate")) != 1 || !timeupdate) TimeLastUpdate.innerText = "";
	else TimeLastUpdate.innerText = timeupdate;


														//actual temperature
	if (System.Gadget.Settings.read("tunits") == "m") {
		var temp = Xml.substring(Xml.indexOf("<temp_c>") + 8, Xml.indexOf("</temp_c>"));
		temp = Math.round(temp);
		var TemperatureUnits = "C";
	}
	if (System.Gadget.Settings.read("tunits") == "f") {
		var temp = Xml.substring(Xml.indexOf("<temp_f>") + 8, Xml.indexOf("</temp_f>"));
		var TemperatureUnits = "F";
	}
	if (temp == 'NaN') temp = lng_nodata;
	TempSpan.innerHTML = temp + "&deg;" + lng_Units[TemperatureUnits];


	
	var wind = Xml.substring(Xml.indexOf("<wind_mph>") + 10, Xml.indexOf("</wind_mph>"));
	if (wind == '' || wind == 'N/A' || Xml.indexOf("<wind_mph>") == -1) wind = 0;
	if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed = (wind*0.44704).toFixed(); var SpeedUnits = "m/s";}
	if (System.Gadget.Settings.read("sunits") == "km") {windSpeed = (wind*1.609344).toFixed(0); var SpeedUnits = "km/h";}
	if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed = wind; var SpeedUnits = "mph";}

	var windDirection = Xml.substring(Xml.indexOf("<wind_dir>") + 10, Xml.indexOf("</wind_dir>"));
	var WindDirectionSpan = winddirection_Stats[windDirection];
	if (WindDirectionSpan == undefined) WindDirectionSpan = "";
	else WindDirectionSpan = "[" + WindDirectionSpan + "]";

	WindCapt = lng_Stats["wind"] + WindDirectionSpan;
	WindSpan = windSpeed + lng_Units[SpeedUnits];
	if (wind == 'N/A' || wind == 'calm' || wind == 'CALM' || wind == '' || wind == 'NaN') WindSpan = lng_nodata;
	parametrsArray.push({"name":"wind", "capt":WindCapt, "span":WindSpan});



	var humidity = Xml.substring(Xml.indexOf("<relative_humidity>") + 19, Xml.indexOf("</relative_humidity>"));
	HumidityCapt = lng_Stats["humidity"];
	HumiditySpan = humidity + "%";
	if (humidity == 'N/A' ||Xml.indexOf("<relative_humidity>") == -1) HumiditySpan = lng_nodata;
	parametrsArray.push({"name":"humidity", "capt":HumidityCapt, "span":HumiditySpan});



	var pressure = Xml.substring(Xml.indexOf("<pressure_mb>") + 13, Xml.indexOf("</pressure_mb>"));
	if (System.Gadget.Settings.read("punits") == "mm") {pressure = (pressure * 0.75006).toFixed(0); var PressureUnits = "mm";}
	if (System.Gadget.Settings.read("punits") == "mb") {var PressureUnits = "mb";}
	if (System.Gadget.Settings.read("punits") == "in") {pressure = (pressure * 0.02953).toFixed(2); var PressureUnits = "in";}
	if (System.Gadget.Settings.read("punits") == "kpa") {pressure = (pressure * 0.1).toFixed(2); var PressureUnits = "kPa";}
	PressureCapt = lng_Stats["pressure"];
	PressureSpan = pressure + lng_Units[PressureUnits];
	if (pressure == 'NaN') PressureSpan = lng_nodata;
	parametrsArray.push({"name":"pressure", "capt":PressureCapt, "span":PressureSpan});


											//dewpoint
	if (System.Gadget.Settings.read("tunits") == "m") {
		var dewpoint = Xml.substring(Xml.indexOf("<dewpoint_c>") + 12, Xml.indexOf("</dewpoint_c>"));
		var TemperatureUnits = "C";
	}
	if (System.Gadget.Settings.read("tunits") == "f") {
		var dewpoint = Xml.substring(Xml.indexOf("<dewpoint_f>") + 12, Xml.indexOf("</dewpoint_f>"));
		var TemperatureUnits = "F";
	}
	DewpCapt = lng_Stats["dewpoint"];
	DewpSpan = dewpoint + "°" + lng_Units[TemperatureUnits];
	if (dewpoint == '' || Xml.indexOf("<dewpoint_c>") == -1 || Xml.indexOf("<dewpoint_f>") == -1) DewpSpan = lng_nodata;
	parametrsArray.push({"name":"dewpoint", "capt":DewpCapt, "span":DewpSpan});


	var visibility = Xml.substring(Xml.indexOf("<visibility_mi>") + 15, Xml.indexOf("</visibility_mi>"));
	if (System.Gadget.Settings.read("dunits") == "km") {visibility = (visibility*1.609344).toFixed(0); var DistanceUnits = "km";}
	if (System.Gadget.Settings.read("dunits") == "mi") {var DistanceUnits = "mi";}
        VisibilityCapt = lng_Stats["visibility"];
	VisibilitySpan = visibility + lng_Units[DistanceUnits];
	if (visibility == 'N/A' || visibility == '' || visibility == 'NaN') VisibilitySpan = lng_nodata;
	parametrsArray.push({"name":"visibility", "capt":VisibilityCapt, "span":VisibilitySpan});



	LocationCode = System.Gadget.Settings.read('locationCode').split('|');
	var latitude = LocationCode[0].slice(0, LocationCode[0].indexOf(","));
	var longitude = LocationCode[0].slice(LocationCode[0].indexOf(",") + 1, LocationCode[0].length);

	//var latitude = Xml.substring(Xml.indexOf("<latitude>") + 10, Xml.indexOf("</latitude>"));	//latitude
	LatitudeCapt = lng_Stats["latitude"];
	LatitudeSpan = latitude;
	if (latitude == 'N/A' || latitude == '') LatitudeSpan = lng_nodata;
	parametrsArray.push({"name":"latitude", "capt":LatitudeCapt, "span":LatitudeSpan});


	//var longitude = Xml.substring(Xml.indexOf("<longitude>") + 11, Xml.indexOf("</longitude>"));	//longitude
	LongitudeCapt = lng_Stats["longitude"];
	LongitudeSpan = longitude;
	if (longitude == 'N/A') LongitudeSpan = lng_nodata;
	parametrsArray.push({"name":"longitude", "capt":LongitudeCapt, "span":LongitudeSpan});



	var timezone = Xml.substring(Xml.indexOf("<observation_time_rfc822>") + 25, Xml.indexOf("</observation_time_rfc822>"));
	timezone = timezone.slice(timezone.lastIndexOf(" ") + 1, timezone.length);
	timezone = timezone.replace(/0/g,"");


	var theSunRiseSunset = computeSunRiseSunSet(parseInt(latitude), parseInt(longitude), parseInt(timezone));
	var sunriseTm = theSunRiseSunset.SunRise;
	var sunsetTm = theSunRiseSunset.SunSet;


	checkDayorNight(timeupdate, sunriseTm, sunsetTm, current);


	SunriseCapt = lng_Stats["sunrise"];
	SunriseSpan = sunriseTm;
	if (sunriseTm == '') SunriseSpan = lng_nodata;
	parametrsArray.push({"name":"sunrise", "capt":SunriseCapt, "span":SunriseSpan});
	
	SunsetCapt = lng_Stats["sunset"];
	SunsetSpan = sunsetTm;
	if (sunsetTm == '') SunsetSpan = lng_nodata;
	parametrsArray.push({"name":"sunset", "capt":SunsetCapt, "span":SunsetSpan});


	setOptionsSettings(parametrsArray);


	

	currentImg.src = "images/" + System.Gadget.Settings.read('Skin') + "/" + daytime + "/" + NOAAGetCondImage(current);


	if (daytime == "Night" && img == "undefined.png") img = "clear.png";

	if (daytime == "Night" && (img == "partcloudy.png" || img == "cloudy.png" || img == "mostcloudy.png" || img == "clear.png")) {

	var moon_img = {
		New: "new.png",
		"Waxing Crescent": "waxing_crescent.png",
		"First Quarter": "first_quater.png",
		"Waxing Gibbous": "waxing_gibbous.png",
		Full: "full.png",
		"Waning Gibbous": "waning_gibbous.png",
		"Last Quarter": "last_quater.png",
		"Waning Crescent": "waning_crescent.png",
		Darkened: "new.png"
		};

		var moonphase = computePhaseOfMoon(new Date().getFullYear(), new Date().getMonth()+1, new Date().getDate());
		currentImgMoon.src = "images/" + System.Gadget.Settings.read('Skin') + "/Night/moon/" + moon_img[moonphase];
		if (img != "clear.png") {currentImg.style.display = "block";}
		else currentImg.style.display = "none";
	}
	else currentImgMoon.style.display = "none";
	

	
	while (current.length > 19) {
	 		current = current.slice(0, current.lastIndexOf(" "));
			lastsymbol = current.substring(current.lastIndexOf(" ") + 1, current.length);
			if (lastsymbol.length == 1 || lastsymbol == 'and') current = current.slice(0, current.lastIndexOf(" "));
		}
	CondSpan.innerText = current;

	

	NOAAFillForecast(ForecastXml);

	
	redrawGadget();
	
		
	
}




////////////////////////




function NOAAGetCondImage(condition)
{
	img="undefined.png";

	if ((condition.search(/Cloudy/) > -1) || (condition.search(/Clouds/) > -1) || (condition.search(/Overcast/) > -1))
		img="cloudy.png";

	if (condition.search(/Rain/) > -1 || condition.search(/shra/) > -1 || condition.search(/shwr/) > -1)
		img="rain.png";

	if (condition.search(/Hail/) > -1)
		img="hail.png";

	if ((condition.search(/Sunny/) > -1) || (condition.search(/skc/) > -1))
		img="clear.png";

	if ((condition.search(/Mostly Sunny/) > -1 || condition.search(/Partly Sunny/) > -1))
		img="mostsunny.png";

	if (condition.search(/Dust/) > -1)
		img="dusthaze.png";

	if ((condition.search(/Fog/) > -1) || (condition.search(/Mist/) > -1) || (condition.search(/Haze/) > -1)) 
		img="fog.png";

	if (condition.search(/Smoke/) > -1)
		img="smoke.png";

	if (condition.search(/Snow/) > -1 || condition.search(/sn/) > -1)
		img="snow.png";

	if ((condition.search(/Thunder/) > -1) || (condition.search(/T-Storm/) > -1))
		img="thunderstorm.png";

	if ((condition.search(/Partly Cloudy/) > -1) || (condition.search(/Fair/) > -1) || (condition.search(/few/) > -1) || (condition.search(/sct/) > -1))
		img="partcloudy.png";

	if (condition.search(/Mostly Cloudy/) > -1 || condition.search(/bkn/) > -1 || condition.search(/ovc/) > -1)
		img="mostcloudy.png";

	if ((condition.search(/Light Rain/) > -1) || (condition.search(/Shower/) > -1) || (condition.search(/Drizzle/) > -1) || (condition.search(/ra/) > -1))
		img="lightrain.png";

	if ((condition.search(/Snow/) > -1) && ((condition.search(/Rain/) > -1) || (condition.search(/Shower/) > -1)))
		img="rainandsnow.png";
	
	if ((condition.search(/Snow/) > -1) && (condition.search(/Light/) > -1) || (condition.search(/Flurries/) > -1) || (condition.search(/Ice Crystals/) > -1))
		img="lightsnow.png";

	return img;
}




///////////////////////




function NOAAFillForecast(XmlData)
{


	var a = 1;
	totalFCDays = 0;
	
	var daytemperature = XmlData.getElementsByTagName('temperature')[0];
	var nighttemperature = XmlData.getElementsByTagName('temperature')[1];

	var DayTempArray = daytemperature.getElementsByTagName('value');
	var NightTempArray = nighttemperature.getElementsByTagName('value');


	var dayname = XmlData.getElementsByTagName('time-layout')[0];
	var DayNameArray = dayname.getElementsByTagName('start-valid-time');

	var forecast3H = XmlData.getElementsByTagName('time-layout')[2];
	var forecast3Harray = forecast3H.getElementsByTagName('start-valid-time');
	
	var conditionsicon = XmlData.getElementsByTagName('conditions-icon')[0];
	var IconsArray = conditionsicon.getElementsByTagName('icon-link');

	var WeatherType = XmlData.getElementsByTagName('weather')[0];
	var WeatherTypeArray = WeatherType.getElementsByTagName('weather-conditions');

	for (var i = 0; i < NightTempArray.length; i++) {

		if ((System.Gadget.Settings.read("showForecastToday")) != 1 || (Date24ToMinutesConvert(timeupdate) >= 900 && DayNameArray[i].getAttribute('period-name') == 'Today'))
			{
				if (i == 0) i++;
			}
 		

		var high = DayTempArray[i].firstChild.nodeValue;
		var low = NightTempArray[i].firstChild.nodeValue;

		if (System.Gadget.Settings.read("tunits") == "m") {high = Math.round((high - 32)*5/9); low = Math.round((low - 32)*5/9);}
				
		high+="°";
		low +="°";
		
	
	
		var day = DayNameArray[i].getAttribute('period-name');
		
	
		var date = DayNameArray[i].firstChild.nodeValue;
		date = date.slice(0, date.lastIndexOf("T"));
		var datestr = DateUSToEU(date);

	
		for (var count = 0; count < forecast3Harray.length; count++) {
			var period3H = forecast3Harray[count].firstChild.nodeValue;
			var period3Hday = period3H.slice(0, period3H.lastIndexOf("T"));
			var period3Htime = period3H.slice(period3H.lastIndexOf("T")+1, period3H.length);
			period3Htime = period3Htime.slice(0, period3Htime.lastIndexOf("-"));
			if (period3Hday == date && (period3Htime > "10:00:00" && period3Htime < "15:00:00")) var forecastimg = IconsArray[count].firstChild.nodeValue;
		}

		forecastimg = forecastimg + "";
		forecastimg = forecastimg.slice(forecastimg.lastIndexOf("/") + 1, forecastimg.indexOf(".jpg"));

	
		document.getElementById("dayName" + a).innerText = day; 
		document.getElementById("date" + a).innerText = datestr; 
		document.getElementById("dayHi" + a).innerText = high;
		document.getElementById("separator"  + a).innerText = "/";
		document.getElementById("dayLow" + a).innerText = low; 
		document.getElementById("dayImg" + a).src = "images/" + System.Gadget.Settings.read('Skin') + "/Forecast/" + NOAAGetCondImage(forecastimg);
		//if (System.Gadget.Settings.read('showFlyoutForecast') == "1") document.getElementById("dayImg" + a).alt = current + "; " + windSpeed + "; " + humidity;
		a++;
		totalFCDays++;
	}

}








function DateUSToEU(timeparametr)
{	
	day = timeparametr.slice(timeparametr.lastIndexOf("-") + 1, timeparametr.length);
	month = timeparametr.slice(timeparametr.indexOf("-") + 1, timeparametr.lastIndexOf("-"));

var lng_Number_Month = {
	"01": "Jan",
	"02": "Feb",
	"03": "Mar",
	"04": "Apr",
	"05": "May",
	"06": "Jun",
	"07": "Jul",
	"08": "Aug",
	"09": "Sep",
	"10": "Oct",
	"11": "Nov",
	"12": "Dec"};

	date = day +" " + lng_Month[lng_Number_Month[month]];
	return date;
}




