/** Constants for this application */
/** Extent of map service as minx,miny,maxx,maxy - default here is Scotland */
var allBBox = '-283326,499988,783341,1298988';
var allXmin = -283326;
var allYmin = 499988;
var allXmax = 783341;
var allYmax = 1298988;
/** Suppress useless messages! */
window.onerror = killError;
// The width and height of a map generated from a gazeteer search (in metres)
var GAZ_MAP_WIDTH = 12800;
var GAZ_MAP_HEIGHT = 10326.89;
// The width of the map at the maximum zoom level (in metres)
var MAX_ZOOM_WIDTH = 400;
// The multiplier used to scale up zoom levels (see function zoomToLevel)
// Increasing this will make bigger jumps between zoom levels and make the map at zoom level 2
// cover a much bigger area. Decreasing it will have the reverse effect. A multiplier of 1 will
// make everything the same, obviously!
var ZOOM_MULTIPLIER = 2;

   /** 	Update the map based on some user action.
   		VITAL function - this is called by more than one mapping function.
		Takes the global variables set by mapping functions,
		sets some values in the form "fLoader" and makes a new map request to
		the server.
		*/
	function triggerUpdate() {
		document.forms['fLoader'].elements['ZOOMLEVEL'].value = zoomLevel;
		document.forms['fLoader'].elements['SHOW_INSET'].value = showInset;
		document.forms['fLoader'].elements['REFLAYER'].value = refLayer;
		findLayers();
		if (levelZoom == true) {
			if (zoomLevel == 1) {
				document.forms['fLoader'].elements['BBOX'].value = allBBox;
			}
			else {
				document.forms['fLoader'].elements['BBOX'].value = rx1 + ',' + ry1 + ',' + rx2 + ',' + ry2;
			}
			document.forms['fLoader'].elements['SELECTBBOX'].value = '';
			document.forms['fLoader'].elements['X'].value = '';
			document.forms['fLoader'].elements['Y'].value = '';
			hidePage();
			document.forms['fLoader'].submit();
		}
		else if (insetZoom == true) {
			 document.forms['fLoader'].elements['BBOX'].value = rx1 + ',' + ry1 + ',' + rx2 + ',' + ry2;
			 document.forms['fLoader'].elements['SELECTBBOX'].value = '';
			 hidePage();
			 document.forms['fLoader'].submit();
		}
		else {
	 		if (toolStatus == 'SELECT') {
				if ((Math.abs(x2 - x1) > 5) && (Math.abs(y2 - y1) > 5)) {
					 document.forms['fLoader'].elements['SELECTBBOX'].value = x1 + ',' + y1 + ',' + x2 + ',' + y2;
					 document.forms['fLoader'].elements['X'].value = '';
					 document.forms['fLoader'].elements['Y'].value = '';
				}
				else {
					document.forms['fLoader'].elements['SELECTBBOX'].value = '';
					document.forms['fLoader'].elements['X'].value = x1;
					document.forms['fLoader'].elements['Y'].value = y1;
				}
				hidePage();
				document.forms['fLoader'].submit();
			}
			else if (toolStatus == 'IDENTIFY') {
				doQuery(x1, y1);
			}
			else if (toolStatus == 'PAN') {
				document.forms['fLoader'].elements['BBOX'].value = rx1 + ',' + ry1 + ',' + rx2 + ',' + ry2;
				document.forms['fLoader'].elements['SELECTBBOX'].value = '';
				document.forms['fLoader'].elements['X'].value = '';
				document.forms['fLoader'].elements['Y'].value = '';
				hidePage();
				document.forms['fLoader'].submit();
			}
			else {
				var across = Math.abs(rx2 - rx1);
	 			var down = Math.abs(ry2 - ry1);
	 			if ((across > Math.abs(allXmax - allXmin)) || (down > Math.abs(allYmax - allYmin))) {
					rx1 = allXmin;
					ry1 = allYmin;
					rx2 = allXmax;
					ry2 = allYmax;
				}
				else if ((across < MAX_ZOOM_WIDTH) || (down < MAX_ZOOM_WIDTH)) {
					var xRes = (maxx - minx) / iWidth;
					var yRes = (maxy - miny) / iHeight;
					var factor = yRes / xRes;
					var centreX = rx1 + (across / 2);
					var centreY = ry1 + (down / 2);
					rx1 = centreX - (MAX_ZOOM_WIDTH / 2);
					ry1 = centreY - (MAX_ZOOM_WIDTH / 2);
					rx2 = centreX + ((MAX_ZOOM_WIDTH / 2) * factor);
					ry2 = centreY + ((MAX_ZOOM_WIDTH / 2) * factor);
				}
				across = Math.abs(rx2 - rx1);
	 			down = Math.abs(ry2 - ry1);
	 			document.forms['fLoader'].elements['BBOX'].value = rx1 + ',' + ry1 + ',' + rx2 + ',' + ry2;
				document.forms['fLoader'].elements['SELECTBBOX'].value = '';
				document.forms['fLoader'].elements['X'].value = '';
				document.forms['fLoader'].elements['Y'].value = '';
				// Now check the zoom level
	 			var zoomAt = MAX_ZOOM_WIDTH / 2;
				for (i = 9; i > 0; i--) {
					zoomAt = zoomAt * ZOOM_MULTIPLIER;
					if ((across <= zoomAt) && (down <= zoomAt)) {
						 document.forms['fLoader'].elements['ZOOMLEVEL'].value = i;
						 break;
					}
				}
				hidePage();
				document.forms['fLoader'].submit();
			}
		}
	}

	/**	Toggle the base layers on and off.
		*/
	function toggleBaseLayers() {
		if (document.forms['fLoader'].elements['useBaseLayers'].value == 'true' || document.forms['fLoader'].elements['useBaseLayers'].value == 'TRUE') {
			 document.forms['fLoader'].elements['useBaseLayers'].value = 'false';
	    }
	    else document.forms['fLoader'].elements['useBaseLayers'].value = 'true';
	    document.forms['fLoader'].elements['SHOW_INSET'].value = showInset;
    	document.forms['fLoader'].elements['REFLAYER'].value = refLayer;
    	findLayers();
		hidePage();
	    document.forms['fLoader'].submit();
	}

	/** Empty method to suppress on-screen Javascript error messages.
		Occasionally get error is an image is loaded b4 a function etc etc.
		but no problems with page, so don't upset the user.
		*/
	function killError() {
		return true;
	}

	/** Re-submit the "fLoader" form to get a new map, because the vsisble layers have been changed.
		@param isRefChange 	'true' if the change is only of the reference layer - in this case the selected IDs remain.
							'false' or '' if the change is to the radio layer - in this case the selected IDs are cleared.
		*/
	function triggerLayerUpdate(isRefChange) {
		document.forms['fLoader'].elements['ZOOMLEVEL'].value = zoomLevel;
		document.forms['fLoader'].elements['SHOW_INSET'].value = showInset;
		var flist = '';
		var qlist = '';
		findLayers();
		document.forms['fLoader'].elements['SELECTBBOX'].value = '';
		document.forms['fLoader'].elements['X'].value = '';
		document.forms['fLoader'].elements['Y'].value = '';
		if (document.forms['fLoader'].elements['selectedIDs'] && (!isRefChange || (isRefChange == '') || (isRefChange == 'false'))) {
			document.forms['fLoader'].elements['selectedIDs'].value = '';
		}
		hidePage();
		document.forms['fLoader'].submit();
	}

	/** Finds the selected layers from a form ("fLayers") and fills in the relevant values in
		the other form that is used to send information to the server ("fLoader").
		*/
	function findLayers() {
		// Get the layer information.
		// The layer form.
		var theForm = document.forms['fLayers'];
		// The drop down box selection
		var theIndex = theForm .selectLayers.selectedIndex;
		refLayer = theForm.selectLayers.options[theIndex].value;
		// The selected radio button layer.
		var radioLayer = '';
		for (i = theForm.radioLayers.length - 1; i >= 0 ; i--) {
			if (theForm.radioLayers[i].checked) {
				// Add to the layer lists.
				radioLayer = theForm.radioLayers[i].value;
				break;
			}
		}
		if (refLayer != 'None') document.forms['fLoader'].elements['REFLAYER'].value = refLayer;
		else document.forms['fLoader'].elements['REFLAYER'].value = '';
		document.forms['fLoader'].elements['RADIOLAYER'].value = radioLayer;
		document.forms['fLoader'].elements['QUERY_LAYERS'].value = radioLayer;
		if (document.forms['fLoader'].elements['REFLAYER'].value != '') {
			document.forms['fLoader'].elements['LAYERS'].value = document.forms['fLoader'].elements['REFLAYER'].value + ',' + document.forms['fLoader'].elements['RADIOLAYER'].value;
		}
		else {
			document.forms['fLoader'].elements['LAYERS'].value = document.forms['fLoader'].elements['RADIOLAYER'].value;
		}
	}

	/** Clears any selection made in the map by resetting variables in the
		form "fLoader" and re-submitting the request to the server.
		*/
	function clearSelection() {

                // Keith Anderson, 10/12/03
                // Added code to set clearAreas hidden field
                document.forms['fLoader'].elements['clearAreas'].value = 'true';

		document.forms['fLoader'].elements['SELECTBBOX'].value = '';
		document.forms['fLoader'].elements['X'].value = '';
		document.forms['fLoader'].elements['Y'].value = '';
		document.forms['fLoader'].elements['QUERYCOLUMN'].value = '';
		document.forms['fLoader'].elements['QUERYTEST'].value = '';
		document.forms['fLoader'].elements['QUERYVALUE'].value = '';
		if (document.forms['fLoader'].elements['selectedIDs']) document.forms['fLoader'].elements['selectedIDs'].value = '';
		hidePage();
		document.forms['fLoader'].submit();
	}

	/** Used to allow a layers checkbox to be turened on/off programatically.
		Used to allow the user to click on either the text or the checkbox on the map page.
		*/
	function selectLayer(id) {
		if (document.forms['fLayers'].elements[cb].checked) document.forms['fLayers'].elements[cb].checked = false;
		else document.forms['fLayers'].elements[cb].checked = true;
		triggerLayerUpdate();
	}

	/** Resets the map extent to the bounding box of map service (as defined above).
		*/
	function zoomToAll() {
		document.forms['fLoader'].elements['BBOX'].value = allBBox;
		hidePage();
		document.forms['fLoader'].submit();
	}

	/** Updates the global "toolStatus" variable that controls user mouse interaction with
		the map. Also updates some on screen features (buttons, colours).
		@param tool One of IDENTIFY, SELECT, ZOOM_IN, ZOOM_OUT or PAN.
		*/
	function setToolStatus(tool) {
		zoomBoxColor = '#FF0000';
		toolStatus = tool;
		if (toolStatus == 'ZOOM_OUT') {
			MM_nbGroup('down','group1','zoomout','../images/map_zoomout_down.gif',1);
			if (document.all) {
				if (document.all['theMap']) document.all['theMap'].style.cursor = 'crosshair';
			}
		}
		else if (toolStatus == 'PAN') {
			if (document.all) {
				if (document.all['theMap']) document.all['theMap'].style.cursor = 'move';
			}
		}
		else if (toolStatus == 'IDENTIFY') {
			if (document.all) {
				if (document.all['theMap']) document.all['theMap'].style.cursor = 'help';
			}
		}
		else if (toolStatus == 'SELECT') {
			zoomBoxColor = '#0000FF';
			MM_nbGroup('down','group1','select','../images/map_select_down.gif',1);
			if (document.all) {
				if (document.all['theMap']) document.all['theMap'].style.cursor = 'default';
			}
		}
		else {
			toolStatus = 'ZOOM_IN';
			MM_nbGroup('down','group1','zoomin','../images/map_zoomin_down.gif',1);
			if (document.all) {
				if (document.all['theMap']) {
					document.all['theMap'].style.cursor = 'crosshair';
				}
			}
		}
		setLayerBackgroundColor('zoomBoxTop', zoomBoxColor);
		setLayerBackgroundColor('zoomBoxLeft', zoomBoxColor);
		setLayerBackgroundColor('zoomBoxRight', zoomBoxColor);
		setLayerBackgroundColor('zoomBoxBottom', zoomBoxColor);
		for (i = 0; i < document.forms.length; i++) {
			if (document.forms[i].elements['JSMAPTOOL']) document.forms[i].elements['JSMAPTOOL'].value = tool;
		}
	}

	/** Return to the index page and close the map window.
		*/
	function goHome() {
		window.opener.location = './';
		window.opener.focus();
		window.close();
	}

	/**	Makes sure the map is showing and the buttons are interactive.
		Removes the "Loading" layer from the window.
		*/
	function showPage() {
		//Internet Explorer 5+ or Netscape 6
	  	if (document.getElementById) {
	    	document.getElementById('mapPage').style.visibility = 'visible';
	    	document.getElementById('wait').style.visibility = 'hidden';
	    	document.getElementById('glass').style.visibility = 'hidden';
	    }
	  	else if (document.all) {
	    	document.all['mapPage'].style.visibility = 'visible';
	    	document.all['wait'].style.visibility = 'hidden';
	    	document.all['glass'].style.visibility = 'hidden';
	    }
	    else if (document.layers) {
	    	document.layers['glass'].visibility = 'hide';
	    	document.layers['wait'].visibility = 'hide';
	  	}
	}

  	/** Pops up the "Loading" layer in the window.
  		*/
  	function hidePage() {
  		//Internet Explorer 5+ or Netscape 6
		if (document.getElementById) {
			document.getElementById('glass').style.visibility = 'visible';
			document.getElementById('wait').style.visibility = 'visible';
			//document.getElementById('wait').style.left = hspc + (iWidth / 2) - 100;
			//document.getElementById('wait').style.top = vspc + (iHeight / 2) - 30;
		}
		else if (document.all) {
			document.all['glass'].style.visibility = 'visible';
			document.all['wait'].style.visibility = 'visible';
			//document.all['wait'].style.left = hspc + (iWidth / 2) - 100;
			//document.all['wait'].style.top = vspc + (iHeight / 2) - 30;
		}
		else if (document.layers) {
			document.layers['glass'].visibility = 'show';
			document.layers['wait'].visibility = 'show';
			//document.layers['wait'].moveTo(hspc + (iWidth / 2) - 100,  vspc + (iHeight / 2) - 30);
		}
	}

	/** Toggles the inset (or overview) map on and off.
		*/
	function toggleInsetMap() {
		// Get the layer.
		if (showInset == true) {
			showInset = false;
			hideLayer("insetMap");
			hideLayer("mapPosition");
		}
		else {
			showInset = true;
			showLayer("insetMap");
			showLayer("mapPosition");
		}
	}

	/**	Zooms the map to a specific scale level.
		The zoom levels are set by global variables above - MAX_ZOOM_WIDTH and ZOOM_MULTIPLIER.
		At zoom level 9 the map will be MAX_ZOOM_WIDTH across.
		At zoom level 2 the map will be MAX_ZOOM_WIDTH * ZOOM_MULTIPLIER^(9 - 2).
		i.e. if the width at zoom level 9 is 400m and the ZOOM_MULTIPLIER is 2 (the default),
		then the width at zoom level 2 will be 51200m - 400 * 2^7 or 400 * 2 * 2 * 2 * 2 * 2 * 2 * 2
		@param zoom The zoom level - between 1 (the full extent) and 9 (the maximum zoom or smallest extent)
		*/
	function zoomToLevel(zoom) {
		var level;
		if ((zoom < 1) || (zoom == 1)) {
			zoomLevel = 1;
		}
		else {
			if (zoom > 9) zoom = 9;
			level = MAX_ZOOM_WIDTH * Math.pow(ZOOM_MULTIPLIER, 9 - zoom);
			// Reset the zoom level;
			zoomLevel = zoom;
			// Get the centre of the main map.
			var mapCenterX = minx + ((maxx - minx)/2);
			var mapCenterY = miny + ((maxy - miny)/2);
			// Reset the bbox coords.
			// These will be rejigged by ArcIMS to preserve screen resolution.
	   		rx1 = mapCenterX - (level / 2);
			rx2 = mapCenterX + (level / 2);
			ry1 = mapCenterY - (level / 2);
			ry2 = mapCenterY + (level / 2);
		}
		// Set levelZoom to true and update map.
		levelZoom = true;
		triggerUpdate();
		return false;
	}

	/**	Search for a placename or a postcode in response to a user entering text.
		Pulls information from the form "fGaz" and puts it into form "fLoader" before
		re-submitting the form and fetching a new page with the search results.
		*/
	function placenameOrPostcodeSearch() {
		if ((document.forms['fGaz'].elements['placename'].value == '') &&
				(document.forms['fGaz'].elements['postcode'].value == '')) {
			alert('You must type in a postcode or a placename.\nPlease retype your text and try again.');
			return;
		}
		document.forms['fLoader'].elements['placename'].value = document.forms['fGaz'].elements['placename'].value;
		document.forms['fLoader'].elements['postcode'].value = document.forms['fGaz'].elements['postcode'].value;
		document.forms['fLoader'].action = './scrolgazresults.jsp';
		if (document.forms['fLoader'].target) document.forms['fLoader'].target = '_self';
		document.forms['fLoader'].submit();
	}

	/**	Opens the map centred on a specific point.
		Use the global variables GAZ_MAP_WIDTH and GAZ_MAP_HEIGHT to determine how big
		the map should be.
		@param px The centre X point of the map (in metres).
		@param py The centre Y point of the map (in metres).
		*/
	function openMapAt(px, py) {

                rx1 = px - (GAZ_MAP_WIDTH / 2);
		rx2 = px + (GAZ_MAP_WIDTH / 2);
		ry1 = py - (GAZ_MAP_HEIGHT / 2);
		ry2 = py + (GAZ_MAP_HEIGHT / 2);
		var across = Math.abs(rx2 - rx1);
		var down = Math.abs(ry2 - ry1);
		document.forms['fLoader'].elements['BBOX'].value = rx1 + ',' + ry1 + ',' + rx2 + ',' + ry2;
		document.forms['fLoader'].elements['SELECTBBOX'].value = '';
		document.forms['fLoader'].elements['X'].value = '';
		document.forms['fLoader'].elements['Y'].value = '';
		// Now check the zoom level
		var zoomAt = MAX_ZOOM_WIDTH / 2;
		for (i = 9; i > 0; i--) {
			zoomAt = zoomAt * 2;
			if ((across <= zoomAt) && (down <= zoomAt)) {
				 document.forms['fLoader'].elements['ZOOMLEVEL'].value = i;
				 break;
			}
		}
		document.forms['fLoader'].elements['SELECTBBOX'].value = '';
		document.forms['fLoader'].elements['X'].value = '';
		document.forms['fLoader'].elements['Y'].value = '';
		document.forms['fLoader'].submit();
	}