/******************************************************************************
 * FILE: element_table_jquery.js
 * AUTHOR: mcarroll
 * CREATED: June 2009
 *
 * This file contains the majority of javascript functions used in the forecast explorer pages
 *
 * This file is used in combination with the varants set in config.js
 *
 * Refer to http://comms.bom.gov.au/twiki/bin/view/AMDISS/ForecastExplorer for
 * more information
 *
 * Conventions: UPPERCASE = varant lowercase/camelcase: variables
 ******************************************************************************/

/**
 * attached to the onchange event for the Period Drop down on the daily view
 * Called when user changes the selected period via the period drop down on the daily view
 */
function selectPeriod() {
	// period number is period drop down selected index + 1
	var period = document.getElementById(PERIOD_DROP_DOWN_ID).selectedIndex + 1;
	updateElementPeriodTimeslotAndCookie(CURRENT_ELEMENT, period, CURRENT_TIMESLOT);
	dailyViewSwitchPeriod();
	showCurrentElement();
}

/**
 * Shows the selected element/period/timeslot image
 * Also calls highlight element and sets the cookie
 * If the 'selected' table cell doesn't have an image associated (6 hourly > 3 days out) show no data available image
 * (this occurs when user using the +/- 12 hours buttons where it stays on current element/timeslot but changes period)
 */
function showCurrentElement() {
	updateImages();
	updateSelection();
	createCookie(SHOW_ELEMENT_COOKIE_NAME, buildShowElementCookieValue(), COOKIE_EXPIRE);
}

/**
 * attached on click event for links in element rollover table
 * @param element the weather element
 * @param period the period number
 * @timeslot the timeslot in the period
 */
function showElement(element,period,timeslot) {
	updateElementPeriodTimeslotAndCookie(element, period, timeslot);
	showCurrentElement();
}

/**
 * On a daily view page, switch the period shown in the element rollover table
 * This is done by hiding currently shown tbody and showing the tbody for the newly selected period
 */
function dailyViewSwitchPeriod() {
	$("#" + DOM_ID_PREFIX + PREVIOUS_PERIOD).hide();
	$("#" + DOM_ID_PREFIX + CURRENT_PERIOD).show();
}

function weeklyViewSwitch() {
	var index = getIndexOfWeatherElement(CURRENT_ELEMENT);
	var set = parseInt(index / numberColumnsShownAtOneTime) + 1;
	showSet(set);
}

function changePeriodDiv(periodNumber) {
	if (CURRENT_PERIOD != periodNumber) {
		$("#" + DOM_ID_PREFIX + CURRENT_PERIOD).hide();
		CURRENT_PERIOD = periodNumber;
		$("#" + DOM_ID_PREFIX + CURRENT_PERIOD).show();
	}
}

/**
 * Determines the thumbnail imagefile to show and sets the overview image to it.
 * If it is a no data available timeslot, shows the no data available thumbnail image
 */
function showOverviewThumbnail(id) {
	var imgsrc = '';
	if (id == NO_DATA_AVAILABLE_IMAGE) {
		imgsrc = NO_DATA_AVAILABLE_THUMBNAIL_IMAGE;
	}
	else if (id == NO_DATA_AVAILABLE_FFDI_IMAGE) {
		imgsrc = NO_DATA_AVAILABLE_FFDI_THUMBNAIL_IMAGE;
	}
	else {
		imgsrc = getThumbnailImageName(id);
	}

	$("#" + OVERVIEW_PIC_ID).attr('src', imgsrc);

}

/**
 * returns the full image name (path) for the image id (e.g. id = MaxT1)
 */
function getFullImageName(id) {

	var fullImageName = IMAGES_DIR + '/' + sector + '/' + id + '_'
					+ sector + IMAGE_EXTENSION;

	if (gfeForecastType == "Fcastr") {

		for(var i = 0; i < marine_elmnts.length; i++) {

			var re = new RegExp('^' + marine_elmnts[i],'g');

			if (re.test(id)) {

				fullImageName = IMAGES_DIR + '/' + sector + '/' + id + '_'
							+ sector + '_marine' + IMAGE_EXTENSION;

				break;

			}

		}

		for(var i = 0; i < fire_elmnts.length; i++) {

			var re = new RegExp('^' + fire_elmnts[i],'g');

			if (re.test(id)) {

				fullImageName = IMAGES_DIR + '/' + sector + '_fire' + '/' + id + '_'
							+ sector + '_fire' + IMAGE_EXTENSION;

				break;

			}

		}

	}

	return fullImageName;

}

/**
 * returns the full thumbnail image name (path) for the image id (e.g. id = MaxT1)
 */
function getThumbnailImageName(id) {

	var thumbImageName = THUMBNAIL_IMAGE_DIR + "Thumbnail_" + id + "_" + state
							 + IMAGE_EXTENSION;

	if (gfeForecastType == "Fcastr") {

		for(var i = 0; i < marine_elmnts.length; i++) {

			var re = new RegExp('^' + marine_elmnts[i],'g');

			if (re.test(id)) {

				thumbImageName = THUMBNAIL_IMAGE_DIR + "Thumbnail_" + id + "_" + state
										+ '_marine' + IMAGE_EXTENSION;

				break;

			}

		}

		for(var i = 0; i < fire_elmnts.length; i++) {

			var re = new RegExp('^' + fire_elmnts[i],'g');

			if (re.test(id)) {

				thumbImageName = THUMBNAIL_IMAGE_DIR + "Thumbnail_" + id + "_" + state
										 + '_fire' + IMAGE_EXTENSION;

				break;

			}

		}

	}

	return thumbImageName;

}

/**
 * Changes the forecast image and the thumbnail image (overview) to represent the currently selected
 * weather element, period number and timeslot
 * @param element - the weather element name of the new image
 * @param period - the period number of the new image
 * @param timeslot - the timeslot number of the new image
 */
//function changeImage(element,period,timeslot) {
//	var id = getImageNameId(element,period,timeslot);
//	changeImageById(id);
//}
//
//function changeImageById(id) {
//	$("#" + MAP_IMAGE_ID).attr('src', getFullImageName(id));
//	showOverviewThumbnail(id);
//}


function updateImages() {
	var id = getImageNameId(CURRENT_ELEMENT,CURRENT_PERIOD,CURRENT_TIMESLOT);
	var imgname = id;
	if (id != NO_DATA_AVAILABLE_IMAGE && id != NO_DATA_AVAILABLE_FFDI_IMAGE) imgname = getFullImageName(id);
	// The script for highlighting the map areas creates a div which it wraps around
	// the map image (<img) so we need to change the background image of this parent
	// div so that the image will change.
	$("#" + MAP_IMAGE_ID).parent().css('background-image', 'url('+imgname+')');
	$("#" + MAP_IMAGE_ID).attr('src', imgname); // change forecast image
	showOverviewThumbnail(id); // change overview thumbnail image
}


function updateElementPeriodTimeslotAndCookie(element, period, timeslot) {
	var success = setCurrentElementPeriodTimeslot(element, period, timeslot);
	// alert("sssss success " + success+ " element "+element+ " period "+period+" timeslot "+timeslot);
	if (success) createCookie(SHOW_ELEMENT_COOKIE_NAME, buildShowElementCookieValue(), COOKIE_EXPIRE);
	return success;
}

function setCurrentElementPeriodTimeslot(element, period, timeslot) {

	var validElement = false;
	var validPeriod = true;
	var validTimeslot = true;

	var i = 0;
	while((i < ELEMENT_NAMES.length) && (validElement == false)) {
		if (element == ELEMENT_NAMES[i]) validElement = true;
		i++; // next
	}

	if ((period < 1) || (period > NUMBER_OF_PERIODS)) { validPeriod = false; }
	if (timeslot > NUMBER_OF_THREE_HOURLY_TIMESLOTS) { validTimeslot = false;  }
	//alert("(validElement) "+validElement+" (validPeriod) "+validPeriod+" (validTimeslot) "+validTimeslot);
	if (validElement && validPeriod && validTimeslot) {

		// set previous
		PREVIOUS_PERIOD = CURRENT_PERIOD;
		PREVIOUS_ELEMENT = CURRENT_ELEMENT;
		PREVIOUS_TIMESLOT = CURRENT_TIMESLOT;
		PREVIOUS_PERIOD_ELEMENT_TIMESLOT = CURRENT_PERIOD_ELEMENT_TIMESLOT;

		// set current
		CURRENT_ELEMENT = element;
		CURRENT_PERIOD = period;
		CURRENT_TIMESLOT = timeslot;
		CURRENT_PERIOD_ELEMENT_TIMESLOT = "" + DOM_ID_PREFIX + CURRENT_PERIOD + CURRENT_ELEMENT + CURRENT_TIMESLOT;
		return true;

	}
	else {
		return false;
	}
}

function updateSelection() {

	if (pagetype == PAGE_TYPE_DAY || pagetype == PAGE_TYPE_WEEK) {

		// switch highlighted cell
		$("#" + PREVIOUS_PERIOD_ELEMENT_TIMESLOT).css('background-color', TABLE_CELL_DEFAULT_COLOUR);
		$("#" + CURRENT_PERIOD_ELEMENT_TIMESLOT).css('background-color', TABLE_CELL_HIGHLIGHT_COLOUR);

		if (pagetype == PAGE_TYPE_DAY) {
			dailyViewSwitchPeriod();
			updatePeriodDropDown();
			disableNextPrevButtonsWhereAppropriate();
		}
		else { // weekly
			weeklyViewSwitch();
		}

	}
	else if (pagetype == PAGE_TYPE_LOOP) {
		changeLoopDivSelections(null, null, null); // update to current
		disableLoopButtonsWhereAppropriate();
	}

}

function createLoopForecastElementDropDown() {

	var select = document.createElement(HTML_ELEMENT_SELECT);
	select.id = ELEMENT_ID_FORECAST_ELEMENT_SELECT;
	select.size = NUMBER_OF_ITEMS_SHOWN_AT_ONE_TIME_IN_SELECT_BOXES;
	select.onchange = new Function(JAVASCRIPT_FUNCTION_CHANGE_LOOP_FORECAST_ELEMENT);

	var option;
	var textnode;
	var numLoopForecastElements = LOOP_FORECAST_ELEMENTS.length;
	for (var i = 0; i < numLoopForecastElements; i++) {
		option = document.createElement(HTML_ELEMENT_OPTION);
		option.id = LOOP_FORECAST_ELEMENTS_MAPPING[i];
		if (i == 0) option.selected = true;
		textnode = document.createTextNode(LOOP_FORECAST_ELEMENTS[i]);
		option.appendChild(textnode);
		select.appendChild(option);
	}

	$("#" + ELEMENT_ID_FORECAST_ELEMENT_DROP_DOWN).append(select);

}

function loopForecastElementChange() {

	var select = document.getElementById(ELEMENT_ID_FORECAST_ELEMENT_SELECT);
	var index = select.selectedIndex;
	createLoopPeriodDropDown(index);
	loopPeriodChange();
	disableLoopPreviousButton();
	enableLoopNextButton();

}

function loopPeriodChange() {

	var select = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);
	var index = select.selectedIndex;
	var value = select.options[index].value;
	var id = select.options[index].id;
	loopShowImage(value);
	disableLoopButtonsWhereAppropriate();
	createCookie(SHOW_ELEMENT_COOKIE_NAME, id, COOKIE_EXPIRE);

}

function loopShowImage(id) {

	// document.getElementById(MAP_IMAGE_ID).src = getFullImageName(id);
	var imgname = getFullImageName(id);
	$("#" + MAP_IMAGE_ID).parent().css('background-image', 'url('+imgname+')');
	$("#" + MAP_IMAGE_ID).attr('src', imgname); // change forecast image
	showOverviewThumbnail(id);
	createCookie(SHOW_ELEMENT_COOKIE_NAME, buildShowElementCookieValue(), COOKIE_EXPIRE);

}

function showFirstImage() {

	document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT).selectedIndex = 0;
	loopPeriodChange();

}

function showLastImage() {

	var select = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);
	var lastIndex = select.options.length - 1;
	select.selectedIndex = lastIndex;
	loopPeriodChange();

}

function image_step(direction) {

	var select = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);
	var index = select.selectedIndex;
	var newIndex;

	if (direction == 1) { // forward
		newIndex = index + 1;
	}
	else if (direction == -1) { // backwards
		newIndex = index - 1;
	}

	if ( (newIndex < select.options.length) && (newIndex >= 0)) {
		select.selectedIndex = newIndex;
		loopPeriodChange();
		disableLoopButtonsWhereAppropriate();
	}

}

function disableLoopButtonsWhereAppropriate() {

	var select = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);
	var index = select.selectedIndex;
	enableLoopPreviousButton();
	enableLoopNextButton();
	var firstIndex = 0;
	var lastIndex = select.options.length-1;
	if (index == firstIndex) {
		disableLoopPreviousButton();
	}
	if (index == lastIndex) {
		disableLoopNextButton();
	}

}

function loopAnimate(recurse) {

	if (signal == 0 || recurse == true) {

		signal = 1;
		var select = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);
		var currentIndex = select.selectedIndex;

		if (currentIndex == select.options.length-1) {
			showFirstImage();
		}
		else {
			image_step(1);
		}

		currentIndex = select.selectedIndex;
		var lastIndex = select.options.length-1;

		if (currentIndex == lastIndex) {
			timeId = setTimeout(JAVASCRIPT_FUNCTION_LOOP_ANIMATE
									  , END_OF_LOOP_WAIT_FACTOR * delay);
		}
		else {
			timeId = setTimeout(JAVASCRIPT_FUNCTION_LOOP_ANIMATE, delay);
		}

		disableLoopPlayButton();
		enableLoopStopButton();

	}

}

function loopStopAnimation() {

	if (signal == 1) {
		clearTimeout(timeId);
		signal = 0;
		disableLoopStopButton();
		enableLoopPlayButton();
	}

}

function changeLoopSpeed(num) {

	if (num < 0) {

		if (delay  <= 1000) {
			delay -= 200;
		}
		else if (delay  <= 2000) {
			delay -= 500;
		}
		else {
			delay -= 1000;
		}

	}
	else {

		if (delay >= 2000) {
			delay += 1000;
		}
		else if (delay >= 1000) {
			delay += 500;
		}
		else {
			delay += 200;
		}

	}

	enableLoopButtonFaster();
	enableLoopButtonSlower();

	if (delay >= MAX_LOOP_ANIMATION_DELAY) { // as fast as it will go
		delay = MAX_LOOP_ANIMATION_DELAY;
		disableLoopButtonSlower();
	}

	if (delay <= MIN_LOOP_ANIMATION_DELAY) { // as slow as it will go
		delay = MIN_LOOP_ANIMATION_DELAY;
		disableLoopButtonFaster();
	}

}

function determineLoopElementDropdownIndex(element, period) {

	var dropDownElementName = element;

	if (element == ELEMENT_NAME_MAXTMINT) {
		if (periodDayNight[period-1] == DAY_FLAG) {
			dropDownElementName = ELEMENT_NAME_MAXT;
		}
		else {
			dropDownElementName = ELEMENT_NAME_MINT;
		}
	}

	var numElements = LOOP_FORECAST_ELEMENTS_MAPPING.length;

	for (var i = 0; i < numElements; i++) {
		if (LOOP_FORECAST_ELEMENTS_MAPPING[i] == dropDownElementName) {
			return i;
		}
	}

	return 1; // error

}

function changeLoopDivSelections(element, period, timeslot) {

	if (element == null) {
		element = CURRENT_ELEMENT;
	}
	if (period == null) {
		period = CURRENT_PERIOD;
	}
	if (timeslot == null) {
		timeslot = CURRENT_TIMESLOT;
	}

	var elementIndex = determineLoopElementDropdownIndex(element, period);
	var elementSelect = document.getElementById(ELEMENT_ID_FORECAST_ELEMENT_SELECT);

	if (elementIndex < elementSelect.options.length) {
		elementSelect.options[elementIndex].selected = true;
	}

	createLoopPeriodDropDown(elementIndex);
	document.getElementById(element + OPTION_VALUE_DELIMINATOR + period
									+ OPTION_VALUE_DELIMINATOR + timeslot)
									.selected = true;

}

function createLoopPeriodDropDown(elementIndex) {

	if (!elementIndex) {
		elementIndex = 0; // default first load
	}

	var loopPeriodType = LOOP_PERIOD_MAPPING[elementIndex];
	var loopPeriods = new Array();
	var loopValues = new Array();
	var loopIds = new Array();
	var element = LOOP_FORECAST_ELEMENTS_MAPPING[elementIndex];
	var realElement = element;

	if (element == ELEMENT_NAME_MAXT || element == ELEMENT_NAME_MINT) {
		realElement = ELEMENT_NAME_MAXTMINT;
	}

	var isDailyRainfall = (element == ELEMENT_NAME_DAILY_PRECIP);

	if (typeof(ELEMENT_NAME_HAZARDS) !== 'undefined') {
		isHazards = (element == ELEMENT_NAME_HAZARDS);
	}
	else {
		isHazards = false;
	}

	var index = 0;

	if (loopPeriodType == LOOP_PERIOD_DAYS) {

		for (var i = 0; i < PERIOD_NAMES.length; i++) {
			var periodnumber = i + 1;
			if (periodDayNight[i] == DAY_FLAG) {
				loopPeriods.push(PERIOD_NAMES[i]);
				if (isDailyRainfall) {
					loopValues.push("" + element + periodnumber);
				}
				else {
					loopValues.push("" + element + (index + 1));
				}
				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR
								 + DEFAULT_TIMESLOT);
				index++;
			}
		}

	}
	else if (loopPeriodType == LOOP_PERIOD_NIGHTS) {

		for (var i = 0; i < PERIOD_NAMES.length; i++) {
			var periodnumber = i + 1;
			if (periodDayNight[i] == NIGHT_FLAG) {
				loopPeriods.push(PERIOD_NAMES[i]);
				loopValues.push("" + element + (index + 1));
				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR
								 + DEFAULT_TIMESLOT);
				index++;
			}
		}

	}
	else if (loopPeriodType == LOOP_PERIOD_ALL_PERIODS) {
		
		for (var i = 0; i < PERIOD_NAMES.length; i++) {
			
			var periodnumber = i + 1;

			for (var j = 0; j < NUMBER_OF_THREE_HOURLY_TIMESLOTS; j++) {

				var timeslot = j + 1;
				var numTimeSlots;

				if (periodnumber >= PERIOD_NUMBER_WHEN_SWITCHES_TO_SIX_HOURLY) {
					numTimeSlots = NUMBER_OF_TIMESLOTS_WHEN_SIX_HOURLY;
				}
				else {
					numTimeSlots = NUMBER_OF_TIMESLOTS_WHEN_THREE_HOURLY;
				}

				var timeslotlookup;

				if (periodDayNight[i] == DAY_FLAG) {
					timeslotlookup = DAYTIME_TIMESLOTS;
				}
				else {
					timeslotlookup = NIGHTTIME_TIMESLOTS;
				}

				if ( (numTimeSlots == NUMBER_OF_TIMESLOTS_WHEN_SIX_HOURLY
					&& (timeslot == 1 || timeslot == 3)) // six-hourly, only timeslot 1 and 3 shown
					|| (numTimeSlots == NUMBER_OF_TIMESLOTS_WHEN_THREE_HOURLY) ) { // three-hourly, all timeslots shown
					
					loopPeriods.push(PERIOD_NAMES[i] + " " + timeslotlookup[j]);
					loopValues.push(getImageNameId(element,periodnumber, timeslot));
					loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
									 + periodnumber + OPTION_VALUE_DELIMINATOR
									 + timeslot);

				}

			}

		}

	}
	else if (loopPeriodType == LOOP_PERIOD_DAYS_0_AND_1) {
		
		var day_count = 0;

		for (var i = 0; i < PERIOD_NAMES.length; i++) {

			var periodnumber = i + 1;

			if (periodDayNight[i] == DAY_FLAG) {

				day_count++;

				if (day_count > 2) break;

				loopPeriods.push(PERIOD_NAMES[i]);

				if (isDailyRainfall) {
					loopValues.push("" + element + periodnumber);
				}
				else {
					loopValues.push("" + element + (index + 1));
				}

				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR
								 + DEFAULT_TIMESLOT);
				index++;

			}

		}

	}
	else if (loopPeriodType == LOOP_PERIOD_DAYS_0_1_AND_2) {

		var day_count = 0;

		for (var i = 0; i < PERIOD_NAMES.length; i++) {

			var periodnumber = i + 1;

			if (periodDayNight[i] == DAY_FLAG) {
				day_count++;

				if (day_count > 3) break;

				loopPeriods.push(PERIOD_NAMES[i]);

				if (isHazards) {
					loopValues.push("" + element + periodnumber);
				}
				else {
					loopValues.push("" + element + (index + 1));
				}

				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR
								 + DEFAULT_TIMESLOT);
				index++;

			}

		}

	}
	else if (loopPeriodType == LOOP_PERIOD_ALL_PERIODS_FIRST_THREE_DAYS) {

		for (var i = 0; i < 6; i++) {


			var periodnumber = i + 1;
			for (var j = 0; j < NUMBER_OF_THREE_HOURLY_TIMESLOTS; j++) {

				var timeslot = j + 1;
				var numTimeSlots = NUMBER_OF_TIMESLOTS_WHEN_THREE_HOURLY;
				var timeslotlookup;

				if (periodDayNight[i] == DAY_FLAG) {
					timeslotlookup = DAYTIME_TIMESLOTS;
				}
				else {
					timeslotlookup = NIGHTTIME_TIMESLOTS;
				}

				loopPeriods.push(PERIOD_NAMES[i] + " " + timeslotlookup[j]);
				loopValues.push(getImageNameId(element,periodnumber, timeslot));
				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR + timeslot);

			}

		}

	}
	else if (loopPeriodType == LOOP_PERIOD_24HR_DAYS) {

		for (var i = 0; i < PERIOD_NAMES.length; i = i+2) {
			var periodnumber = i + 1;
			console.log(periodnumber);
			if (periodDayNight[i] == DAY_FLAG) {
				loopPeriods.push(PERIOD_NAMES[i]);
				if (isDailyRainfall) {
					loopValues.push("" + element + periodnumber);
				}
				else {
					loopValues.push("" + element + (index + 1));
				}
				console.log(loopValues);
				loopIds.push("" + realElement + OPTION_VALUE_DELIMINATOR
								 + periodnumber + OPTION_VALUE_DELIMINATOR
								 + DEFAULT_TIMESLOT);
				index = index + 2;
			}
		}

	}

	var div = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_DROP_DOWN);
	var select = document.createElement(HTML_ELEMENT_SELECT);
	var option;
	var textnode;
	select.id = ELEMENT_ID_ELEMENT_PERIOD_SELECT;
	select.onchange = new Function(JAVASCRIPT_LOOP_PERIOD_CHANGE);

	for (var i = 0; i < loopPeriods.length; i++) {

		option = document.createElement(HTML_ELEMENT_OPTION);

		if (i == 0) {
			option.selected = OPTION_SELECTED_TRUE_VALUE;
		}

		option.id = loopIds[i];
		option.value = loopValues[i];
		textnode = document.createTextNode(loopPeriods[i]);
		option.appendChild(textnode);
		select.appendChild(option);

	}

	var old = document.getElementById(ELEMENT_ID_ELEMENT_PERIOD_SELECT);

	if (old) {
		div.replaceChild(select, old);
	}
	else {
		div.appendChild(select);
	}

}

function isOddNumber(number) {

	if ((number % 2) == 1) {
		return true;
	}
	else {
		return false;
	}

}

/**
 * Called when a user clicks the '+12 Hrs >' button  (Daily View)
 * if current period isn't the last one, switch table body to be the next 12 hour period
 * also update period selector (drop down), show the element image for element/timeslot for the new period and
 * disable next/prev button if appropriate
 */
function next12Hours() {

	if (CURRENT_PERIOD != NUMBER_OF_PERIODS) {
		updateElementPeriodTimeslotAndCookie(
			CURRENT_ELEMENT, parseInt(CURRENT_PERIOD) + 1, CURRENT_TIMESLOT
		);
		$("#" + DOM_ID_PREFIX + PREVIOUS_PERIOD).hide();
		$("#" + DOM_ID_PREFIX + CURRENT_PERIOD).show();
		updatePeriodDropDown();
		showCurrentElement();
		disableNextPrevButtonsWhereAppropriate();
	}

}

/**
 * Called when the user clicks the '< -12 hours' button (Daily View)
 * if current period isn't the first one, swtich table body to the previous 12 hour period
 * also update period selector (drop down), show the element image for element/timeslot for the new period and
 * disable next/previous button if appropriate
 */
function previous12Hours() {

	if (CURRENT_PERIOD != 1) {

		updateElementPeriodTimeslotAndCookie(
			CURRENT_ELEMENT, parseInt(CURRENT_PERIOD) - 1, CURRENT_TIMESLOT
		);
		$("#" + DOM_ID_PREFIX + PREVIOUS_PERIOD).hide();
		$("#" + DOM_ID_PREFIX + CURRENT_PERIOD).show();
		updatePeriodDropDown();
		showCurrentElement();
		disableNextPrevButtonsWhereAppropriate();

	}

}

/**
 * Disables the '+12 Hrs >' button if at the last period  (Daily View)
 * Disables the '< -12 Hrs' button if at the first period
 * in other cases ensures the buttons are not disabled
 */
function disableNextPrevButtonsWhereAppropriate() {

	$("#" + PREVIOUS_TWELVE_HOUR_PERIOD_BUTTON_ID).attr('disabled', false);
	$("#" + NEXT_TWELVE_HOUR_PERIOD_BUTTON_ID).attr('disabled', false);

	if (CURRENT_PERIOD == 1) { //first period, disable previous button
		$("#" + PREVIOUS_TWELVE_HOUR_PERIOD_BUTTON_ID).attr('disabled', true);
	}

	if (CURRENT_PERIOD == NUMBER_OF_PERIODS) { // last period, disable next button
		$("#" + NEXT_TWELVE_HOUR_PERIOD_BUTTON_ID).attr('disabled', true);
	}

}

/**
 * Called when + / - 12 hours buttons clicked  (Daily View)
 * updates the period selector (drop down) to match the change
 */
function updatePeriodDropDown() {

	if (pagetype != PAGE_TYPE_WEEK) {
		document.getElementById(
			PERIOD_DROP_DOWN_ID + CURRENT_PERIOD
		).selected = true;
		//$("#periodSelect").selectOptions(PERIOD_DROP_DOWN_ID + CURRENT_PERIOD);
	}

}

/**
 * Conditional test if there is no three hourly image available for a particular period/ timeslot
 * @param period the period number
 * @timeslot the timeslot number
 */
function no_three_hourly_image_available(period, timeslot) {

	// MaxTMinT & DailyPrecip timeslot 1 only
	if ( period >= PERIOD_NUMBER_WHEN_SWITCHES_TO_SIX_HOURLY
		  && ( timeslot == NUMBER_OF_TIMESLOTS_WHEN_SIX_HOURLY
				|| timeslot == NUMBER_OF_TIMESLOTS_WHEN_THREE_HOURLY)
		) {
		return true;
	}
	else {
		return false;
	}

}


function getImageNameId(element,period,timeslot) {

	var period_index = period - 1;
	var timeslot_index = timeslot - 1;
	var id = ""; // to be set by if statements below

	// if element/period/timeslot combo is a 3 hourly image (not available)
	// at 6 hourly period (more than 3 days out)...
	if (no_three_hourly_image_available(period, timeslot)) {
		return NO_DATA_AVAILABLE_IMAGE; // show no data image
	}

	/*if (element == 'FFDIMaxT') {
	  if ( (periodDayNight[0] == NIGHT_FLAG && period > 3) || (period > 4)) {
		return NO_DATA_AVAILABLE_FFDI_IMAGE; // show no data image
	  }
	}*/

	var index = getIndexOfWeatherElement(element);

	if (index == -1) {
		alert("An error occurred"); return;
	}	
	
	id = ELEMENT_NAMES_ARRAY[index]
		  [WEATHER_ELEMENT_ARRAY_ELEMENT_IMAGE_NAME_LOOKUP]
		  [period_index][timeslot_index];

	return id;

}

/**
 * creates the period drop down in the elements table (Daily View)
 */
function createPeriodDropDownDailyView() {
// $.fn.createPeriodDropDownDailyView = function() {

	var func = JAVASCRIPT_FUNCTION_DAILY_VIEW_PERIOD_CHANGE;
	var select = document.getElementById(PERIOD_DROP_DOWN_ID);
	var option;
	var textnode;
	select.onchange = new Function(func);
	var selected = "";

	for (var i = 0; i < NUMBER_OF_PERIODS; i++) {
		option = document.createElement(HTML_ELEMENT_OPTION);
		option.id = PERIOD_DROP_DOWN_ID + (i+1);
		if (i == 0) option.selected = OPTION_SELECTED_TRUE_VALUE;
		option.value = (i+1);
		textnode = document.createTextNode(PERIOD_NAMES[i]);
		option.appendChild(textnode);
		select.appendChild(option);
	}

}

/************* cookie stuff **************************************************/


function buildShowElementCookieValue() {

	return CURRENT_ELEMENT + COOKIE_VALUE_DELIMINATOR + CURRENT_PERIOD
			 + COOKIE_VALUE_DELIMINATOR + CURRENT_TIMESLOT;

}

function checkCookie() {

	var showElementCookieFound = false;

	if (document.cookie) { // if document has cookies



		var cookieArray = document.cookie.split(COOKIE_PARAM_DELIMINATOR);
		var form = document.getElementById(CLICK_OR_MOUSEOVER_FORM_NAME);

		var valueArray;
		var name;
		var value;

		for (var i = 0; i<cookieArray.length; i++) { // for each cookie stored against document

			// get name value pair
			valueArray = cookieArray[i].split(COOKIE_KEY_VALUE_DELIMINATOR);
			// valueArray = cookieArray[i].split('=');
			name = valueArray[0];
			value = valueArray[1]; // 0 or 1

			//load click or mouseover as stored in cookie
			if (name == CLICK_OR_MOUSEOVER_COOKIE_NAME) {
				set_mouse_effect(value);
				// set_mouse_effect.call(value);
			}

			// show element according to element/period/timeslot stored in cookie
			else if (name == SHOW_ELEMENT_COOKIE_NAME) {

				var showElementParamArray = value.split(COOKIE_VALUE_DELIMINATOR);
				if (showElementParamArray[1] != 0) {
					var element = showElementParamArray[0];
					var period = showElementParamArray[1];
					var timeslot = showElementParamArray[2];
					showElement(element,period,timeslot);
					showElementCookieFound = true;
				}

			}

		}

		if (!showElementCookieFound) {
			showElement(ELEMENT_NAMES_ARRAY[0]
							[WEATHER_ELEMENT_ARRAY_ELEMENT_NAME_INDEX],1,1);
		}

	}
	else {

		// store cookie for click or mouseover
		var value = 0;
		var radioBtn = document.getElementById(MOUSE_CLICK_ID);
		if (radioBtn.checked) value = 0; else value = 1;
		createCookie(CLICK_OR_MOUSEOVER_COOKIE_NAME, value, COOKIE_EXPIRE);
		showElement(ELEMENT_NAMES_ARRAY[0]
						[WEATHER_ELEMENT_ARRAY_ELEMENT_NAME_INDEX],1,1);

	}

}

/**
 * Called when user clicks on mouse-click or mouse-over radiobuttons,
 * and also when loading a cookie * @param choice integer representing one
 * of click_chosen or mouseover_chosen varants goes through element rollover
 * table, setting cell links to either click effect or mosueover effect
 * depending on choice
 */
function set_mouse_effect(choice) {
	var click_chosen = 0;
	var mouseover_chosen = 1;

	if(pagetype != PAGE_TYPE_LOOP) { // no mouseeffect on loop pages

		if(choice == click_chosen) {
			$("span.link")
				.unbind("mouseover")
				.click(function() {
					var splitup = this.id.split(":", 3);
					showElement(""+splitup[0],splitup[1],splitup[2]);
				})
				.mouseover(function() { $(this).css('color', '#FF6633'); })
				.mouseout(function() { $(this).css('color', 'blue'); });
			/* rainfall special case - added PS 20101101  */
			for(var i = 0; i < 24; i++) {
				$("span.rainfall:eq(" + i + ")")
					.unbind("mouseover")
					.click(function() {
						var splitup = this.id.split(":", 3);
						showElement(""+splitup[0],splitup[1],splitup[2]);
					})
					.mouseover(function() { $(this).css('color', '#FF6633'); })
					.mouseout(function() { $(this).css('color', 'blue'); }); // PS!!!
			}
		}
		else {
			$("span.link")
				.unbind("click")
				.mouseover(function() {
					var splitup = this.id.split(":", 3);
					showElement(""+splitup[0],splitup[1],splitup[2]);
				});
			/* rainfall special case - added PS 20101101 */
			for(var i = 0; i < 24; i++) {
				$("span.rainfall:eq(" + i + ")")
					.unbind("click")
					.mouseover(function() {
						var splitup = this.id.split(":", 3);
						showElement(""+splitup[0],splitup[1],splitup[2]);
					})
			}
		}

		createCookie(CLICK_OR_MOUSEOVER_COOKIE_NAME, choice, COOKIE_EXPIRE);

		// ensures radiobutton checked (useful when loading from cookie)
		$("#"+((choice == click_chosen)? MOUSE_CLICK_ID : MOUSE_OVER_ID))
			.attr('checked',true);
		$("#"+((choice == click_chosen)? MOUSE_OVER_ID : MOUSE_CLICK_ID))
			.attr('checked',false);
	}
}


function createCookie(name, value, expire) {

	var expireDate = new Date();
	expireDate.setMonth(expireDate.getMonth()+(expire));
	document.cookie = name + COOKIE_KEY_VALUE_DELIMINATOR + value
						 + COOKIE_PARAM_DELIMINATOR + "path"
						 + COOKIE_KEY_VALUE_DELIMINATOR + COOKIEPATH;

}

/**
 * Called on page load
 * sets the map variable and checks for cookies
 */
function initialise() {

	$(function() { // wait until loaded DOM
		var map = $("#" + MAP_IMAGE_ELEMENT_ID);
		// var SUBCONTENT_DEF_HEIGHT = 610;
		checkCookie();
		// Because fire weather has more elements then public weather, so we need
		// to adjust the height to get better effect.

		// Set sub content height to image height
		// N.B. The size of the RHSCB at this point will be the same as the image
		// or bigger the #image, #right-hand-side-control-block and #main-content
		// height have allready been set
		var image_height = $('#mapimage').height();
		var rhscontrolblock_height = $('#right-hand-side-control-block').height();
		if ( rhscontrolblock_height > image_height ) {
			// alert('RHSCB is bigger');
			$(".viewer").height(
				rhscontrolblock_height
				+$("#maintabs").height()
				+$("#helptext-and-gotoregion-line").height()
			);
			$("#sub-content").height(
				rhscontrolblock_height
			);
		}
		else {
			$(".viewer").height(
				image_height
				+ $("#maintabs").height()
				+ $("#helptext-and-gotoregion-line").height()
			);
			$("#sub-content").height(
				image_height + 2
			);
		}
	});
}

/**
 * Called when a users clicks on a adjacent areas 'compass point' arrow
 * @param areaName the page name for the state or district that is represents the adjacent area
 */
function goToAdjacentArea(areaName) {

	if (pagetype == PAGE_TYPE_DAY) {
		document.location = areaName + PHP_FILE_EXTENSION;
	}
	else {
		document.location = areaName + '-' + pagetype.toLowerCase() + PHP_FILE_EXTENSION;
	}

}

/**
 * Called when users clicks on a state (at national level) or district (at state level)
 * Links to the appropriate state or district page (with the same view as current page - Daily, Weekly or Loop view)
 * @param page_in the page name to redirect to
 * @param marineForecast - flag to determine if this is for a marine forecasts, flag no currently used.
 */
function pageZoomSelect(page_in, marineForecast) {

	// Day pages do not have the pagetype extension, just region.php
	var go_page = page_in + PHP_FILE_EXTENSION; // Day View (Day pagetype)
	if ( pagetype != PAGE_TYPE_DAY ) {
		// go_page = page_in + pagetype + PHP_FILE_EXTENSION;
		go_page = page_in + '-' + pagetype.toLowerCase() + PHP_FILE_EXTENSION;
	}
	document.location = go_page;

}

// ----------------------------------------------------------------
// LOOP BUTTON ENABLE/DISABLE FUNCTIONS
// ----------------------------------------------------------------

function disableLoopPreviousButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_PREVIOUS).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_PREVIOUS_DISABLED
	);
}

function enableLoopPreviousButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_PREVIOUS).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_PREVIOUS_ENABLED
	);
}

function disableLoopNextButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_NEXT).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_NEXT_DISABLED
	);
}

function enableLoopNextButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_NEXT).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_NEXT_ENABLED
	);
}

function disableLoopPlayButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_PLAY).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_PLAY_DISABLED
	);
}

function enableLoopPlayButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_PLAY).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_PLAY_ENABLED
	);
}

function disableLoopStopButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_STOP).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_STOP_DISABLED
	);
}

function enableLoopStopButton() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_STOP).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_STOP_ENABLED
	);
}

function enableLoopButtonFaster() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_FASTER).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_FASTER_ENABLED
	);
}

function disableLoopButtonFaster() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_FASTER).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_FASTER_DISABLED
	);
}

function enableLoopButtonSlower() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_SLOWER).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_SLOWER_ENABLED
	);
}

function disableLoopButtonSlower() {
	$("#" + ELEMENT_ID_LOOP_BUTTON_SLOWER).attr(
		'src', IMAGE_PATH_LOOP_BUTTON_SLOWER_DISABLED
	);
}

$(document).ready(function() {
	/* ??? */
});

$(function() {
	//initialise();
});


