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


function parseForecastYandex(Xml)
{
	updateBar.style.display = "none";

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

	var fact = node(Xml, 'fact');
	var locData = node(Xml, 'forecast');
	
	
	var locName = locData.getAttribute('city') + ", " + locData.getAttribute('country');
	System.Gadget.Settings.write("YAlastSearch", locName);
	setLocation(locName);


	var current = value(fact, 'weather_type_short');
	current = current.replace(current.charAt(0), (current.charAt(0)).toUpperCase())
	

	var timeupdate = value(fact, 'observation_time');								//time last update
	timeupdate = timeupdate.slice(timeupdate.lastIndexOf('T') + 1, timeupdate.lastIndexOf(':')) ;
	if ((System.Gadget.Settings.read("showLastTimeUpdate")) != 1 || timeupdate == "N/A") TimeLastUpdate.innerText = "";
	else TimeLastUpdate.innerText = timeupdate;
	
	
	time = new Date().getHours() +":" + new Date().getMinutes();

	


	var number = value(fact, 'image');
	if(number.substr(0,1) == 'n') {
		number = number.substr(1);
		daytime = "Night";
		daytime_back = "";
		currentImgMoon.style.display = "block";
		}
	else daytime = "Day";

	if (daytime == "Day") 
	{
		
		if (number == "6" || number == "7" || number == "14")
			{
				daytime_back = "blue";
			}
		else
			{
				daytime_back = "grey";
			}
		currentImg.style.display = "block";
		currentImgMoon.style.display = "none";
	}

	
	var temp = value(fact, 'temperature');										//actual temperature
	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 == 'N/A') temp = lng_nodata;
	TempSpan.innerHTML = temp + "&deg;" + lng_Units[TemperatureUnits];


	var wind = value(fact, 'wind_speed');
	if (wind == 'calm' || wind == '') wind = 0;
	if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed = Math.round(wind); var SpeedUnits = "m/s";}
	if (System.Gadget.Settings.read("sunits") == "km") {windSpeed = (wind*3.6).toFixed(0); var SpeedUnits = "km/h";}
	if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed = (wind*2.23693629).toFixed(0); var SpeedUnits = "mph";}

	var windDirection = (value(fact, 'wind_direction')).toUpperCase(); 
	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 == '') WindSpan = lng_nodata;
	parametrsArray.push({"name":"wind", "capt":WindCapt, "span":WindSpan});

	
	var humidity = value(fact, 'humidity');
	HumidityCapt = lng_Stats["humidity"];
	HumiditySpan = humidity + "%";
	if (humidity == 'N/A') HumiditySpan = lng_nodata;
	parametrsArray.push({"name":"humidity", "capt":HumidityCapt, "span":HumiditySpan});


	var pressure = value(fact, 'pressure');
	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 == 'N/A') PressureSpan = lng_nodata;
	parametrsArray.push({"name":"pressure", "capt":PressureCapt, "span":PressureSpan});


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


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


	var day1 = node(Xml, 'day');
	var sunriseTm = value(day1, 'sunrise');
	var sunsetTm = value(day1, 'sunset');

	SunriseCapt = lng_Stats["sunrise"];
	SunriseSpan = sunriseTm;
	if (sunriseTm == 'N/A') SunriseSpan = lng_nodata;
	parametrsArray.push({"name":"sunrise", "capt":SunriseCapt, "span":SunriseSpan});

	SunsetCapt = lng_Stats["sunset"];
	SunsetSpan = sunsetTm;
	if (sunsetTm == 'N/A') SunsetSpan = lng_nodata;
	parametrsArray.push({"name":"sunset", "capt":SunsetCapt, "span":SunsetSpan});

	
	var watertemp = value(fact, 'water_temperature');										//actual temperature
	if (System.Gadget.Settings.read("tunits") == "m") {var TemperatureUnits = "C";}
	if (System.Gadget.Settings.read("tunits") == "f") {watertemp = (watertemp*(9/5) + 32).toFixed(0); var TemperatureUnits = "F";}
	if (watertemp == 'N/A' || watertemp == 'NaN') watertemp = lng_nodata;
	var WatertempCapt = lng_Stats["watertemp"];
	var WatertempSpan = watertemp + "&deg;" + lng_Units[TemperatureUnits];
	if (watertemp == null) WatertempSpan = lng_nodata;
	parametrsArray.push({"name":"watertemp", "capt":WatertempCapt, "span":WatertempSpan});
	

	setOptionsSettings(parametrsArray);

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

	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 currentdate = day1.getAttribute('date');
		currentdate = currentdate.split('-');
		var moonphase = computePhaseOfMoon(currentdate[0]*1, currentdate[1]*1, currentdate[2]*1);
		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.innerHTML = current;



	//alert module
	var alert = value(Xml, 'generated_alert');
	if (alert) document.getElementById("CondSpan").title = alert;

	

	YAFillForecast(Xml);

	
	redrawGadget();
	
		
	
}




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




function YandexGetCondImage(condition)
{
	img="undefined.png";
	
	if (condition == "5" || condition == "11" || condition == "15" || condition == "16")
		img="cloudy.png";

	if (condition == "1" || condition == "3" || condition == "4")
		img="rain.png";

	if (condition == "7")
		img="clear.png";

	if ((condition.search(/Малооблачно/i) > -1 || condition.search(/Partly Sunny/i) > -1))
		img="mostsunny.png";

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

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

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

	if (condition == "2" || condition == "17")
		img="snow.png";

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

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

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

	if ((condition.search(/неб. дождь/i) > -1) || (condition.search(/небольшой дождь/i) > -1) || condition == "9" || condition == "10")
		img="lightrain.png";

	if (((condition.search(/Снег/i) > -1) || ((condition.search(/Дождь/i) > -1)) && (condition.search(/Shower/i) > -1)))
		img="rainandsnow.png";
	
	if (condition.search(/Небольшой снег/i) > -1 || condition.search(/неб. снег/i) > -1 || condition == "12" || condition == "13")
		img="lightsnow.png";

	return img;
}




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




function YAFillForecast(XmlData)
{

var lng_Month_Number = {
	"01": "January",
	"02": "February",
	"03": "March",
	"04": "April",
	"05": "May",
	"06": "June",
	"07": "July",
	"08": "August",
	"09": "September",
	"10": "October",
	"11": "November",
	"12": "December"
};


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

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

	if (a >= 10) break;

	if ((System.Gadget.Settings.read("showForecastToday")) != 1 || DateToMinutesConvert(time) >= 900)
			{
				if (i == 0) i++;
				if (System.Gadget.Settings.read("showDayNameForecast") == 0) dayName1.innerText = lng_Tomorrow;
			}
 		else
			{
				if (System.Gadget.Settings.read("showDayNameForecast") == 0) {
					dayName1.innerText = lng_Today;
					dayName2.innerText = lng_Tomorrow;
				}
			}
	

		var ForecastDayPartArray = ForecastArray[i].getElementsByTagName('day_part');
		for (var n = 0; n < ForecastDayPartArray.length; n++) {
			if (ForecastDayPartArray[n].getAttribute('typeid') == 5) var ForecastDay = ForecastDayPartArray[n];
			if (ForecastDayPartArray[n].getAttribute('typeid') == 6) var ForecastNight = ForecastDayPartArray[n];
		}

		var high = value(ForecastDay, 'temperature');
		var low = value(ForecastNight, 'temperature');
	
		if (System.Gadget.Settings.read("tunits") == "f") {high = (high*(9/5) + 32).toFixed(0); low = (low*(9/5) + 32).toFixed(0);}
		
		if (high != "N/A")
			high+="°";
		else	high = "??°";
		if (low != "N/A")
			low +="°";
		else	low = "??°";


		var day = determineDay(ForecastArray[i].getAttribute('date'));
		day = lng_DayOfWeek[day];
		
		var date_str = ForecastArray[i].getAttribute('date');
		var date = date_str.slice(date_str.lastIndexOf("-") + 1, date_str.length);
		var month = date_str.slice(date_str.indexOf("-") + 1, date_str.lastIndexOf("-"));
		date = date + " " + lng_Month_full[lng_Month_Number[month]];

				
		var condition = value(ForecastDay, 'weather_type');
		var condition_short = value(ForecastDay, 'weather_type_short');

		var image = value(ForecastDay, 'image');

		var windSpeed = value(ForecastDay, 'wind_speed');
		if (windSpeed == 'calm' || windSpeed == 'N/A' || !windSpeed) windSpeed = 0;
		windSpeed = (windSpeed*1).toFixed(0);
		if (System.Gadget.Settings.read("sunits") == "ms") {windSpeed = windSpeed; var SpeedUnits = "m/s";}
		if (System.Gadget.Settings.read("sunits") == "km") {windSpeed = (windSpeed*3.6).toFixed(0); var SpeedUnits = "km/h";}
		if (System.Gadget.Settings.read("sunits") == "mp") {windSpeed = (windSpeed*2.23693629).toFixed(0); var SpeedUnits = "mph";}
		windSpeed = lng_Stats["wind"] + " " + windSpeed + lng_Units[SpeedUnits];

		var humidity = value(ForecastDay, 'humidity');
		if (humidity == '') 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/" + YandexGetCondImage(image);
		if (System.Gadget.Settings.read('showFlyoutForecast') == "1") document.getElementById("dayImg" + a).alt = condition + "; " + windSpeed + "; " + humidity;
		a++;
		totalFCDays++;
	}

}






function node(x, name)
{
	result = x.getElementsByTagName(name)[0];
	return result;
};


function value(x, name)
{
	var x = node(x, name);
	return x ? x.firstChild.nodeValue : null;
}



function determineDay(parStr)
{
	var yyyy = parStr.substring(0, parStr.indexOf("-"));
	var mm = parStr.substring(parStr.indexOf("-") + 1, parStr.lastIndexOf("-"));
	mm = mm*1 - 1;
	var dd = parStr.substring(parStr.lastIndexOf("-") + 1, parStr.length);


  d=new Date();
  d.setDate(1);

  d.setYear(yyyy);
  d.setMonth(mm);
  d.setDate(dd);

  d.setHours(12);

  ww=d.getDay();
  if (ww==0) wDay="Sunday";
  if (ww==1) wDay="Monday";
  if (ww==2) wDay="Tuesday";
  if (ww==3) wDay="Wednesday";
  if (ww==4) wDay="Thursday";
  if (ww==5) wDay="Friday";
  if (ww==6) wDay="Saturday";

  return wDay;
}



