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


function parseForecastMeteonova(Xml)
{

	var parametrsArray = [{"name":"nothing", "capt":"", "span":""}]

	var wind_direction_rumb = {
	"0": "N",
	"1": "NE",
	"2": "E",
	"3": "SE",
	"4": "S",
	"5": "SW",
	"6": "W",
	"7": "NW"
	};


	var town = Xml.getElementsByTagName('TOWN')[0];

	
	var locName = System.Gadget.Settings.read('METEONOVAlastSearch');
	locName = locName.toString();

	if (locName.search(/\d/) > -1) locName = town.getAttribute('name') + ",";
	locName = locName.replace("Нижний ", "Н.");
	locName = locName.replace("КомсомольскнаДнепре", "Комсомольск, Украина");
	locName = locName.replace("Комсомольск-на, Украина", "Комсомольск, Украина");
	locName = locName.replace("КомсомольскнаАмуре", "Комсомольск, Россия");
	locName = locName.replace("Комсомольск-на-Амуре, Россия", "Комсомольск, Россия");
	setLocation(locName);
	


	
	var CurrentArray = Xml.getElementsByTagName('FORECAST')[0];

	var timeupdate = CurrentArray.getAttribute('hour');				//time last update


	if ((timeupdate - (new Date().getHours()) > 2) && MeteonovaFlag == 1) {
		updateBar.style.display = "none";
		return;
	}

	//if (new Date().getHours() > timeupdate + 3) {
	//	CurrentArray = Xml.getElementsByTagName('FORECAST')[1];
	//	timeupdate = CurrentArray.getAttribute('hour');
	//}

	if (timeupdate.length == 1) timeupdate = "0" + timeupdate;
	timeupdate = timeupdate + ":00";
	if ((System.Gadget.Settings.read("showLastTimeUpdate")) != 1) TimeLastUpdate.innerText = "";
	else TimeLastUpdate.innerText = timeupdate;
		

		
	var temp_max = parseInt(CurrentArray.getElementsByTagName('TEMPERATURE')[0].getAttribute('max'));				//actual temperature
	var temp_min = parseInt(CurrentArray.getElementsByTagName('TEMPERATURE')[0].getAttribute('min'));
	var temp = ((temp_max + temp_min)/2).toFixed(0);
	if (System.Gadget.Settings.read("tunits") == "m") {var TemperatureUnits = "C";}
	if (System.Gadget.Settings.read("tunits") == "f") {temp = (temp*(9/5) + 32).toFixed(0); var TemperatureUnits = "F";}
	if (temp == 'NaN') temp = lng_nodata;
	TempSpan.innerHTML = temp + "&deg;" + lng_Units[TemperatureUnits];


	var flik_max = parseInt(CurrentArray.getElementsByTagName('HEAT')[0].getAttribute('max'));					//flik temperature
	var flik_min = parseInt(CurrentArray.getElementsByTagName('HEAT')[0].getAttribute('min'));
	var flik = ((flik_max + flik_min)/2).toFixed(0);
	if (System.Gadget.Settings.read("tunits") == "m") {var TemperatureUnits = "C";}
	if (System.Gadget.Settings.read("tunits") == "f") {flik = (flik*(9/5) + 32).toFixed(0); var TemperatureUnits = "F";}
	if (flik == 'NaN') flik = lng_nodata;
	FlikCapt = lng_Stats["flik"];
	FlikSpan = flik + "&deg;" + lng_Units[TemperatureUnits];
	parametrsArray.push({"name":"flik", "capt":FlikCapt, "span":FlikSpan});


	var wind_max = parseInt(CurrentArray.getElementsByTagName('WIND')[0].getAttribute('max'));
	var wind_min = parseInt(CurrentArray.getElementsByTagName('WIND')[0].getAttribute('min'));
	if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed_max = wind_max; var SpeedUnits = "m/s";}
	if (System.Gadget.Settings.read("sunits") == "km") {windSpeed_max = (wind_max*3.6).toFixed(0); var SpeedUnits = "km/h";}
	if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed_max = (wind_max*0.621371192).toFixed(0); var SpeedUnits = "mph";}
	if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed_min = wind_min; var SpeedUnits = "m/s";}
	if (System.Gadget.Settings.read("sunits") == "km") {windSpeed_min = (wind_min*3.6).toFixed(0); var SpeedUnits = "km/h";}
	if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed_min = (wind_min*0.621371192).toFixed(0); var SpeedUnits = "mph";}

	var windDirection = parseInt(CurrentArray.getElementsByTagName('WIND')[0].getAttribute('direction'));
	var WindDirectionSpan = winddirection_Stats[wind_direction_rumb[windDirection]];
	if (WindDirectionSpan == undefined) WindDirectionSpan = "";
	else WindDirectionSpan = "[" + WindDirectionSpan + "]";

	WindCapt = lng_Stats["wind"] + WindDirectionSpan;
	WindSpan = windSpeed_min + "-" + windSpeed_max + lng_Units[SpeedUnits];
	if (wind_max == '' || wind_min == '') WindSpan = lng_nodata;
	parametrsArray.push({"name":"wind", "capt":WindCapt, "span":WindSpan});


	var humidity_max = parseInt(CurrentArray.getElementsByTagName('RELWET')[0].getAttribute('max'));
	var humidity_min = parseInt(CurrentArray.getElementsByTagName('RELWET')[0].getAttribute('min'));
	HumidityCapt = lng_Stats["humidity"];
	HumiditySpan = humidity_min + "-" +  humidity_max + "%";
	if (humidity_max == '' || humidity_min == '') HumiditySpan = lng_nodata;
	parametrsArray.push({"name":"humidity", "capt":HumidityCapt, "span":HumiditySpan});


	var pressure_max = parseInt(CurrentArray.getElementsByTagName('PRESSURE')[0].getAttribute('max'));
	var pressure_min = parseInt(CurrentArray.getElementsByTagName('PRESSURE')[0].getAttribute('min'));
	var pressure = ((pressure_max + pressure_min)/2).toFixed(0);
	if (System.Gadget.Settings.read("punits") == "mm") {var PressureUnits = "mm";}
	if (System.Gadget.Settings.read("punits") == "mb") {pressure = (pressure * 1.333224).toFixed(2); var PressureUnits = "mb";}
	if (System.Gadget.Settings.read("punits") == "in") {pressure = (pressure * 0.03937008).toFixed(2); var PressureUnits = "in";}
	if (System.Gadget.Settings.read("punits") == "kpa") {pressure = ((pressure/10)*0.1333224).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});



	var latitude_str = town.getAttribute('latitude');				//latitude
	latitude = (latitude_str*1).toFixed(2);
	LatitudeCapt = lng_Stats["latitude"];
	LatitudeSpan = latitude;
	if (latitude == '') LatitudeSpan = lng_nodata;
	parametrsArray.push({"name":"latitude", "capt":LatitudeCapt, "span":LatitudeSpan});


	var longitude_str = town.getAttribute('longitude');				//longitude
	longitude = (longitude_str*1).toFixed(2);
	LongitudeCapt = lng_Stats["longitude"];
	LongitudeSpan = longitude;
	if (longitude == '') LongitudeSpan = lng_nodata;
	parametrsArray.push({"name":"longitude", "capt":LongitudeCapt, "span":LongitudeSpan});

	

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


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



	var cloudiness = CurrentArray.getElementsByTagName('PHENOMENA')[0].getAttribute('cloudiness');
	var precipitation = CurrentArray.getElementsByTagName('PHENOMENA')[0].getAttribute('precipitation');
	if (cloudiness == "0" || cloudiness == "1" || cloudiness == "2" || precipitation == "10") var blueday = "Clear";
	else var blueday = "Grey";
	if (precipitation == "4" || precipitation == "5" || precipitation == "6" || precipitation == "7" || precipitation == "8") var blueday = "Grey";
		

	checkDayorNight(timeupdate, sunriseTm, sunsetTm, blueday);


	setOptionsSettings(parametrsArray);


	

	currentImg.src = "images/" + System.Gadget.Settings.read('Skin') + "/" + daytime + "/" + GismeteoGetCondImage(cloudiness,precipitation);

	if (daytime == "Night" && (img == "undefined.png" || img == "mostsunny.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";





	var current;

	if ((precipitation==4) || (precipitation==5))
 	{
		if (cloudiness==2) current = imghintArrayGismeteoShort[4];
		if (cloudiness==3) current = imghintArrayGismeteoShort[5];
		current = imghintArrayGismeteoShort[4];
	}

	if ((precipitation==6) || (precipitation==7))
	{
		if (cloudiness==2) current = imghintArrayGismeteoShort[6];
		if (cloudiness==3) current = imghintArrayGismeteoShort[7];
		current = imghintArrayGismeteoShort[6];
	}

	if (precipitation==8) 
	{
		current = imghintArrayGismeteoShort[8];		
	}

	if (precipitation==10) 
	{
		current = imghintArrayGismeteoShort[+(cloudiness)];			
	}
	
	CondSpan.innerText = current;

	

	METEONOVAFillForecast(Xml);

	MeteonovaFlag = 1;
	
	redrawGadget();
	
		
	
}




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




function GismeteoGetCondImage(cloudiness,precipitation)
{
	img="undefined.png";

	if (cloudiness == "0")
		img="clear.png";

	if (cloudiness == "1")
		img="mostsunny.png";

	if (cloudiness == "2")
		img="cloudy.png";

	if (cloudiness == "3")
		img="mostcloudy.png";

	if (precipitation == "5")
		img="rain.png";

	if (precipitation == "4")
		img="lightrain.png";

	if (precipitation == "6")
		img="lightsnow.png";

	if (precipitation == "7")
		img="snow.png";

	if (precipitation == "8")
		img="thunderstorm.png";
	

	//if (condition.search(/Пыль/i) > -1)
	//	img="dusthaze.png";

	//if ((condition.search(/Туман/i) > -1) || (condition.search(/Mist/i) > -1) || (condition.search(/Дымка/i) > -1)) 
	//	img="fog.png";

	//if (condition.search(/Дым/i) > -1)
	//	img="smoke.png";


	//if (condition == "6")
	//	img="partcloudy.png";


	//if (((condition.search(/Снег/i) > -1) || ((condition.search(/Дождь/i) > -1)) && (condition.search(/Shower/i) > -1)))
	//	img="rainandsnow.png";
	

	return img;
}




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




function METEONOVAFillForecast(XmlData)
{


var lng_DayWeek_Number = {
	"1": "Sunday",
	"2": "Monday",
	"3": "Tuesday",
	"4": "Wednesday",
	"5": "Thursday",
	"6": "Friday",
	"7": "Saturday"	
};

	var a = 1;
	totalFCDays = 0;
	
	var ForecastArray = XmlData.getElementsByTagName('FORECAST');


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

		var high = ForecastArray[i].getElementsByTagName('TEMPERATURE')[0].getAttribute('max');
		var low = ForecastArray[i].getElementsByTagName('TEMPERATURE')[0].getAttribute('min');

		if (System.Gadget.Settings.read("tunits") == "f") {high = (high*(9/5) + 32).toFixed(0); low = (low*(9/5) + 32).toFixed(0);}
		
		if (high != "")
			high+="°";
		else	high = "??°";
		if (low != "")
			low +="°";
		else	low = "??°";

	
		var day = ForecastArray[i].getAttribute('weekday');
		day = lng_DayOfWeek[lng_DayWeek_Number[day]];


	
		var date = ForecastArray[i].getAttribute('tod');
		date = periodsArrayGismeteo[date];

				
		var cloudiness = ForecastArray[i].getElementsByTagName('PHENOMENA')[0].getAttribute('cloudiness');
		var precipitation = ForecastArray[i].getElementsByTagName('PHENOMENA')[0].getAttribute('precipitation');


		var current;
		if ((precipitation==4) || (precipitation==5))
 		{
			if (cloudiness==2) current = imghintArrayGismeteo[4];
			if (cloudiness==3) current = imghintArrayGismeteo[5];
			current = imghintArrayGismeteo[4];
		}

		if ((precipitation==6) || (precipitation==7))
		{
			if (cloudiness==2) current = imghintArrayGismeteo[6];
			if (cloudiness==3) current = imghintArrayGismeteo[7];
			current = imghintArrayGismeteo[6];
		}

		if (precipitation==8) 
		{
			current = imghintArrayGismeteo[8];		
		}

		if (precipitation==10) 
		{
			current = imghintArrayGismeteo[+(cloudiness)];			
		}		



		
		var wind_max = parseInt(ForecastArray[i].getElementsByTagName('WIND')[0].getAttribute('max'));
		var wind_min = parseInt(ForecastArray[i].getElementsByTagName('WIND')[0].getAttribute('min'));
		var wind = ((wind_max + wind_min)/2).toFixed(0);
		if (wind == 'calm' || wind == '' || wind == 'NaN') wind = 0;
		if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed = (wind*0.277777778).toFixed(0); var SpeedUnits = "m/s";}
		if (System.Gadget.Settings.read("sunits") == "km") {windSpeed = wind; var SpeedUnits = "km/h";}
		if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed = (wind*0.621371192).toFixed(0); var SpeedUnits = "mph";}
		windSpeed = lng_Stats["wind"] + ": " + windSpeed + lng_Units[SpeedUnits];

		var humidity_max = parseInt(ForecastArray[i].getElementsByTagName('RELWET')[0].getAttribute('max'));
		var humidity_min = parseInt(ForecastArray[i].getElementsByTagName('RELWET')[0].getAttribute('min'));
		var humidity = ((humidity_max + humidity_min)/2).toFixed(0);
		if (humidity == 'NaN') humidity = "";
		else humidity = lng_Stats["humidity"] + ": " + humidity + "%";
		
						
		document.getElementById("dayName" + a).innerText = day; 
		document.getElementById("date" + a).innerText = date; 
		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/" + GismeteoGetCondImage(cloudiness,precipitation);
		if (System.Gadget.Settings.read('showFlyoutForecast') == "1") document.getElementById("dayImg" + a).alt = current + "; " + windSpeed + "; " + humidity;
		a++;
		totalFCDays++;
	}

}









function GettingTimeZone()
{
var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
return std_time_offset;
}



function decodeLang(str)
{ 
	str = str.substring(1); 
	var arr = str.split('%'); 
	var data = ''; 
	for(var i=0; i<arr.length; i++){ 
	data += String.fromCharCode(parseInt(arr[i],16) + 848);} 
	return data;
} 




