/**
 * wallpaper.JS
 * Wallpaper shows clock as well as weather(fed by Yahoo), takes one row of icon.
 * By Shitiz "Dragooon" Garg (mail[at]dragooon.net)
 * Redestribution not allowed without written permission
 * Idea from "Active Weather Wallpaper" found in Cydia store
 */

var temperature, humidity, code, city, low, high, condition = '';
var weatherInterval, clockInterval = null;
var current_time = new Date();
var in_progress = false;

// Weather Icon index
var MiniIcons =
[
	"tstorm3",		//0 	tornado
	"tstorm3",		//1 	tropical storm
	"tstorm3",		//2 	hurricane
	"tstorm3",		//3 	severe thunderstorms
	"tstorm2",		//4 	thunderstorms
	"sleet",		//5 	mixed rain and snow
	"sleet",		//6 	mixed rain and sleet
	"sleet",		//7 	mixed snow and sleet
	"sleet",		//8 	freezing drizzle
	"light_rain",		//9 	drizzle
	"sleet",		//10 	freezing rain
	"shower2",		//11 	showers
	"shower2",		//12 	showers
	"snow1",		//13 	snow flurries
	"snow2",		//14 	light snow showers
	"snow4",		//15 	blowing snow
	"snow4",		//16 	snow
	"hail",		//17 	hail
	"sleet",		//18 	sleet
	"mist",		//19 	dust
	"fog",		//20 	foggy
	"fog",		//21 	haze
	"fog",		//22 	smoky
	"cloudy1",		//23 	blustery
	"cloudy1",		//24 	windy
	"overcast",		//25 	cold
	"cloudy1",		//26 	cloudy
	"cloudy4_night",		//27 	mostly cloudy (night)
	"cloudy4",		//28 	mostly cloudy (day)
	"cloudy2_night",		//29 	partly cloudy (night)
	"cloudy2",		//30 	partly cloudy (day)
	"sunny_night",		//31 	clear (night)
	"sunny",		//32 	sunny
	"mist_night",		//33 	fair (night)
	"mist",		//34 	fair (day)
	"hail",		//35 	mixed rain and hail
	"sunny",		//36 	hot
	"tstorm1",		//37 	isolated thunderstorms
	"tstorm2",		//38 	scattered thunderstorms
	"tstorm2",		//39 	scattered thunderstorms
	"tstorm2",		//40 	scattered showers
	"snow5",		//41 	heavy snow
	"snow3",		//42 	scattered snow showers
	"snow5",		//43 	heavy snow
	"cloudy1",		//44 	partly cloudy
	"storm1",		//45 	thundershowers
	"snow2",		//46 	snow showers
	"tstorm1",		//47 	isolated thundershowers
	"dunno",		//3200 	not available

];

// OnLoad event, handles the initialisation of clock/weather
var windowOnLoad = function()
{
	// Disable BG?
	if (!enableBG)
		document.getElementById('bg_el').style.display = 'none';

	// Set the date and the interval
	setClock();
	clockIntervalHandler = setInterval('setClock()', 1000);

	// Set the weather the interval
	weatherIntervalHandler = setInterval('updateWeather()', 1000);
};

// Sets the clock
var setClock = function()
{
	var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
	var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	var current_time = new Date();

	// Get the date string
	var date_string = days[current_time.getDay()] + ', ' + current_time.getDate() + ' ' + months[current_time.getMonth()];

	var hours = current_time.getHours();
	var minutes = current_time.getMinutes();
	if (ampm_format === true)
	{
		var is_pm = hours > 12;
		hours = is_pm ? hours - 12 : hours;

		var am_pm = document.createElement('span');
		am_pm.innerHTML = is_pm ? 'PM' : 'AM';
		am_pm.style.fontSize = '10px';
	}


}

// Formats Temperature
var formatTemp = function(temp)
{
	return temp + (isCelsius ? 'ºC' : 'ºF');
}

// Sets the weather
var setWeather = function()
{
	if (in_progress)
		return false;

	in_progress = true;

	updateWeatherData('Request Weather...', '', '', '', '', '', 'dunno.png', null, true);

	// Do a request from Yahoo!'s weather
	var xml_request = new XMLHttpRequest();
	xml_request.open('GET', 'http://weather.yahooapis.com/forecastrss?u=' + (isCelsius ? 'c' : 'f') + '&w=' + locale + '&' + new Date().getTime());
	xml_request.onload = function(e)
	{
		in_progress = false;

		if (xml_request.status != 200)
		{
			if (typeof(city) == 'undefined' || code == '')
				return false;

			updateWeatherData(city, temperature, humidity, low, high, condition, MiniIcons[code] + '.png', current_time, true);
			document.getElementById('update').style.color = 'red';
			return true;
		}

		document.getElementById('update').style.color = '';

		weatherRequestHandler(e, xml_request)
	};
	xml_request.onreadystatechange = function(e)
	{
		return xml_request.onload();
	}
	xml_request.overrideMimeType('text/xml');
	xml_request.setRequestHeader('Cache-control', 'no-cache');
	xml_request.send();
}

var weatherUpdateFailed = function()
{

}

// Parses a weather request's response
var weatherRequestHandler = function(event, request)
{
	var root = request.responseXML.getElementsByTagName('rss')[0].getElementsByTagName('channel')[0];
	current_time = new Date(root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue.substr(0, root.getElementsByTagName('lastBuildDate')[0].firstChild.nodeValue.length - 4));

	// Get the temperature, humidity, city name, 
	temperature = root.getElementsByTagName('item')[0].getElementsByTagName('condition')[0].getAttribute('temp');
	humidity = root.getElementsByTagName('atmosphere')[0].getAttribute('humidity');
	city = root.getElementsByTagName('location')[0].getAttribute('city');
	low = root.getElementsByTagName('item')[0].getElementsByTagName('forecast')[0].getAttribute('low');
	high = root.getElementsByTagName('item')[0].getElementsByTagName('forecast')[0].getAttribute('high');
	condition = root.getElementsByTagName('item')[0].getElementsByTagName('condition')[0].getAttribute('text');
	code = root.getElementsByTagName('item')[0].getElementsByTagName('condition')[0].getAttribute('code');

	if (MiniIcons[code].indexOf('%type%') > 0)
	{
		// Get the current time
		var current_time2 = new Date();
		var sunset = parseTimeString(root.getElementsByTagName('astronomy')[0].getAttribute('sunset'));
		var sunrise = parseTimeString(root.getElementsByTagName('astronomy')[0].getAttribute('sunrise'));

		// Is it day?
		var sufix = 'night';
		if (current_time2.getHours() > sunrise[0] && current_time2.getHours() < sunset[0])
			sufix = 'day';

		MiniIcons[code] = MiniIcons[code].replace('%type%', sufix);
	}

	// Update the data
	updateWeatherData(city, temperature, humidity, low, high, condition, MiniIcons[code] + '.png', current_time);

}

// Updates a weather's data
var updateWeatherData = function(city, temperature, humidity, low, high, condition, icon, current_time, no_last_update)
{
	// Set the information
	document.getElementById('city').innerHTML = ' '+city;
	document.getElementById('temp').innerHTML = 'Temp: '+formatTemp(temperature);
	document.getElementById('humidity').innerHTML = 'Humidity: '+humidity + '%';
	document.getElementById('forecast').innerHTML = 'Temp From: '+formatTemp(low)+ '-' +formatTemp(high) ;
	document.getElementById('desc').innerHTML =  condition;
	document.getElementById('bgimg').src = 'joca/' + icon;

	if (current_time != null)
		document.getElementById('update').innerHTML = '' + (current_time.getHours() > 12 ? current_time.getHours() - 12 : current_time.getHours()) + ':' + (current_time.getMinutes() < 10 ? '0' + current_time.getMinutes() : current_time.getMinutes()) + ' ' + (current_time.getHours() > 12 ? 'PM' : 'AM');

	document.getElementById('last_update').innerHTML = new Date().getTime() + (no_last_update == null ? 0 : (failedInterval * 1000) - (updateInterval * 1000));
}

// Handles periodical check for the update of weather data
var updateWeather = function()
{
	if (document.getElementById('last_update').innerHTML.length == 0)
		return setWeather();

	var current_time = parseInt(new Date().getTime());
	var last_time = parseInt(document.getElementById('last_update').innerText);
	var max_diff = updateInterval * 1000;

	if (current_time - last_time > max_diff)
		return setWeather();

	return true;
}

// Parses a string in format hh:mm a/p and returns the time and minute in 24 hour format
function parseTimeString(string)
{
	var parts = string.split(':');
	var hour = parseInt(parts[0]);
	parts = parts[1].split(' ');
	var minute = parseInt(parts[0]);

	// We got PM?
	if (parts[1].toLowerCase() == 'pm' && hour != 12)
		hour += 12;

	return [hour, minute];
}
window.onload = windowOnLoad;