jQuery(document).ready(function() {

	// Initialise the navigation links
	jQuery(".BBCWeatherWidget a.Location").each(function() {
		jQuery(this).removeClass('hidden');
	});
	jQuery(".BBCWeatherWidget span.divider").each(function() {
		jQuery(this).removeClass('hidden');
	});

	// Setup the click call back on the location nav
	jQuery(".BBCWeatherWidget a.Location").click(function() {
		// Get the Location-{num} class of this item
		var tagClasses = jQuery(this).attr('class');
		var classArray = tagClasses.split(' ');
		for( var c = 0; c < classArray.length; c++) {
			if (classArray[c].substring(9,0) == "Location-") {
				//First reset everything
				jQuery(".BBCWeatherWidget div.Location").addClass("hidden");
				jQuery(".BBCWeatherWidget a.current").removeClass("current");
				// Find the forecast with this class
				jQuery(".BBCWeatherWidget div.Location."+classArray[c]).toggleClass("hidden");
				jQuery(".BBCWeatherWidget a."+classArray[c]).toggleClass("current");
			}
		}
		return false;
	});
	
	// Setup the click callback for the mode switcher
	jQuery(".BBCWeatherWidget .modeSwitch a").click(function() {
		var c = jQuery(this).attr("class");
		var mode = c.substring(5);
		if (mode == "Forecasts") {
			jQuery(".BBCWeatherWidget .Forecasts").removeClass("hidden");
			jQuery(".BBCWeatherWidget .Observation").addClass("hidden");
			jQuery(".BBCWeatherWidget .mode-Forecasts").addClass("hidden");
			jQuery(".BBCWeatherWidget .mode-Observation").removeClass("hidden");
		} else {
			jQuery(".BBCWeatherWidget .Observation").removeClass("hidden");
			jQuery(".BBCWeatherWidget .Forecasts").addClass("hidden");
			jQuery(".BBCWeatherWidget .mode-Observation").addClass("hidden");
			jQuery(".BBCWeatherWidget .mode-Forecasts").removeClass("hidden");
		}
		return false;
	});
	
	// Toggle which forecast day is being shown on all locations
	function updateForecast(pos,modifier) {
		jQuery(".Forecast.Pos-"+pos).toggleClass("hidden");
		jQuery(".Forecast.Pos-"+(pos+modifier)).toggleClass("hidden");
	}
	
	// Extract the current forcast position number from its class
	function getCurrentPos(obj) {	
		var tagClasses = jQuery(obj).attr('class');
		var classArray = tagClasses.split(' ');
		for( var c = 0; c < classArray.length; c++) {
			if (classArray[c].substring(0,5) == "From-") {
				return classArray[c].substring(5,6);
			}
		}
	}
	
	// Setup the call back on the next forcast links
	jQuery(".BBCWeatherWidget a.Next").click(function() {
		updateForecast(parseInt(getCurrentPos(this)),1);
		return false;
	});
	
	// Setup the call back on the previous forcast links
	jQuery(".BBCWeatherWidget a.Previous").click(function() {
		updateForecast(parseInt(getCurrentPos(this)),-1);
		return false;
	});
	
});
