var areas = {Mallorca:"SPXX0061",Menorca:"SPXX0051",Ibiza:"SPXX0044",Formentera:"SPXX0044"};

for (var i in areas)
	get_weather(i,areas[i]);

$(document).ready(function() {

	$('#weather').hide();
	
	$('#map span.island').hover(function() {
		show_weather($(this).find('span').html());
	},function() {
		$('#weather').hide();
	});
	
});

var weathers = {
	
}

function get_weather(area,code) {
	
//	if (code != "SPXX0044") {
	if (false) {
		var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fuk.weather.com%2Fweather%2Ftoday-"+code+"%22%20and%20(%0A%20%20%20%20%20%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22current_box_icon%22%5D%2Fimg'%20or%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22current_box_temp%22%5D%2Fp')&format=json&diagnostics=true&callback=?";
				
		$.getJSON(url, function(data) {
		//	var str = data.query;
		
			
			if (data.query && data.query.results && data.query.results.img) {
				var $img = $('<p><img src="" /></p>').find('img');
				$img.attr('width',30).attr('src',data.query.results.img.src);
				
				var temp = data.query.results.p;
				temp = escape(temp);
				temp = temp.replace('%B0C','');
				
			
				weathers[area] = {temp:temp,image:$img};	
				if (area == "Mallorca") {
					show_weather("Mallorca");
					
				}
			
			}
			else {
				get_weather_old(area,code);
			}

		});
	}
	else {
		get_weather_old(area,code);
		
	}
	
	
}

function get_weather_old(area,code) {


	var yql_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%20=%20'"+code+"'&format=json&diagnostics=false&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?";
	$.getJSON(yql_url, function(data) {
	//	var str = data.query;
		
		channel = data.query.results.channel;
		
		var date = channel.lastBuildDate;
		
		var arr = date.split(' ');
		
		date = arr[arr.length - 3] + " " + arr[arr.length - 2] + "<br/>" + arr[arr.length - 1];
		
		var $img = $('<p>'+channel.item.description+'</p>').find('img');
		$img.attr('width',30);
		weathers[area] = {temp:ftoc(channel.item.condition.temp),image:$img,date:date};	
		
		if (area == "Mallorca") {
			show_weather("Mallorca");
				
		}
	});

}

function show_weather(area) {
	
	$('#map_title').html(area)
	$('#weather').show();
	var date = weathers[area].date;
	
	$('#weather_date').html("As of "+date);	
	var temp = weathers[area].temp;		
	$('#weather #weather-temp').html(temp);
	if (weathers[area].image) {
		var $img = weathers[area].image;		
		$('#weather #weather-img').html($img);
	}
		
}

function ftoc(num) {
	num = (((num-32) * 5) / 9);
	num = parseInt(num);
	return num;
}
