// Retrieve data from Wunderground XML webservice, a proxy PHP is necesary bacause security browsers issues
// The service for current conditions is located in:
// http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=City,Country_code
(function($){
	$.fn.weather = function (){
		// Initialize component
		var $this = $(this);
		var data;
		var baseURLWebService = "http://www.dragnux.com/webservices";
		// load css
		var head = document.getElementsByTagName("head")[0];
		$(document.createElement("link"))
		    .attr({type: "text/css", href: baseURLWebService+"/weather/styles/weather.css", rel: "stylesheet", media:"screen"})
		    .appendTo(head);
		if($.browser.msie && $.browser.version == '6.0'){
			$(document.createElement("link"))
			    .attr({type: "text/css", href: baseURLWebService+"/weather/styles/weather_icons_ie6.css", rel: "stylesheet", media:"screen"})
			    .appendTo(head);
			
		}
		else{
			$(document.createElement("link"))
			    .attr({type: "text/css", href: baseURLWebService+"/weather/styles/weather_icons.css", rel: "stylesheet", media:"screen"})
			    .appendTo(head);
		}
		// load GeoIP data
		// More info at: http://www.maxmind.com/app/ip-location
		$.ajax({
			type: "GET",
			url: "http://j.maxmind.com/app/geoip.js",
			success: function(data,textStatus){
				loadWebService(baseURLWebService+"/wunderground.php?lang="+weather_lang+"&type=currentConditions|forecast&key=query&query="+geoip_city()+","+geoip_country_code())
			},
			error:function(XMLHttpRequest,textStatus,errorThrown){
				/*
					TODO thrown error 
				*/
			},
			dataType: "script",
			cache:true
		});			
		loadWebService = function (URLWebService){
			$.ajax({
				beforeSend: function(xhrObj){
					xhrObj.setRequestHeader("Content-Type","application/json");
					xhrObj.setRequestHeader("Accept","application/json");
				},
				type: "GET",
				data: "referer="+encodeURIComponent(window.location.href),
				url: URLWebService,
				success: function(data,textStatus){
					createWidget(data);
				},
				error:function(XMLHttpRequest,textStatus,errorThrown){
					/*
						TODO thrown error
					*/
				},
				dataType:"jsonp",
				cache:false
			});			
		};
		createWidget = function(o){
			data = o.response;
			// $this.html(data);
			$this.css('background','none').html('<div class="wrapper-weather">'+data+'</div>');
			$this.show();
			$this.find('#show-forecast').click(function(){
				$this.find('.wrapper-weather').animate({
					marginLeft:'-210px'
				},1000);
			});
			$this.find('#show-current-conditions').click(function(){
				$this.find('.wrapper-weather').animate({
					marginLeft:'0px'
				},1000);
			});
		};
		
	}
	$("#weather-info").weather();
})(jQuery);

