/******************
 *	RASPtable.js  *
 ******************/

		/* 
		 * Global Variables
		 */

		var oldDayIndex;
		var Loaded;
		var Pics;

		var ref;
		var oldParam;
		var oldDay;
		var times;

		var paramWindow;
		var origTblHt;

		var tipobj;
		var pointerobj;

		var offsetfromcursorX=1;		 	//Customize x offset of tooltip
		var offsetfromcursorY=1;		 	//Customize y offset of tooltip

		var offsetdivfrompointerX=00;	//Customize x offset of tooltip DIV relative to pointer image
		var offsetdivfrompointerY=14;	//Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

 /***********************
 * initIt()             *
 *                      *
 * Initialise Variables *
 * Build Menus, etc     *
 ***********************/
function initIt()
{

		ref = document.forms[0];	// shorthand
		oldDayIndex = ref.Day.options.selectedIndex;
		Loaded = new Array();
		Pics = new Array();

		oldParam = ref.Param.options.value;
		oldDay = ref.Day.value;

		paramWindow = "" ;


		/**********************/
		/* Build the Day Menu */
		/**********************/
		var Now = new Date().getTime();	// Time now - in milliSec(!)
		var mS_Day = 24 * 60 * 60 * 1000;	// mS in a day
		var T = new Date();			// Instantiate a Date object
		var dayName   = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
		var monthName = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

		var day = document.forms[0].Day;	// save typing

		T.setTime(Now);					// Today
	//	day.options[0] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()] + " - Today", dayName[T.getDay()]);
	//	day.options[1] = new Option("Today - Latest data - 12Km ", "UK12");
		day.options[0] = new Option("Mallin tiedot ajalta", "12");

	//	T.setTime(Now + mS_Day);	// Tomorrow
	//	day.options[2] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
	//	T.setTime(Now + 2 * mS_Day);
	//	day.options[3] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
	//	T.setTime(Now + 3 * mS_Day);
	//	day.options[4] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
	//	T.setTime(Now + 4 * mS_Day);
	//	day.options[5] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
	//	T.setTime(Now + 5 * mS_Day);
	//	day.options[6] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
	//	T.setTime(Now + 6 * mS_Day);
	//	day.options[7] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);


		/***********************/
		/* Set Default Options */
		/***********************/


		// Install Time options
		times = d2times;
		for (var i = 0; i < times.length; i++) {
			ref.Time.options[i] = new Option(times[i], times[i]);
			if(times[i] == "1200")
				ref.Time.options[i].selected = true;
		}

		// Now done above!! ref.Time.options[12].selected   = true;				// 1200
		ref.Day.options[0].selected    = true;				// Today 4Km
		ref.Param.options[1].selected  = true;				// wstar

		/* Sort out Archive year(s), at least, to handle 6 months */

		T.setTime(Now - 182 * mS_Day);
		ref.archiveYear.options[1] = new Option(T.getFullYear(), T.getFullYear());
		T.setTime(Now);
		if(T.getFullYear() != ref.archiveYear.options[1].value){
			ref.archiveYear.options[2] = new Option(T.getFullYear(), T.getFullYear());
		}

		for (i = 0; i < ref.Time.options.length; i++){
			Pics[i] = new Image();
			Loaded[i] = false;
		}

		whichBrowser();	// Determine punter's Browser

		loadImage(1);	// Assume forwards

		// Save the original Selector Table Height
		origTblHt = document.getElementById("selectors").offsetHeight;


		/********************* Material below adapted from *************************************
		* Cool DHTML tooltip script II- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
		* This notice MUST stay intact for legal use
		* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
		****************************************************************************************/


		document.write('<div id="dhtmltooltip" onload="ddrivetip(\'Ctl-Click for value\')" ></div>') //write out tooltip DIV
		document.write('<img id="dhtmlpointer" src="arrow2.gif" >') //write out pointer image

		var enabletip=false
		if (ie){
			tipobj		 = document.all["dhtmltooltip"];
			pointerobj = document.all["dhtmlpointer"];
		}
		else{
			tipobj		 = document.getElementById("dhtmltooltip") ;
			pointerobj = document.getElementById("dhtmlpointer") ;
		}

	//	unfreezetip("Ctl-Click for a value");

		document.getElementById("imgBox").onmousedown    = click;	// don't use onmouseup - doesn't always work!
		document.getElementById("imgBox").onmousemove  = positiontip;
		document.getElementById("selectors").onmouseover	= obscuretip;
		document.getElementById("selectors").onmouseout	= unhidetip;
		pointerobj.onmouseover = positiontip;
}


		/****************************************
		 *      END OF INITIALISATION STUFF     *
		 *      Start of functions              *
		 ****************************************/

		function popup(mylink, windowname, wid, ht)
		{
			if (! window.focus)return true;
			var href;
			if (typeof(mylink) == 'string')
				href=mylink;
			else
				href=mylink.href;
			args = 'width=' + wid + ',height=' + ht + ',scrollbars=yes';
			window.open(href, windowname, args);
			return false;
		}

		function ietruebody(){
			return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
		}


		function ddrivetip(thetext, thewidth, thecolor){
			if (typeof thewidth != "undefined")
				tipobj.style.width = thewidth+"px"
			if (typeof thecolor != "undefined" && thecolor != "")
				tipobj.style.backgroundColor = thecolor
			tipobj.innerHTML = thetext
			enabletip = false
			return false
		}

		function positiontip(e)
		{
			if (enabletip){
				var nondefaultpos=false
				var curX=(ns) ? e.pageX : event.clientX+ietruebody().scrollLeft;
				var curY=(ns) ? e.pageY : event.clientY+ietruebody().scrollTop;

				//Find out how close the mouse is to the corner of the window
				var winwidth  = ie && !window.opera ? ietruebody().clientWidth : window.innerWidth-20
				var winheight = ie && !window.opera ? ietruebody().clientHeight : window.innerHeight-20

				var rightedge = ie &&!window.opera ? winwidth  - event.clientX - offsetfromcursorX : winwidth - e.clientX - offsetfromcursorX
				var bottomedge= ie &&!window.opera ? winheight - event.clientY - offsetfromcursorY : winheight - e.clientY - offsetfromcursorY

				var leftedge=(offsetfromcursorX<0) ? offsetfromcursorX*(-1) : -1000

				//if the horizontal distance isn't enough to accomodate the width of the context menu
				if (rightedge < tipobj.offsetWidth){
					//move the horizontal position of the menu to the left by it's width
					tipobj.style.left = curX - tipobj.offsetWidth + "px"
					nondefaultpos = true
				}
				else if (curX < leftedge)
					tipobj.style.left = "5px"
				else{
					//position the horizontal position of the menu where the mouse is positioned
					tipobj.style.left = curX + offsetfromcursorX - offsetdivfrompointerX + "px"
					pointerobj.style.left = curX + offsetfromcursorX + "px"
				}

				//same concept with the vertical position
				if (bottomedge<tipobj.offsetHeight){
					tipobj.style.top = curY - tipobj.offsetHeight - offsetfromcursorY + "px"
					nondefaultpos = true
				}
				else{
					tipobj.style.top = curY + offsetfromcursorY + offsetdivfrompointerY + "px"
					pointerobj.style.top = curY + offsetfromcursorY + "px"
				}
				// if(!archiveMode){
					tipobj.style.visibility = "visible"
					if (!nondefaultpos)
						pointerobj.style.visibility = "visible"
          // else
            // pointerobj.style.visibility = "hidden"
				// }
			}
		}

		function removePopup()
		{
			// Remove popup window
			try {
				if(paramWindow != "" ){
					paramWindow.close();
					paramWindow = "" ;
				}
			}
			catch(err) {
				; // error irrlevant
			}
		}

		var tipstate = "";
		function obscuretip()
		{
			if(tipstate != "frozen")
				hidetip();
		}


		function unfreezetip(Str)
		{
			removePopup();
			// if(archiveMode){
				// hidetip();
				// return;
			// }
			unhidetip();
			tipobj.innerHTML = Str;
			tipobj.onmouseover  = positiontip;
			pointerobj.onmouseover  = positiontip;
			document.getElementById("imgBox").onmousemove = positiontip;
			tipstate = "";
		}


		function freezetip(){
			document.getElementById("imgBox").onmousemove = "";
			// document.getElementById("imgBox").onmouseout = "";
			pointerobj.onmouseover = "";
			tipobj.onmouseover = "";
			tipstate = "frozen";
		}


		function unhidetip()
		{
			// if(archiveMode)
				// return;	// No tip in archiveMode
		//	enabletip=true
			enabletip=false
			tipobj.style.visibility="visible"
			pointerobj.style.visibility="visible"
		}

		function hidetip(){
			enabletip=false
			tipobj.style.visibility="hidden"
			pointerobj.style.visibility="hidden"
		}



		/*****************************/
		/* Get image click Coords    */
		/*****************************/ 
		function getPageCoords (element)
		{
			var coords = {x : 0, y : 0};
			while (element) {
				coords.x += element.offsetLeft;
				coords.y += element.offsetTop;
				element = element.offsetParent;
			}
			return coords;
		}


		/*****************************/
		/* Get image click Posn info */
		/*****************************/ 
		function getOffsets(evt)
		{
			if( ie ) {		// Internet Exploder
				target = event.srcElement;
				if (typeof target.offsetLeft == 'undefined') {
					target = target.parentNode;
				}
				var pageCoords = getPageCoords(target);
				var eventCoords = {
					x: window.pageXOffset + event.clientX,
					y: window.pageYOffset + event.clientY
				}
			}
			else {		// NS etc
				var target = evt.target;
				if (typeof target.offsetLeft == 'undefined') {
					target = target.parentNode;
				}
				var pageCoords =getPageCoords(target);
				var	eventCoords = {
						x: window.pageXOffset + evt.clientX,
						y: window.pageYOffset + evt.clientY
				};

			}
			var offsets = {
				offsetX: eventCoords.x - pageCoords.x,
				offsetY: eventCoords.y - pageCoords.y
			}
			return offsets;
		}


		/********************************/
		/* CallBack for onclick (image) */
		/********************************/
		function click(E)
		{
			var buttn;
			var dirn = 1; // forwards

			// Catch a stupid selection
			if (ref.Param.value === "nope1") {
				return false;
			}

			/*	buttn	IE		NS (etc?)
			 *  L			1			1
			 *  M			4			2
			 *  R			2			3
			 */
			var LEFT 	= 1;
			var MID  	= 2;
			var RIGHT	= 3;
			if ( ie ) {
				shiftPressed	= event.shiftKey;
				ctrlPressed		= event.ctrlKey;
				altPressed		= event.altKey;
				switch(event.button){
				case 1:	buttn = LEFT;  break;
				case 2: buttn = RIGHT; break;
				case 3:	buttn = MID; 	 break;
				case 4:	buttn = MID;	 break;
				default:
					alert("I don't understand which butoon you pressed!\nButton # = " + event.button);
					break;
				}
			}
			else if (ns || ko || op ) {
				shiftPressed	= E.shiftKey;
				ctrlPressed		= E.ctrlKey;
				altPressed		= E.altKey;
				switch(E.which){
				case 1:	buttn = LEFT; 	break;
				case 2:	buttn = MID;		break;
				case 3: buttn = RIGHT;	break;
				default:	alert("Which button was that?\nE.which = " + E.which); break;
				}				
			}
			else {
				alert("Which Button?\nE.which = " + E.which);
			}
			
			times = d2times;

			switch (buttn) {
			case 1:
				/**** ORDINARY CLICK -> NEXT TIME IN DAY ****/
				if(!shiftPressed && !ctrlPressed){
				var i = ref.Time.selectedIndex;
				i = (i + 1) % times.length;
				ref.Time.options[i].selected   = true;
				unfreezetip("Ctl-Click for Value");
				break;
				}

				/**** CTRL-SHIFT -> PREVIOUS TIME IN DAY ****/
				else if(shiftPressed && ctrlPressed){
					var i = ref.Time.selectedIndex;
					if (--i < 0) {
						i = (times.length - 1);
					}
					ref.Time.options[i].selected   = true;
					dirn = -1; // backwards;
					unfreezetip("Ctl-Click for Value");
					break;
				}

				/**** SHIFT -> PARAMETER VALUE IN POPUP ****/
				else if(shiftPressed && !ctrlPressed){
					if( ie){		//Internet Exploder
						wx  = event.offsetX;
						wy  = event.offsetY;
						ht  = window.theMap.height;
						wid = window.theMap.width;
					}
					else{		// NS etc
						var offsets = getOffsets(E);
						target = E.target;
						ht  = E.target.height;
						wid = E.target.width;
						wx  = offsets.offsetX;
						wy  = offsets.offsetY
					}

					removePopup();

					// if(archiveMode ) {
						// return false;	// Param Value not implemented for archiveMode
					// }

					parameter = checkParam();

					if(parameter === "") {
						unfreezetip("Unimplemented");
					}

					else { // Good parameter
						
//						unfreezetip("Getting Value ...");
//						positiontip(E);
//						blipSpotUrl = Server + "cgi-bin/get_rasp_blipspot.cgi";
//						str = (archiveMode ? "UK%2b0" : ref.Day.value) // %2b == '+'
//						tail = "region=" + str
//							+ "&grid="   + "d2"
//							+ "&day=" + (archiveMode ? (ref.archiveYear.value + ref.archiveMonth.value + ref.archiveDay.value) : "0")
//							+ "&i="      + wx + "&k=" + wy
//							+ "&width="  + wid + "&height=" + ht
//							+ "&linfo="	 +  1
//							+ "&param="	 + parameter
//							;
//						txtPlace = "popUp";
//						// alert("URL = " + blipSpotUrl + "\ntail = " + tail);
//						doCallback(blipSpotUrl, tail);
//						freezetip();
//						tipobj.innerHTML = "See PopUp" ;
//						removePopup();
					}
					break;
				}

				/* CONTROL -> PARAMETER VALUE IN TOOLTIP ****/
				else if(!shiftPressed && ctrlPressed){
					if( ie){		//Internet Exploder
						wx  = event.offsetX;
						wy  = event.offsetY;
						ht  = window.theMap.height;
						wid = window.theMap.width;
					}
					else{		// NS etc
						var offsets = getOffsets(E);
						target = E.target;
						ht  = E.target.height;
						wid = E.target.width;
						wx  = offsets.offsetX;
						wy  = offsets.offsetY
					}

					removePopup();

					// if(archiveMode ) {
						// return false;	// Param Value not implemented for archiveMode
					// }

					parameter = checkParam();

					if(parameter === "") {
						unfreezetip("Unimplemented");
					}

					else { // Good parameter
//						unfreezetip("Getting Value ...");
//						positiontip(E);
//						blipSpotUrl = Server + "cgi-bin/get_rasp_blipspot.cgi";
//						str = (archiveMode ? "UK%2b0" : ref.Day.value) // %2b == '+'
//						tail = "region=" + str
//							+ "&grid="   + "d2"
//							+ "&day=" + (archiveMode ? (ref.archiveYear.value + ref.archiveMonth.value + ref.archiveDay.value) : "0")
//							+ "&i="      + wx + "&k=" + wy
//							+ "&width="  + wid + "&height=" + ht
//							+ "&linfo="	 + 0
//							+ "&time="	 + ref.Time.value + "lst"
//							+ "&param="	 + parameter 
//							;
//						txtPlace = "tip";
//						// alert("URL = " + blipSpotUrl + "\ntail = " + tail);
//						doCallback(blipSpotUrl, tail);
//						freezetip();
//						tipobj.innerHTML = "Getting value ..." ;
//						removePopup();
					}
					break;

				}

			
			/* NOT NEEDED
			case 2:	// MID - was Previous time in day
			alert("Use Ctrl-Shift-LeftClick for Previous Time in Day");
			break;


			case 3:	// RIGHT - was BLIPspot
			// if(archiveMode)
				// return;	// No Params in archiveMode
			alert("Use Ctrl-LeftClick for Parameter Value\nShift-LeftClick for PopUp");
			break;
			*/


			}

			loadImage(dirn);

			return false;		// Defeat normal contextmenu for Firefox
		}

		var txtPlace = "tip";

		function writePopup()
		{
			// paramWindow = window.open('', "BLIPspot", "width=1200,height=200,toolbar=no,location=no,status=no,titlebar=no,resizable=yes" );
			paramWindow = window.open('', "_blank", "resizable=yes,height=200,titlebar=no,scrollbars=yes" );
			paramWindow.focus();
			paramWindow.document.write("<html><head></head><body><pre>" + req.responseText + "</pre></body></html>");
		}


		/******************************************************
		 * Check if param is implemented
		 *
		 * Returns true if not in list of unimplemented params
		 ******************************************************/
		function checkParam()
		{
			var badParams = new Array();
			badParams[0]  = "";
			badParams[1]  = "press850";
			badParams[2]  = "press700";
			badParams[3]  = "press500";
			badParams[4]  = "boxwmax";
			badParams[5]  = "sounding1";
			badParams[6]  = "sounding2";
			badParams[7]  = "sounding3";
			badParams[8]  = "sounding4";
			badParams[9]  = "sounding5";
			badParams[10] = "sounding6";
			badParams[11] = "sounding7";
			badParams[12] = "sounding8";
			badParams[13] = "sounding9";
			badParams[14] = "sounding10";
			badParams[15] = "sounding11";
			badParams[16] = "sounding12";
			badParams[17] = "sounding13";
			badParams[18] = "sounding14";
			badParams[19] = "sounding15";
			badParams[20] = "topo" ;
			badParams[21] = "zblclmask" ;
			badParams[22] = "zsfclclmask" ;
			badParams[23]  = "press1000";
			badParams[24]  = "press950";

			for( i = 0; i < badParams.length; i++) 
				if( ref.Param.value === badParams[i])
					return "" ;

			var newParams = new Array();
			newParams[0]  = "wstar_bsratio";
			newParams[1] = "sfcwind" ;
			newParams[2] = "blwind" ;
			newParams[3] = "bltopwind" ;

			for( i = 0; i < newParams.length; i++) 
				if( ref.Param.value === newParams[i]){
					if(ref.Param.value === "wstar_bsratio")
						return("wstar bsratio");
					if(ref.Param.value === "sfcwind")
						return("sfcwindspd sfcwinddir");
					if(ref.Param.value === "blwind")
						return("blwindspd blwinddir");
					if(ref.Param.value === "bltopwind")
						return("bltopwindspd bltopwinddir");
				}

					return ref.Param.value ;
				}

			
		var req = false;
		var responseText;

		function doCallback(url, data)
		{
			/************************************************/
			/* This stuff needed if running from file://...
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
			} catch (e) {
				alert("Permission UniversalBrowserRead denied.");
			}
			// End This stuff needed
			************************************************/

			if (window.XMLHttpRequest) {
				try {
					req = new XMLHttpRequest();
				}
				catch (e) {
					req = false;
				}
			}
			else if (window.ActiveXObject) {
				// For Internet Explorer on Windows
				try {
					req = new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e) {
					try {
						req = new ActiveXObject("Microsoft.XMLHTTP");
					}
					catch (e) {
						req = false;
					}
				}
			}

			if (req) {
				req.onreadystatechange = processReqChange;
				try {
					req.open('POST', url, true);
				}
				catch (E){
					alert(E);
				}
				req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				req.send(data);
			}
			else  {
				document.println("Failed");
			}
		}

		function processReqChange()
		{
			if (req.readyState == 4) { // only if req shows 'loaded'
				if (req.status == 200) { // only if 'OK'
					// alert("Response = \"" + req.responseText + "\"");
					if(txtPlace === "tip"){
						tipobj.innerHTML = req.responseText;
						// A rather horrible hack to identify 2-line responses
						if(tipobj.innerHTML.indexOf('\n') != tipobj.innerHTML.length - 2){
							tipobj.innerHTML = tipobj.innerHTML.replace(/\n/, (ref.Param.value === "wstar_bsratio" ? " BS: ": " Dirn: ")); 
						}
						// alert("Tip text = " + tipobj.innerHTML);
					}
					else
						writePopup();
				}
				else {
					alert('There was a problem retrieving the XML data: ' + req.responseText);
				}
			}
		}


		/*********************************/
		/* Return false for context Menu */
		/*********************************/
		function retFalse()
		{
			return false;
		}


		/******************/
		/* Which Browser? */
		/******************/
		var ns;
		var ko;
		var ie;
		var op;

		function whichBrowser()
		{
			// alert("Browser = " + navigator.appName);
			ns = navigator.appName === 'Netscape' ;
			ie = navigator.appName === 'Microsoft Internet Explorer' ;
			ko = navigator.appName === 'Konqueror' ;
			op = navigator.appName === 'Opera' ;
		}

		/********************************/
		/* Set Image Size and Callbacks */
		/********************************/
		function setSize()
		{
			var Ht;

			if(ie){
				Ht = document.body.offsetHeight - 44 ;
			}
			else {
				Ht = window.innerHeight - 22;
			}

      document.images[0].height = Ht;
      document.images[0].width  = Ht;

			
      tblHt = document.getElementById("selectors").offsetHeight;
			
			if( tblHt > Ht ){
				ref.Param.size = 1;	// Set the number of Parameters visible
				ref.Time.size = 1;	// Set the number of Times visible
				ref.Day.size = 1;	// Set the number of Days visible
			}

			if( Ht > origTblHt ){		// The big Tables will fit
				ref.Param.size = 15;	// Set the number of Parameters visible
				ref.Time.size = 8;	// Set the number of Times visible
				ref.Day.size = 8;	// Set the number of Days visible
			}

      // NOT NEEDED document.oncontextmenu = retFalse;
    }


		/********************/
		/* Check if Archive */
		/* 0 => normal      */
		/* 1 => archive     */
		/********************/
		var archiveMode = 0;
		var oldArchive = 0;
		var oldArchiveDay;
		var oldArchiveMonth;
		var oldArchiveYear;
		var oldDayIndex;

		function isArchive()
		{
			if((ref.archiveDay.value === "nope1")
				|| (ref.archiveMonth.value === "nope1")
				|| (ref.archiveYear.value === "nope1")){
				archiveMode = 0;
			}
			else
				archiveMode = 1;
		}

		function resetArchive()
		{
			ref.archiveDay.options[0].selected = true;
			ref.archiveMonth.options[0].selected = true;
			ref.archiveYear.options[0].selected = true;
			doChange();
		}



		/***************************/
		/* CallBack from the forms */
		/***************************/
		function doChange()
		{
			if(ref.Param.value === "nope1" ) {
				return 0;		// Catch a stupid selection
			}

			/*
			 *  Descriptions
			 */
			(document.getElementById("desc")).innerHTML = description[ref.Param.selectedIndex] ;

			isArchive();

			if( oldArchive == 0 && archiveMode == 1){	// Change to Archive mode
				oldDayIndex =  ref.Day.options.selectedIndex;
				ref.Day.options[ref.Day.options.selectedIndex].selected = false;
				ref.Day.disabled = true;
				hidetip();
				removePopup();
			}
			else if (oldArchive == 1 && archiveMode == 0){ // Change to Normal mode
				ref.Day.disabled = false;
				ref.Day.options[oldDayIndex].selected = true;
			}


			/* Clear saved images
			 * if changing to / from archiveMode,
			 * or Param or Day changes
			 */
			if(  (oldParam !== ref.Param.value)
				|| (oldDay !== ref.Day.value)
				|| (oldArchive !== archiveMode)
				|| (archiveMode
						&& (		oldArchiveDay 	!= ref.archiveDay.value
								||	oldArchiveMonth != ref.archiveMonth.value
								||	oldArchiveYear  != ref.archiveYear.value
							 )
					 )
				){
				for(i = 0; i < ref.Time.options.length; i++){
					Loaded[i] = false;
				}
			}

			/* Save current values, so can detect change */
			oldParam = ref.Param.value;
			oldDay = ref.Day.value;
			oldArchive = archiveMode;
			oldArchiveDay = ref.archiveDay.value;
			oldArchiveMonth = ref.archiveMonth.value;
			oldArchiveYear  = ref.archiveYear.value;

			/* Load images */
			// Add Topo option
			if(ref.Param.value.match("topo") ) {
				loadImage(0);
			}

			else {
				loadImage(1); // forwards
			}

		}

		/************************************/
		/* Load the Image, and the next one */
		/************************************/


		function loadImage(dirn)
		{
			// Load image and next, depending on direction
			// -1 => backwards
			//  0 => neither
			//  1 => forwards

			var tIdx = ref.Time.selectedIndex;
			var tValue;
			var	imgURL;


			for( i = 0; i < 2; i++){
				if (Loaded[tIdx]) {
					tIdx = (tIdx + dirn) % times.length;
					if (tIdx < 0)
						tIdx = times.length - 1;
					continue;
				}
				tValue = ref.Time.options[tIdx].value;

				if(ref.Param.value === "topo"){
					imgURL = Server
					  + ref.Day.value
						+ "/color_topo.g2.png"
						;
				}
				else {
					if(archiveMode == 1){
						imgURL = Server + "ARCHIVE/"
							+ "UK+0/"
							+ ref.archiveYear.value
							+ "/"
							+ ref.archiveYear.value
							+ ref.archiveMonth.value
							+ ref.archiveDay.value
							+ "/"
							;
							// alert("archiveDate = " + ref.archiveYear.value + " " + ref.archiveMonth.value + " " + ref.archiveDay.value);
					}
					else {
						imgURL =  Server ; // +
						//	+ ref.Day.value
						//	+ "/FCST/"
						//	;
					}
					imgURL += ref.Param.value
							+ ".curr."
							+ tValue
							+ "lst.d2.png";
				}

				/* Removed temporarily and doesn't work properly
				(document.getElementById("imgUrl")).innerHTML = imgURL ;
				*/
				Pics[tIdx].src = imgURL;
				Loaded[tIdx] = true;
				// alert( "imgURL = " + imgURL); // for debugging, tero
				if (dirn === 0)
					break;

				tIdx = (tIdx + dirn) % times.length;
				if (tIdx < 0)
					tIdx = times.length - 1;
			}
			document.images[0].src = Pics[ref.Time.selectedIndex].src;
		}

		/**************************
		 * badimage()             *
		 * Put up a warning image *
		 * if image not found etc *
		 **************************/
		function badImage()
		{
			if(archiveMode)
				document.images[0].src = Server + "noArchive.png";
			else
				document.images[0].src = Server + "noImage.png";
		}



