/** All the stuff for handling weather. */
var weatherTabs = {

	/** Postcodes defaulting to 6000. */
	WA_OFFSETS : [-480, -540],

	/** Displays forecast information */
	displayForecast : function(forecast) {

		/** Day mappings */
		var dmap = {
			'Friday' : 'Fri',
			'Saturday' : 'Sat',
			'Sunday' : 'Sun',
			'Monday' : 'Mon',
			'Tuesday' : 'Tues',
			'Wednesday' : 'Wed',
			'Thursday' : 'Thurs'
		};

		/** Save forcast info the page. */
		var c = '';
		$.each(forecast.slice(1, 7), function(index, e) {
			c += "<div class='week_weather_day'>";
			c += "<p>";
			c += "<img src='/img/customers/weather/small/" + e.icon.filename + "'/>";
			c += "<br/>";
			c += dmap[e.day_name];
			c += "<br/>";
			c += "<span>";
			c += e.temp_min_c.content + "&deg;/" + e.temp_max_c.content + "&deg;"
			c += "</span>";
			c += "</p>";
			c += "</div>";
		});

		jQuery('#week_weather_forecast').html(c);
		jQuery('#weather').show();
	},

	/** Displays condition information */
	displayConditions : function(conditions) {
		try {
			/* Populate conditions */
			var place = conditions.place;
			conditions = conditions.conditions;
			
			$("#postcode").attr("value", 'Enter postcode');
			$("#weather_place").text(place);

			var today = conditions.forecasts.forecast[0];
			jQuery('#weather_todays_icon').attr('src', '/img/customers/weather/large/' + today.icon.filename);

			var c = today.temp_min_c.content + "&deg;/" + today.temp_max_c.content + "&deg;"
			jQuery('#weather_todays_temp').html(c);

			c = conditions.temp_c.content + "&deg;";
			jQuery('#weather_temp').html(c);

			c = conditions.feels_like_c.content + "&deg;";
			jQuery('#weather_feels_like').html(c);

			c = conditions.rh.content + "%";
			jQuery('#weather_humidity').html(c);

			c = conditions.rainfall_mm.content + conditions.rainfall_mm.units;
			jQuery('#weather_rainfall').html(c);

			// Some places don't have wind information. :(
			if (conditions.wind_speed_kph.content != undefined) {
				c = conditions.wind_dir_compass + ' ' + conditions.wind_speed_kph.content;
				jQuery('#weather_wind').html(c);
			}
			else
				jQuery('#weather_wind').html('');

			/* Populate forecast */
			weatherTabs.displayForecast(conditions.forecasts.forecast);
			$("#weather_error").hide();
		}
		catch(e) {
			jQuery('#weather').show();
		}
	},

	/** Updates the weather with a new postcode. */
	getWeather : function(postcode) {
		if (weatherTabs.quicksel != null) 
			weatherTabs.quicksel.hide();
		var no_postcode = false;
		if (!postcode) {
			postcode = document.getElementById("postcode").value;
		}


		if (!postcode || postcode == undefined || postcode == "Enter postcode") {
//postcode = isWA() ? "6000" : "2000"; //call to isWA is buggy. Commented out.
           if ($.profile("postcode") == undefined || $.profile("postcode") == "Enter postcode"){

                postcode = "2000"; //hardcoded to Sydney's area code: 2000 
			    no_postcode = true;
            } else {
                postcode = $.profile("postcode");		
            }
        }
		$.profile("postcode", postcode);
    	$("#postcode").attr("value", postcode);

		/* Map full name to postcode if possible. */
		var pcMap = {
			'Perth' : '6000',
			'Darwin' : '0800',
			'Canberra' : '2600',
			'Melbourne' : '3000',
			'Adelaide' : '5000',
			'Sydney' : '2000',
			'Brisbane' : '4000',
			'Hobart' : '7000'
		};
		if (pcMap[postcode] !== undefined)
			postcode = pcMap[postcode];

		$.ajax({
			type: "GET",
			url: "/customers/weather/conditions.cgi",
			dataType: "json",
			data: { postcode: postcode },
			timeout: 5000,
			success: weatherTabs.displayConditions,
			error: function(xhr, status, e) { 
				var resp;
				if (status == "timeout") {
                        $("#current_weather_layout").hide();
                        $("#new_weather_layout").hide();
                        $("#weather_error").hide();
                        $("#week_weather_layout").hide();
                        $("#weather_timeout").show();
				}
				else { 
					eval("resp = " + xhr.responseText); 
					$("#weather_error_message").text(resp.message); 
					$("#weather_error").show();
				}
			}
		});

		$.ajax({
			type: "GET",
			url: "/scripts/time.cgi",
			dataType: "json",
			success: weatherTabs.updateTime
		});
	    $("#postcode").attr("value", postcode);
    },

	/** Regional time data, loaded via ajax */
	current_time : {},

	/** Ajax callback for having loaded time data */
	updateTime : function(data) {
		weatherTabs.current_time = data;
		postcode = document.getElementById("postcode").value;

		/* Map full name to subname if possible. */
		var pcMap = {
			'Perth' : 'wa',
			'Darwin' : 'nt',
			'Canberra' : 'act',
			'Melbourne' : 'vic',
			'Adelaide' : 'sa',
			'Sydney' : 'nsw',
			'Brisbane' : 'qld',
			'Hobart' : 'tas'
		};
		if (pcMap[postcode] !== undefined) {
			postcode = pcMap[postcode];
		}

		/* Map postcode to state, if unknown */
		if (data[postcode] === undefined) {
			postcode = weatherTabs.postcodeToState(postcode);
			if (postcode == null)
				postcode = "wa";
		}

		jQuery("#weather_date").text(data[postcode].date);
		jQuery("#weather_time").text(data[postcode].time + ' ' + data[postcode].zone);
	},

	/** Cunningly maps postcodes to states. */
	'postcodeToState' : function(postcode) {
		var data = {
			'nsw' : [
				{ 'lower' : 1000, 'upper' : 1999 },
				{ 'lower' : 2000, 'upper' : 2599 },
				{ 'lower' : 2619, 'upper' : 2898 },
				{ 'lower' : 2921, 'upper' : 2999 }
			],
			'act' : [
				{ 'lower' : 200, 'upper' : 299 },
				{ 'lower' : 2600, 'upper' : 2618 },
				{ 'lower' : 2900, 'upper' : 2920 }
			],
			'vic' : [
				{ 'lower' : 3000, 'upper' : 3999 },
				{ 'lower' : 8000, 'upper' : 8999 }
			],
			'qld' : [
				{ 'lower' : 4000, 'upper' : 4999 },
				{ 'lower' : 9000, 'upper' : 9999 }
			],
			'sa' : [
				{ 'lower' : 5000, 'upper' : 5799 },
				{ 'lower' : 5800, 'upper' : 5999 }
			],
			'wa' : [
				{ 'lower' : 6000, 'upper' : 6797 },
				{ 'lower' : 6800, 'upper' : 6999 }
			],
			'tas' : [
				{ 'lower' : 7000, 'upper' : 7799 },
				{ 'lower' : 7800, 'upper' : 7999 }
			],
			'nt' : [
				{ 'lower' : 800, 'upper' : 899 },
				{ 'lower' : 900, 'upper' : 999 }
			]
		};

		var rtn = null;
		var context = '';
		for (var key in data) {
			context = key;
			for (var node in data[key]) {
				var block = data[key][node];
				if ((postcode >= block.lower) && (postcode <= block.upper)) {
					rtn = context;
					break;
				}
			}
		}

		return(rtn);
	},

	isWA : function() {
		var offset = (new Date()).getTimezoneOffset();
		return $.inArray(offset, WA_OFFSETS);
	},

	/** Currently open tab */
	'current' : 'forecast',

	/** Use this to set the tab */
	'set' : function(tab) {
		if (weatherTabs.current != tab) {
			jQuery('#weather_tabs_' + weatherTabs.current).removeClass('current');
			jQuery('#weather_tabs_' + tab).addClass('current');
			jQuery('#weather_tabs_' + weatherTabs.current + "_content").hide();
			jQuery('#weather_tabs_' + tab + "_content").show();
			if (!weatherTabs.setLoaded) {
				jQuery('#weather_tabs_' + tab + "_content").load('/customers/tabs/satellite.html');
				weatherTabs.setLoaded = true;
			}
			weatherTabs.current = tab; 
		}
	},

	/** Has the satellite tab been loaded already? */
	satLoaded : false,

	/** Quick sel object... */
	quicksel : null,

	/** Show the weather drop down. */
	quickSelShow : function() {
		if (weatherTabs.quicksel == null) {
			weatherTabs.quicksel = jQuery(document.createElement('div'));
			weatherTabs.quicksel.attr('id', 'weather_quicksel');

			var set = [
				'Melbourne', 
				'Sydney', 
				'Perth', 
				'Brisbane', 
				'Darwin', 
				'Adelaide', 
				'Canberra',
				'Hobart'
			];
			var html = '';
			for (var i in set) {
				html += '<a href="#" onclick="try {weatherTabs.getWeather(\'' + set[i] + '\');}catch(e){} weatherTabs.quicksel.hide(); return(false);">' + set[i] + "</a>";
			}
			weatherTabs.quicksel.html(html);

			jQuery('#weather_postcode_form').append(weatherTabs.quicksel);
		}
		weatherTabs.quicksel.show();
	}, 
   
    /* Empties the textbox for someone to enter the postcode */ 
    ClearPostCode : function() {  
        if ($("#postcode").val() == "Enter postcode")
          $("#postcode").val('');
   },

  /* Resets the textbox value if it's empty   */
   ResetPostCode : function() {
    
        if ($("#postcode").val().length == 0)
            $("#postcode").attr("value", "Enter postcode");
  },

	/** Starts, binds events. */
	__init__ : function() {
		jQuery('#postcode').click(function() { weatherTabs.ClearPostCode();  weatherTabs.quickSelShow(); });
		jQuery('#postcode').blur(function() {weatherTabs.ResetPostCode();  setTimeout(function() { weatherTabs.quicksel.hide(); }, 1000)});
	}
};

/** Start weather tabs */
jQuery(function() {
	weatherTabs.__init__();
}
);
