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

		/* 
		 * Global Variables
		 */

		var oldDayIndex;
		var Loaded;
		var Pics;

		var Zoom = 1.0;			// Image Zoom factor
		var oldZoom = 1.0;
		var oldleft = 0.0;
		var oldtop = 0.0;
		var	mouseDownPos = {
			X: 0,
			Y: 0
		};
		var	initialMousePos = {
			X: 0,
			Y: 0
		};

		var ffversion;

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

		var paramWindow;
		var origTblHt;

		var enabletip=false;
		var tipobj;
		var pointerobj;
		var	mapObj;

		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).
		var archiveday="nope1";
		var archivemonth="nope1";
		var archiveyear="nope1";
		var reg;
		var d2w2;
		var dayval;
		var N_or_S;


 /***********************
 * 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 = "" ;
		len = ref.Area.length;
		for (i = 0; i <len; i++) {
			if (ref.Area[i].checked) {
				N_or_S = ref.Area[i].value;
			}
		}
		if (N_or_S == "") {
			alert("No Area Chosen");
		}
		oldN_or_S = N_or_S;

		/* There is a bug in FF 1.5 & 2 with DOMMouseScroll - look for ffversion below */
		if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
			ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		}


		/**********************/
		/* 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
		T.setTime(Now - 1 * mS_Day);
		day.options[0] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
		day.options[1] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()] + ' - 1.3Km', dayName[T.getDay()] + 'W2');
		T.setTime(Now + 0 * mS_Day);	
		day.options[2] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()] + " - Today 4Km", dayName[T.getDay()]);
		day.options[3] = new Option("Today - Latest data - 1.3Km ", "W2");

		T.setTime(Now + mS_Day);	// Tomorrow
		day.options[4] = new Option(dayName[T.getDay()] + ' ' + T.getDate() + ' ' + monthName[T.getMonth()], dayName[T.getDay()]);
		T.setTime(Now + 2 * mS_Day);    //Day + 2
		day.options[5] = 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]);
		}

		ref.Time.options[1].selected   = true;				// 0700
		ref.Day.options[2].selected    = true;				// Today 4.0Km
		ref.Param.options[2].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


		mapObj = document.getElementById("theMap");
		setSize();

		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 value");

		mapObj.onmousemove = positiontip;
		mapObj.onmouseout	= obscuretip;
		mapObj.onmouseover	= revealtip;
		mapObj.onmousedown = getPos;
		mapObj.onmouseup   = click;
		pointerobj.onmouseover = positiontip;
		tipobj.onmouseover = positiontip;


		// alert("mapObj.addEventListener = " + mapObj.addEventListener + "\nmapObj.onmousewheel = " + mapObj.onmousewheel);
		/* Mouse Wheel Initialization code */
		/* Doesn't work with Chrome */
		// if (window.addEventListener){
				/** DOMMouseScroll is for mozilla. */
				// mapObj.addEventListener('DOMMouseScroll', wheel, false);
		// }
		/** IE/Opera. */
		/*
		else
			 mapObj.onmousewheel = wheel;
		*/
		if(typeof(mapObj.onmousewheel) != 'undefined' )
			mapObj.onmousewheel = wheel;
		else if(mapObj.addEventListener)
				mapObj.addEventListener('DOMMouseScroll', wheel, false);
		else
			alert("No mouse wheel interface");


}


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

		/**********************************
		* Get Mouse Position on mousedown *
		**********************************/
		function getPos(E)
		{
			if(!E)
				E = window.event;

			initialMousePos.X = mouseDownPos.X = E.clientX;
			initialMousePos.Y = mouseDownPos.Y = E.clientY;
			if(Zoom != 1){
				if(window.addEventListener){
					mapObj.removeEventListener('mousemove', positiontip, false);
					mapObj.addEventListener('mousemove', dragIt, false);
				}
				else{
					mapObj.detachEvent('onmousemove', positiontip);
					mapObj.attachEvent('onmousemove', dragIt);
				}
				if (E.preventDefault)
					E.preventDefault();
				E.returnValue = false;
			}
		}


		function dragIt(E)
		{
			if(!E)
				E = window.event;

			var coords = {
				X: E.clientX,
				Y: E.clientY
			};

			if(ie)
				mapObj.releaseCapture();
			positiontip(E);
			oldleft = oldleft + coords.X - initialMousePos.X;
			oldtop  = oldtop  + coords.Y - initialMousePos.Y;
			initialMousePos.X = coords.X;
			initialMousePos.Y = coords.Y;
			mapObj.style.left = oldleft;
			mapObj.style.top  = oldtop;
			if (E.preventDefault)
				E.preventDefault();
			E.returnValue = false;
		}



		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 = true
			return false
		}

		function positiontip(e)
		{
			if(tipstate === "frozen")
				return;
			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"
				}
				tipobj.style.visibility = "visible"
				if (!nondefaultpos)
					pointerobj.style.visibility = "visible"
			}
		}

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

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

		function unfreezetip(Str)
		{
			removePopup();
			revealtip();
			tipobj.innerHTML = Str;
			tipobj.onmouseover  = positiontip;
			pointerobj.onmouseover  = positiontip;
			mapObj.onmousemove = positiontip;
			tipstate = "";
		}

		function freezetip(){
			if(window.addEventListener){
				mapObj.removeEventListener("mousemove", positiontip, false);
				mapObj.removeEventListener("mouseout", obscuretip, false);
			}
			else{
				mapObj.detachEvent("onmousemove", positiontip);
				mapObj.detachEvent("onmouseout", obscuretip);
			}
			pointerobj.onmouseover = "";
			tipobj.onmouseover = "";
			tipstate = "frozen";
		}

		function revealtip()
		{
			enabletip=true
			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
			var pos = {	// current mouse posn
				X: 0,
				Y: 0
			};

			if(window.addEventListener){
				mapObj.removeEventListener('mousemove',   dragIt,   false);
				mapObj.removeEventListener('mousemove',     positiontip,  false);
			}
			else{
				mapObj.detachEvent('onmousemove', dragIt);
				mapObj.detachEvent('onmousemove', positiontip);

			}

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

			if(!E)	// IE stupidity
				E = window.event;

			// Grab mouse posn immediately
			pos.X = E.clientX;
			pos.Y = E.clientY;

			/*	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 button 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 = w2times;

			switch (buttn) {
			case 1:
				/**** ORDINARY CLICK -> NEXT TIME IN DAY ****/
				if(!shiftPressed && !ctrlPressed){
					if( (Zoom == 1) || (Math.abs(mouseDownPos.X - pos.X) < 5 && Math.abs(mouseDownPos.Y - pos.Y) < 5)){
						// No movmt -> NextTimeInDay
						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();

					parameter = checkParam();

					if((archiveMode == true) || (parameter === "")) {
						unfreezetip("Unimplemented");
					}

					else { // Good parameter
						
						unfreezetip("Getting Value ...");
						positiontip(E);
						blipSpotUrl = Server + "rasptable/get_rasp_blipspot.cgi";
						str = (archiveMode ? "UK%2b0" : ref.Day.value) // %2b == '+'
						if (ref.Day.options[0].selected == true || ref.Day.options[1].selected == true )
 						  { dayval = -1 ; }
						else { dayval = 0 ; }
						tail = "region=" + reg
							+ "&grid="   + d2w2
							+ "&day=" + dayval
							+ "&i="      + wx + "&k=" + wy
							+ "&width="  + wid + "&height=" + ht
							+ "&linfo="	 +  1
//							+ "&param="	 + parameter
							;
						txtPlace = "popUp";
						//alert("URL1 = " + 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();

					parameter = checkParam();

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

					else { // Good parameter
						unfreezetip("Getting Value ...");
						positiontip(E);
						freezetip("Getting Value ...");
						blipSpotUrl = Server + "rasptable/get_rasp_blipspot.cgi";
						//blipSpotUrl = "file:///usr/lib/w3m/" + "cgi-bin/get_rasp_blipspot.cgi";
						str = (archiveMode ? "UK%2b0" : ref.Day.value) // %2b == '+'
						if (ref.Day.options[0].selected == true || ref.Day.options[1].selected == true )
						    { dayval = -1 ; }
						else { dayval = 0 ; }
						tail = "region=" + reg
							+ "&grid="   + d2w2
							+ "&day=" + dayval
							+ "&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);
						tipobj.innerHTML = "Getting value ..." ;
						removePopup();
					}
					break;

				}

			
			case 2:	// MID - was Previous time in day: Now Reset Zoom
			Zoom = 1.0;
			setSize();
			break;


			/* NOT NEEDED
			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);

			if (E.preventDefault)
				E.preventDefault();
			E.returnValue = false;
			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('', "Parameter_Values", 					"resizable=yes,dependent=yes,location=no,height=400,screenY=50,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" ;

			/* Identify the Vector Params */
			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;
					}
				}
			}
			url = 'http://www.soaringpredictor.info/rasptable/get_rasp_blipspot.cgi?&' + data;
			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 for 2-line responses
						if(req.responseText.lastIndexOf('\n') - req.responseText.indexOf('\n') > 1){
							tipobj.innerHTML = req.responseText.replace(/\n/, (ref.Param.value === "wstar_bsratio" ? " BS: ": " Dir: ")); 
						}
						// alert("Tip text = " + tipobj.innerHTML);
					}
					else
						writePopup();
				}
				else {
					alert('req.status = '+ req.status + ' There was a problem retrieving the XML data: ' + req.responseText);
				}
			}
		}


		/******************/
		/* 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' ;
		}


		/** Event handler for mouse wheel event */
		function wheel(event){
			var delta = 0;

			if (!event) /* For IE. */
				event = window.event;
			if (event.wheelDelta) { /* IE/Opera. */
				delta = event.wheelDelta/120;
				/** In Opera 9, delta differs in sign as compared to IE */
				if (window.opera)
					delta = -delta;
			} else if (event.detail) { /** Mozilla case. */
				/*
				 * In Mozilla, sign of delta is different than in IE.
				 * Also, delta is multiple of 3.
				 */
				delta = -event.detail/3;
			}

			/* Bug in FF < 3
			 * Correct values for clientX appear as screenX 
			 * See http://extjs.com/forum/showthread.php?t=20298
			 */
			if(ns && ffversion < 3){
				var eventCoords = {
					X: event.screenX,
					Y: event.screenY
				};
			}
			else if(event.clientX){
				var eventCoords = {
					X: event.clientX,
					Y: event.clientY
				}
			}

			/* If delta is nonzero, handle it.
			 * delta > 0 if wheel was scrolled up,
			 * delta < 0 if wheel was scrolled down.
			 */

			if (delta) {
				oldZoom = Zoom;
				if (delta < 0){
					Zoom /= 1.05;
				if(Zoom < 1)
					Zoom = 1.0;
				}
				else{
					Zoom *= 1.05;
				}
				zoomIt(eventCoords);
			}

			/* Prevent default actions caused by mouse wheel */
			if (event.preventDefault)
				event.preventDefault();
			event.returnValue = false;
		}

		function zoomIt(coords)
		{
			var	mapDiv;
			var	siz;
			var	X, Y;

			unfreezetip("Ctl-Click for value");

			siz = Number(document.getElementById("imgBox").style.height.replace(/px/, ""));

			X = coords.X;
			Y = coords.Y;
			oldleft = Zoom * (oldleft - X) / oldZoom + X;
			oldtop  = Zoom * (oldtop  - Y) / oldZoom + Y;

			mapObj.style.left = oldleft;
			mapObj.style.top  = oldtop;
      mapObj.style.height   = Zoom * siz;
      mapObj.style.width    = Zoom * siz;
			// alert("W = " + mapObj.style.width + " " + Zoom + " * " + siz);

		}




		/***************************/
		/* Set Initial Image Size  */
		/***************************/
		function setSize()
		{
			var Ht;
			var newMap;
			var mapBox;
			var mapDiv;

			if (Zoom != 1.0)
				return;		// Don't mess with it if zoomed


			// Deal with the Padding round the image
			if(ie){
				Ht = document.body.offsetHeight - 44 ;
			}
			else {
				Ht = window.innerHeight - 22;
			}

			oldleft = 0;
			oldtop  = 0;

			mapBox = document.getElementById("imgBox");
			mapBox.style.left     = 0  + "px" ;
			mapBox.style.top      = 0  + "px";
			mapBox.style.height   = Ht + "px";
			mapBox.style.width    = Ht + "px";
			mapBox.style.overflow = "hidden" ;

			mapObj.style.height = Ht + "px";
			mapObj.style.width  = Ht + "px";
			mapObj.style.left   = 0  + "px";
			mapObj.style.top    = 0  + "px";
			mapObj.style.position = "absolute";


			/* Now do the Selectors */

			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 = 20;	// 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
			}
    }


		/********************/
		/* 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;
			archiveMode = 0;
		}

		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
			}

			/**  Check North or South indicator **/

			len = ref.Area.length;
			for (i = 0; i <len; i++) {
				if (ref.Area[i].checked) {
					N_or_S = ref.Area[i].value;
				}
			}
			if (N_or_S == "") {
				alert("No Area Chosen");
			}

			isArchive();
			unfreezetip("Ctl-Click for value");

			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;
			}
			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)
				|| (oldN_or_S !== N_or_S)
				){
				for(i = 0; i < ref.Time.options.length; i++){
					Loaded[i] = false;
				}
			}

			/* Change Times available if necessary */
			if ( oldDay !== ref.Day.value ) {
			  oldrefTimeLen = ref.Time.options.length;
			  oldTimeIndex =  ref.Time.options.selectedIndex;
			  ref.Time.options.length = 0;
			  if (ref.Day.options[0].selected == true || ref.Day.options[2].selected == true || ref.Day.options[4].selected == true || ref.Day.options[5].selected == true) {
				times = d2times; }
			  else {
				times = w2times; }
			  for (var i = 0; i < times.length; i++) {
				ref.Time.options[i] = new Option(times[i], times[i]); }

			  time_sel = false;
			  if (oldrefTimeLen == ref.Time.options.length) {
 			      ref.Time.options[oldTimeIndex].selected = true;
			      time_sel = true; }

			  if (oldrefTimeLen < ref.Time.options.length) {
	 		      ref.Time.options[oldTimeIndex + 1].selected = true;
			      time_sel = true; }

			  oldTimeIndexMinus = oldTimeIndex -1;
			  if ( oldrefTimeLen > ref.Time.options.length) {
			        if ( ref.Time.options.length > oldTimeIndexMinus && oldTimeIndex > 0) {
				    ref.Time.options[oldTimeIndex -1].selected = true;
				    time_sel = true; }}

			  if (!time_sel) {
			      ref.Time.options[1].selected   = true; }

			}

			/* Change Soundings list if necessary */
			sav_sel = ref.Param.options.selectedIndex;
			if (oldN_or_S !== N_or_S) {
			  Param_len = ref.Param.options.length;
			  for (i = 0; i <Param_len; i++) {
				if (ref.Param.options[i].value == 'sounding1') {
					ref.Param.options.length = i; 
					Param_len = ref.Param.options.length; }
				} 
			   if (N_or_S == 'S') {
				ref.Param.options[ref.Param.options.length]=new Option("#1: Kagel", "sounding1");
				ref.Param.options[ref.Param.options.length]=new Option("#2: Crestline", "sounding2");
				ref.Param.options[ref.Param.options.length]=new Option("#3: Marshall", "sounding3");
				ref.Param.options[ref.Param.options.length]=new Option("#4: Soboba", "sounding4");
				ref.Param.options[ref.Param.options.length]=new Option("#5: Elsinore", "sounding5");
				ref.Param.options[ref.Param.options.length]=new Option("#6: Palomar", "sounding6");
				ref.Param.options[ref.Param.options.length]=new Option("#7: Big Black", "sounding7");
				ref.Param.options[ref.Param.options.length]=new Option("#8: Little Black", "sounding8");
				ref.Param.options[ref.Param.options.length]=new Option("#9: Torrey", "sounding9");
				ref.Param.options[ref.Param.options.length]=new Option("#10: Blossom", "sounding10");
				ref.Param.options[ref.Param.options.length]=new Option("#11: Laguna", "sounding11");
				ref.Param.options[ref.Param.options.length]=new Option("#12: Horse", "sounding12");
				ref.Param.options[ref.Param.options.length]=new Option("#13: Otay Mesa", "sounding13");
			   } 
			   if (N_or_S == 'N') {
				ref.Param.options[ref.Param.options.length]=new Option("#1: Blackhawk", "sounding1");
				ref.Param.options[ref.Param.options.length]=new Option("#2: Ord", "sounding2");
				ref.Param.options[ref.Param.options.length]=new Option("#3: Garlock", "sounding3");
				ref.Param.options[ref.Param.options.length]=new Option("#4: Kagel", "sounding4");
				ref.Param.options[ref.Param.options.length]=new Option("#5: Crestline", "sounding5");
				ref.Param.options[ref.Param.options.length]=new Option("#6: Marshall", "sounding6");
				ref.Param.options[ref.Param.options.length]=new Option("#7: Soboba", "sounding7");
				ref.Param.options[ref.Param.options.length]=new Option("#8: Elsinore", "sounding8");
			   }
                           if (N_or_S == 'M') {
				ref.Param.options[ref.Param.options.length]=new Option("#1: Kagel", "sounding1");
				ref.Param.options[ref.Param.options.length]=new Option("#2: Crestline", "sounding2");
				ref.Param.options[ref.Param.options.length]=new Option("#3: Marshall", "sounding3");
				ref.Param.options[ref.Param.options.length]=new Option("#4: Soboba", "sounding4");
				ref.Param.options[ref.Param.options.length]=new Option("#5: Elsinore", "sounding5");
				ref.Param.options[ref.Param.options.length]=new Option("#6: Palomar", "sounding6");
				ref.Param.options[ref.Param.options.length]=new Option("#7: Big Black", "sounding7");
				ref.Param.options[ref.Param.options.length]=new Option("#8: Little Black", "sounding8");
				ref.Param.options[ref.Param.options.length]=new Option("#9: Torrey", "sounding9");
				ref.Param.options[ref.Param.options.length]=new Option("#10: Blossom", "sounding10");
				ref.Param.options[ref.Param.options.length]=new Option("#11: Laguna", "sounding11");
				ref.Param.options[ref.Param.options.length]=new Option("#12: Horse", "sounding12");
				ref.Param.options[ref.Param.options.length]=new Option("#13: Otay Mesa", "sounding13");
			   } 
			}

			/* Make sure a valid Param is selected */
			if (sav_sel > ref.Param.options.length ) {
				ref.Param.options[1].selected = true; }
			else { ref.Param.options[sav_sel].selected = true;}

			/*
			 *  Descriptions
			 */
			if (N_or_S == "N") {
				(document.getElementById("desc")).innerHTML = descriptionN[ref.Param.selectedIndex] ; }
			else { (document.getElementById("desc")).innerHTML = description[ref.Param.selectedIndex] ; }
			
			/* Save current values, so can detect change */
			oldParam = ref.Param.value;
			oldDay = ref.Day.value;
			oldArchive = archiveMode;
			oldN_or_S = N_or_S;
			oldArchiveDay = 0;
			oldArchiveMonth = 0;
			oldArchiveYear  = 0;

			/* 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;
			var curr;


			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 {
						if (ref.Day.options[0].selected == true || ref.Day.options[1].selected == true ||
							ref.Day.options[2].selected == true || ref.Day.options[3].selected == true) 
							{
								reg = "AVENAL";
								curr = ".curr.";
							} else if (ref.Day.options[4].selected == true) 
							{
								reg = "AVENAL+1";
								curr = ".curr+1.";
							} else
							{
								reg = "AVENAL+2";	
								curr = ".curr+2.";
							}

						imgURL =  Server 
							+ "/RASP/"
							+ reg
							+ "/FCST/"
							;
					}
					if (ref.Day.options[0].selected == true || ref.Day.options[1].selected == true) {
					imgURL += "previous.";
					}
					if (ref.Day.options[1].selected == true || ref.Day.options[3].selected == true) {
					d2w2 = "w2"
					} else d2w2 = "d2";
					if (ref.Param.value.search(/sounding/) != -1) d2w2 = "d2"; // Soundings are always d2
					imgURL += ref.Param.value
							+ curr
							+ tValue
							+ "lst."
							+ d2w2
							+ ".png"
							;
				}
				//alert( "imgURL = " + imgURL);
				/* Removed temporarily and doesn't work properly
				(document.getElementById("imgUrl")).innerHTML = imgURL ;
				*/
				Pics[tIdx].src = imgURL;
				Loaded[tIdx] = true;
				// alert( "imgURL = " + imgURL);
				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";
		}

        /************************************/
        /* Send an image to Google Earth */
        /************************************/
        function DoGoogle()
        {
            //alert( "In Google Function ");
            var imgURL;
            var imgServer = "http://alcald.homelinux.org";
            var region;
            var d2_w2;
            var prev_flag;
            var curr_flag;
            var ref = document.forms[0];	// shorthand
            var tIdx = ref.Time.selectedIndex;
            var HaveGoogle;
            
            HaveGoogle = true;
            //HaveGoogle = probePlugIn("application/vnd.google-earth.kml+xml");
            
            if (HaveGoogle === true)
            {
                //alert ("Have GoogleEarth");
                
                if (ref.Grid.value === "1.3")
                {
                    d2_w2 = "w2";
                }
                else
                {
                    d2_w2 = "d2";
                }
                
                if (ref.Day.value === "curr")
                {
                    prev_flag = "";
                    curr_flag = "curr";
                    region = "AVENAL";
                }
                else if (ref.Day.value === "curr-1")
                {
                    prev_flag = "previous.";
                    curr_flag = "curr";
                    region = "AVENAL";
                }
                else if (ref.Day.value === "curr+1")
                {
                    prev_flag = "";
                    curr_flag = "curr+1";
                    region = "AVENAL+1";
                }
                else
                {
                    prev_flag = "";
                    curr_flag = "curr+2";
                    region = "AVENAL+2";
                }
                //alert ("Made it all the way to imgURL" );
                //alert ("imgServer = " + imgServer);
                //alert ("region = " + region);
                //alert ("prev_flag =" + prev_flag);
                //alert ("ref.Param.value = " + ref.Param.value);
                //alert ("curr_flag = " + curr_flag);
                //alert ("ref.Time.options[tIdx].value = " + ref.Time.options[tIdx].value);
                //alert ("d2_w2 = " + d2_w2);
                
                imgURL =  imgServer
                + "/RASP/AVENAL/FCST/"
                + prev_flag
                + ref.Param.value + "." + curr_flag + "."
                + ref.Time.options[tIdx].value
                + "lst."
                + d2_w2
                + ".png";
                
                //alert( "imgURL = " + imgURL);
                if (ref.Grid.value === "1.3")
                {
                    window.open("http://alcald.homelinux.org/cgi-bin/1.3km.kml?image=" + imgURL);
                }
                else
                {
                    window.open("http://alcald.homelinux.org/cgi-bin/4km.kml?image=" + imgURL);
                }
            }
            else
            {
                //alert ("No GoogleEarth");
            }
        }
        function probePlugIn(mimeType) {
            var havePlugIn = false;
            var tiny = window.open (" ", "teensy", "width=1, height=1");
            if (tiny !=null) {
                if (tiny.document.open(mimeType) !=null)
                havePlugIn = true;
                tiny.close();
            }
            return havePlugIn;
        }
        



