// ----------------------------------------------------------------
//     				   ArcWeb Services Site Starter Client
// ----------------------------------------------------------------
// Purpose:  Manages "active" navigation functionality.  
//           + Manages map coordinate logic.
//           + Uses DHTML to produce rubber-banding effect 
//             when user zooms in or out.  This is handled
//             by the zoomBox class.
// ----------------------------------------------------------------
// Notes:		
// -------------------------------------------------------------------

	// The following variables are global to the page.
	// These vars reference HTML tags in the page whose
	// values may be read or set dynamically.
    var m_radZoomIn;
    var m_radRecenter;
    var m_txtXCoord;
    var m_txtYCoord;
    var m_imgLoading;
    var m_imgMapCanvas;
    var m_divMapBorder;
    var m_divZoomBox;
	var m_divMapTools;
	var m_divNorth;
	var m_divSouth;
	var m_divEast;
	var m_divWest;
    var	m_hvMinX;
    var	m_hvMinY;
    var	m_hvMaxX;
    var	m_hvMaxY;
	var m_hvMapPage;
	var mouseDown = false;
	
	var startX = 0;
	var startY = 0;
	var lastX = 0;
	var lastY = 0;
	
	//number of time the max extent has been exceeded
	var m_MaxExtentExeeded = 0;

	// These vars represent javascript classes that will
	// handle logic.
    var m_mapViewer;  // Object of type map.  Handles map coordinate management.

    var m_zbxZoom;      // Object of type zoombox.  Handles drawing the zoombox.  
				        // Operates entirely within page coordinates and has no 
				        // awareness of the map space or even the image that 
				        // represents the map on the page.

	var m_iToolMode;

    var m_iToolName=new Array();    
    m_iToolName[0] = new Array("","crosshair","");
    m_iToolName[1] = new Array("","crosshair","");
    m_iToolName[2] = new Array("imgCentre","crosshair","Click to centre the map"); //Recentre
    m_iToolName[3] = new Array("","crosshair","");
    m_iToolName[4] = new Array("imgIdentify","help","Click to identify a WLAN Hotspot"); //Identify WLAN
    m_iToolName[5] = new Array("imgEnhancement","crosshair","Click to give coverage feedback"); //Coverage Feedback
	m_iToolName[6] = new Array("imgPan","move",""); //Pan Map
	 
	
	var m_sClientBrowserType;	// Possible values: "IE", "Netscape"
	var m_sClientPlatform;		// Possible values: "Windows","Mac"
    
    
    // The array that stores the level extent widths	(of the map in map units)		  
	//this is vodafone specific, should reflect with the mapservice
	//levels are in order from (fully zoomed in) 1 -> 8 (fully zoomed out)
	//var m_hvMapScales = new Array(20000,50000,100000,250000,750000,2000000,5000000,13000000);
	//var m_ExtentWidths = new Array(2338,5846,11692,29231,87692,233846,584615,1520000);
	var m_hvMapScales;
	var m_ExtentWidths;
	
	var m_lTimerID = 1; // used only for hiding the "Wait" image for Netscape 6.x

	// Determine browser type and platform.
	if (navigator.appName.indexOf("Netscape")>=0) {
		m_sClientBrowserType = 'Netscape';
	} else if (navigator.appName.indexOf('Microsoft') >=0) {
		m_sClientBrowserType = 'IE';
	} else {
		//window.location = "unsupported.htm";
		m_sClientBrowserType = 'IE';
	}

	if (navigator.userAgent.indexOf("Win") >= 0) {
		m_sClientPlatform = 'Windows';
	} 
	else if (navigator.platform.indexOf("Mac") >= 0  && navigator.userAgent.indexOf("Firefox") >=0) 
	{
		m_sClientPlatform = 'Mac';
	}	
	else 
	{
		window.location = "unsupported.htm";
	}

	//possible safari values for macs, from http://en.wikipedia.org/wiki/User_agent
	//v125 on Mac OS X — Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/124 (KHTML, like Gecko) Safari/125 
	//v125 on Mac OS X, cloaked as MSIE — Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2) 
	//v312 on Mac OS X — Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.1 (KHTML, like Gecko) Safari/312 
	//2.0 (v412) on Mac OS X — Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/412 (KHTML, like Gecko) Safari/412 
	
	//check for cloaked MSIE on macs
	if (navigator.userAgent == 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2)')
	{
		window.location = "unsupported.htm";
	}
	else if (navigator.userAgent.indexOf("Opera") >= 0)
	{
		window.location = "unsupported.htm";
	}	
	



// *******************************************************************
// *********************** STARTUP FUNCTION **************************
// *******************************************************************


function startUp() {

	// Purpose: Fires when the page first loads.  
	// Find the HTML tags that will be used throughout the
	// page.
	m_radZoomIn = document.getElementById("radZoomIn");
	m_radRecenter = document.getElementById("radRecenter");
	m_txtXCoord = document.getElementById("txtXCoord");
	m_txtYCoord = document.getElementById("txtYCoord");
	m_imgMapCanvas = document.getElementById("imgMapCanvas");
    m_imgLoading = document.getElementById("imgLoading");
	m_divZoomBox = document.getElementById("divZoomBox");
	m_divMapBorder = document.getElementById("divMapBorder");
  	m_divNorth = document.getElementById("divNorth");
  	m_divSouth = document.getElementById("divSouth");
  	m_divEast = document.getElementById("divEast");
  	m_divWest = document.getElementById("divWest");
  	m_divMapTools = document.getElementById("divMapTools");
	m_hvMinX = document.getElementById("hvMinX");
	m_hvMinY = document.getElementById("hvMinY");
	m_hvMaxX = document.getElementById("hvMaxX");
	m_hvMaxY = document.getElementById("hvMaxY");
	m_hvMapPage = document.getElementById("hvMapPage");
	m_panel = document.getElementById("panelImage");
	//m_hvToolMode = document.getElementById("hvToolMode");
	
	//set the map widths from the scales 
	m_hvMapScales = document.getElementById("hvMapScales").value.split(",");
	m_ExtentWidths = mapScale2ExtentWidths(m_hvMapScales);
	
		// Create a map coordinate manager.
	m_mapViewer = new map((parseInt(m_panel.offsetLeft) + parseInt(m_imgMapCanvas.offsetLeft)),
  						  (parseInt(m_panel.offsetTop) + parseInt(m_imgMapCanvas.offsetTop)),
						  m_imgMapCanvas.width,	
						  m_imgMapCanvas.height,
						  m_ExtentWidths,
						  new rect(m_hvMinX.value, m_hvMinY.value, m_hvMaxX.value, m_hvMaxY.value)
						  );

		// Create a zoom box.
    m_zbxZoom = new zoomBox(m_divZoomBox);
   
        //Orient other page elements - Map Border, Map Tools, Loading Image, Border Navigation.
    posLoadingImage();
    posBorder();
    posBorderNavigation(); //must be called BEFORE posTools()
    posTools();  //must be called AFTER posBorderNavigation()  

		// Initialize the tool mode. 
	//handleToolClick(returnActiveTool());
		
	    // Initialize the X,Y coordinate display.
	m_txtXCoord.value = "X:"
	m_txtYCoord.value = "Y:"

		// Assign custom event handlers to mousedown, mousemove, 
		// and mouseup.
	if (m_sClientBrowserType == 'Netscape') {
		document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
	}
	
	
	document.onmousedown = handleMouseDown;
	document.onmousemove = handleMouseMove;
	document.onmouseup = handleMouseUp;
	
	// Assign an event handler to the m_imgMapCanvas onload event.
	m_imgMapCanvas.onload = hideWaitImage;
	
	//Request a map.
	submit();
}



// *******************************************************************
// *********************** EVENT HANDLERS  ***************************
// *******************************************************************

function handleMouseDown(evt) {
// Purpose:  Any time a mouse button is depressed, this function
//           is given the opportunity to respond to the event.
//
//           For the purposes of the map, we are only interested
//           in the click if it happened within the map area, so 
//           an initial check kicks us out of the function if the
//           click has not occurred in the map area.
//
//           If the click is over the map, then -- depending on
//           the tool mode -- either the zoombox must be started
//           or a recenter must be performed.

	// Get event coordinates by browser-specific means.
	var eventX;
	var eventY;

	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		eventX = event.clientX;
		eventY = event.clientY;
	}

	// Check to see if click is over map
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 
	
	switch(m_iToolMode) {
		case 1: // zoom in mode
			if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
	  		// For IE, a call to "setCapture" is made to ensure that
				// new IE dragging events do not interfere with capturing 
				// the mousemove events -- effectively, this turns off 
				// drag and drop events temporarily.
				m_imgMapCanvas.setCapture(); 
			}
			m_zbxZoom.show();
			m_zbxZoom.start(eventX, eventY);
			break;
			
		// re-centre
		// added a.cox
		case 2: 
				
			//alert("handleMouseDown:m_iToolMode " + m_iToolMode + " recentre");
			doRecentre(eventX, eventY);
			// added a.cox
			m_iToolMode = 2;
			break;

		// wi-fi / wlan hotspot
		// added a.cox
		case 4:
			identify("wlan", eventX, eventY);
				
						
			break;
			
		
		// coverage enhancement
		// added a.cox
		case 5:
			
			//alert("handleMouseDown:m_iToolMode " + m_iToolMode + " enhancement");
			enhancement(eventX, eventY);
			
			//m_iToolMode = 2;
			//toggleOn('imgCentre');
			//toggleOff('imgEnhancement');
				
			
			break;
		case 6:
			
		
			
			if (mouseDown == false){
				mouseDown = true;
				if (m_sClientBrowserType == 'Netscape'){
					BeginDrag(evt);
				} else {
					BeginDrag(event);		
				}
			}
		
			break;
			

	}
}

function handleMouseMove(evt) {
// Purpose:  Any time the mouse moves anywhere on the document, 
//           this function is given the opportunity to respond to 
//           the event.

	// Get event coordinates by browser-specific means.

	var eventX;
	var eventY;

	if (m_sClientBrowserType == 'Netscape') {
		eventX = evt.clientX;
		eventY = evt.clientY;
	} else {
		eventX = event.clientX;
		eventY = event.clientY;
	}

    // If the mouse isn't currently over the map, we
    // have nothing to do.

	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 
	
	if (hitTest('divZoomLevel',eventX, eventY) == false) {
		reportCoords(m_mapViewer.toMapPoint(eventX, eventY)); // update the textbox to reflect
	}			
	
																																												 // the current coordinates.
    // If the current tool is zoom in and a zoombox is in progress, update
    // the zoom box.
  switch(m_iToolMode) {
	case 1:
		if (m_zbxZoom.isInProgress) {
			m_zbxZoom.update(eventX, eventY);
		}
		break;
	case 6:
		//if (mouseDown == true){
		
		
			document.getElementById('imgMapCanvas').alt = "";
			document.getElementById('imgMapCanvas').title = "";
			
			if (m_sClientBrowserType == 'Netscape' && mouseDown == true){
				Dragging(evt);
			} else {
				Dragging(event);		
			}
		
		//}
		break;

  }
}

function handleMouseUp(evt) {
	// Purpose:  Any time a mouse button is released, this function is 
	//					 given the opportunity to respond to the event.

		// If a ZoomBox is not in progress, we've got nothing
		// to do.
	 
		mouseDown = false;
	if (m_iToolMode == 6) {
	
			if (m_sClientBrowserType == 'Netscape'){
				EndDrag(evt);
			} else {
				EndDrag(event);		
			}
	
	}
	
	if (!(m_iToolMode == 1)) {
		return;
	}
	
	

	if (!(m_zbxZoom.isInProgress())) {
		return;
	}
		// Release the capture that was set in the mousedown
		// handler (again, this is something that we have to do because
		// of drag events in IE).
	if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows')) {
		document.releaseCapture();
	}

		// Stop the current effect.
	m_zbxZoom.stop();

		// If the width of the zoom box is less than five pixels,
		// treat is as a single click and zoom in one map level.
		// Otherwise, set the extent to the zoom box.
	if ((Math.abs(m_zbxZoom.getStartX() - m_zbxZoom.getEndX()) < 5) && (Math.abs(m_zbxZoom.getStartY() - m_zbxZoom.getEndY()) < 5))  {	
		var ptUserClick = m_mapViewer.toMapPoint(m_zbxZoom.getStartX(), m_zbxZoom.getStartY());
		if (m_mapViewer.getLevel() == 1) {   //if we reach the minimum zoom level, zoom a fixed amount.
		  m_mapViewer.zoom(0.5);
		} else {
			m_mapViewer.setLevel(m_mapViewer.getLevel() - 1);
     }
		m_mapViewer.recenter(ptUserClick);
  } else {
  		borderWidth = 0;
  		if (m_sClientBrowserType == 'Netscape') {
			borderWidth = 4; // 2 times border width
		}
		var ptStart = m_mapViewer.toMapPoint(m_zbxZoom.getStartX()+borderWidth, m_zbxZoom.getStartY()+borderWidth);
		var ptEnd   = m_mapViewer.toMapPoint(m_zbxZoom.getEndX()+borderWidth, m_zbxZoom.getEndY()+borderWidth);
		m_mapViewer.setExtent(new rect(ptStart.x,ptStart.y,ptEnd.x,ptEnd.y));
	}
	//Request a new map.
	submit();

}

function handleToolClick(iToolMode) {

	switch(iToolMode) {
		case 1:
			// zoom in mode
			//m_imgMapCanvas.style.cursor = "crosshair";
			break;
		case 2:
			// pan mode
			//m_imgMapCanvas.style.cursor = m_iToolName[iToolMode][1];
			document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = "Click to centre the map";			
			toggleOn('imgCentre');
			toggleOff('imgIdentify');
			toggleOff('imgEnhancement');
			//toggleOff('imgPan');
			
			
			break;
		case 3:
			//drag pan
			//m_imgMapCanvas.style.cursor = "pointer";
			break;		
			// wi-fi / wlan
		
		//added a.cox
		case 4:
			if (document.getElementById('mobileDataMap').checked == true
				&&  document.getElementById("mobile_wifi").checked == true
				&&  document.getElementById("mobile_wifi").disabled == ""
				&&  m_mapViewer.getLevel() < 4) { 			
							
				document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = "Click to identify a WLAN Hotspot";
				
				//m_imgMapCanvas.style.cursor = m_iToolName[iToolMode][1]; // "help";
				
				toggleOn('imgIdentify');
				toggleOff('imgCentre');
				toggleOff('imgEnhancement');
				//toggleOff('imgPan');
				
			}else{ //disabled
				alert('Please enable the WLAN Hotspot layer to use the Identify function');
				//handleToolClick(2);
				iToolMode = 2;
				
				//bang
				handleToolClick(iToolMode);
			}
			
			break;
		
		
		case 5:
			// coverage enhancement
			if (m_mapViewer.getLevel() <= 4) { 
				document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = "Click to give coverage feedback";
				//m_imgMapCanvas.style.cursor = m_iToolName[iToolMode][1]; //"crosshair";
				
				toggleOn('imgEnhancement');
				toggleOff('imgCentre');
				toggleOff('imgIdentify');
				//toggleOff('imgPan');
				
			} else {
				alert('Please zoom in further to use the coverage feedback tool');
				iToolMode = 2;
				//bang
				handleToolClick(iToolMode);
				
			}
			break;	
		case 6:
			// drag pan
				//m_imgMapCanvas.style.cursor = m_iToolName[iToolMode][1]; // "grabhand";
				document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = "Pan the map";
				
				//toggleOn('imgPan');
				toggleOff('imgCentre');
				toggleOff('imgIdentify');
				toggleOff('imgEnhancement');
			break;
			
	}
	
	m_iToolMode = iToolMode;
	m_imgMapCanvas.style.cursor = m_iToolName[iToolMode][1];
	document.getElementById('hvToolMode').value = m_iToolMode;
	checkToolMode();
	
}

function ResizeMap(sSize) {

    if (((sSize == 'SMALL') && (m_imgMapCanvas.className == 'SmallMap')) || 
        ((sSize == 'LARGE') && (m_imgMapCanvas.className == 'LargeMap'))) {
        return;
    }
    
    switch(sSize) { 
        case 'SMALL':
        m_imgMapCanvas.className = 'SmallMap';
        break;
        case 'LARGE':
        m_imgMapCanvas.className = 'LargeMap';
        break;
        default: 
        return; // invalid sSize value
    }

        // Create a new map coordinate manager.
    m_mapViewer = new map((m_panel.offsetLeft + imgMapCanvas.offsetLeft),
  				    (m_panel.offsetTop + imgMapCanvas.offsetLeft),
				    m_imgMapCanvas.width,	
				    m_imgMapCanvas.height,
					m_ExtentWidths,
				    m_mapViewer.getExtent()
				    );


        //Orient other page elements - MapSizeImage, Map Border, Map Tools, Loading Image.
    switch(sSize) { 
        case 'SMALL':
        updateImgMapSize('LARGE');
        break;
        case 'LARGE':
        updateImgMapSize('SMALL');
        break;
    }
    
    posLoadingImage();
    posBorder();
    posBorderNavigation(); //must be called BEFORE posTools()
    posTools();  //must be called AFTER posBorderNavigation()

    submit();
}

function ZoomToLevel(iLevel) {           
	m_mapViewer.setLevel(iLevel);
	

	//If toolmode is enhancement and zoomlevel has gone out
	if (iLevel > 4 && m_iToolMode == 5) {
		
		document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = "Click to centre the map";
			m_iToolMode = 2;
			toggleOn('imgCentre');
			toggleOff('imgEnhancement');		
	}
	
	//check the map service switching
	checkMapService();    

    //Request a new map.
    submit();
}

// *******************************************************************
// ********************** HELPER FUNCTIONS  **************************
// *******************************************************************

function hideWaitImage() {
    m_zbxZoom.hide();
    m_imgLoading.style.visibility = 'hidden';
    
    document.getElementById('imgMapCanvas').style.top = 2 + "px";
	document.getElementById('imgMapCanvas').style.left = 2 + "px";
}

function hideWaitImageForNetscape6() {
	if (m_imgMapCanvas.complete) {
		clearInterval(m_lTimerID);
		m_divZoomBox.style.visibility = 'hidden';
		m_imgLoading.style.visibility = 'hidden';
	}
}

//modififed for vodafone
function moveEast() {

	var newCenter = new point(m_mapViewer.getExtent().getCenter().x, 
							m_mapViewer.getExtent().getCenter().y + (m_mapViewer.getExtent().getWidth() * m_mapViewer.getPanFactor()))

	if(isInsideExtent(newCenter))
	{
		m_mapViewer.moveEast();
	    
		//check the map service switching
		checkMapService();    
	    
		submit();
	}
}

//modififed for vodafone
function moveNorth() {

	var newCenter = new point(m_mapViewer.getExtent().getCenter().x, 
							m_mapViewer.getExtent().getCenter().y + (m_mapViewer.getExtent().getHeight() * m_mapViewer.getPanFactor()))

	if(isInsideExtent(newCenter))
	{
		m_mapViewer.moveNorth();

		//check the map service switching
		checkMapService();    
		    
		submit();
	}
}

//modififed for vodafone
function moveSouth() {

	var newCenter = new point(m_mapViewer.getExtent().getCenter().x, 
							m_mapViewer.getExtent().getCenter().y - (m_mapViewer.getExtent().getHeight() * m_mapViewer.getPanFactor()))

	if(isInsideExtent(newCenter))
	{
		m_mapViewer.moveSouth();

		//check the map service switching
		checkMapService();        
	    
		submit();
	}
}

function moveWest() {

	var newCenter = new point(m_mapViewer.getExtent().getCenter().x, 
							m_mapViewer.getExtent().getCenter().y - (m_mapViewer.getExtent().getWidth() * m_mapViewer.getPanFactor()))

	if(isInsideExtent(newCenter))
	{
		m_mapViewer.moveWest();
	    
		//check the map service switching
		checkMapService();        
	    
		submit();
	}
}

function persistExtent() {
	m_hvMinX.value = m_mapViewer.getExtent().getLeft();
	m_hvMinY.value = m_mapViewer.getExtent().getBottom();
	m_hvMaxX.value = m_mapViewer.getExtent().getRight();
	m_hvMaxY.value = m_mapViewer.getExtent().getTop();
}

function posBorder() {

    if (m_sClientBrowserType == 'Netscape') { 
		m_divMapBorder.style.left = m_panel.offsetLeft - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
		m_divMapBorder.style.top = m_panel.offsetTop - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
	} else { // browser must be IE
		m_divMapBorder.style.left = m_panel.offsetLeft;
		m_divMapBorder.style.top = m_panel.offsetTop;
	}
		
    m_divMapBorder.style.width = m_imgMapCanvas.width;
    m_divMapBorder.style.height = m_imgMapCanvas.height;
    m_divMapBorder.style.visibility = "visible";

}

function posBorderNavigation() {

    var borderOffset = 0;    
    if (m_sClientBrowserType == 'Netscape') {
		borderOffset = parseInt(m_divMapBorder.style.borderWidth.replace('px','')) 
	}
   
          //align the NORTH DIV       
    m_divNorth.style.top = m_panel.offsetTop - (parseInt(m_divNorth.style.height.replace('px',''))) - borderOffset;
    m_divNorth.style.left = m_panel.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divNorth.style.width.replace('px','')) / 2);    

         //align the SOUTH DIV
    m_divSouth.style.top = m_panel.offsetTop + m_imgMapCanvas.height + borderOffset + 5;
    m_divSouth.style.left = m_panel.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divSouth.style.width.replace('px','')) / 2);   
  
         //align the EAST DIV       
    m_divEast.style.top = m_panel.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divEast.style.height.replace('px','')) / 2));
    m_divEast.style.left = m_panel.offsetLeft + m_imgMapCanvas.width + borderOffset + 5;    

         //align the WEST DIV       
    m_divWest.style.top = m_panel.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divWest.style.height.replace('px','')) / 2));
    m_divWest.style.left = m_panel.offsetLeft - (parseInt(m_divWest.style.width.replace('px',''))) - borderOffset;   
}

function posLoadingImage() {
    m_imgLoading.style.top = (parseInt(m_panel.style.top.replace('px','')) + (m_imgMapCanvas.height / 2) - (m_imgLoading.height / 2) );
    m_imgLoading.style.left = (parseInt(m_panel.style.left.replace('px','')) + (m_imgMapCanvas.width / 2) - (m_imgLoading.width / 2) );
}

function posTools() {
    m_divMapTools.style.top = parseInt(m_divSouth.style.top.replace('px','')) + parseInt(m_divSouth.style.height.replace('px',''));
    m_divMapTools.style.width = m_imgMapCanvas.width;
}

function reportCoords(ptReport) {
	// Note: Use round() instead of toFixed(), since the latter isn't supported
  //       in IE Mac.
	var xVal = "X: "+(Math.round(ptReport.x)).toString();
	var yVal = "Y: "+(Math.round(ptReport.y)).toString();
	//m_txtXCoord.value = "X: "+(Math.round(ptReport.x)).toString();
	//m_txtYCoord.value = "Y: "+(Math.round(ptReport.y)).toString();

	self.status = xVal + " " + yVal;
	
}

function returnActiveTool() {
	if (m_radZoomIn.checked) {
		return 1;
	} else if(m_radRecenter.checked) {
		return 2;
	}
}

function showWaitImage() {
	m_imgLoading.style.visibility = 'visible';
}


/*
 * set the hidden variable for the map
 *
 */
function setMapDimensions()
{
	//set the new hidden variable for the dimensions of the images
	document.getElementById('hvLeft').value = m_mapViewer.getExtent().getLeft();
	document.getElementById('hvTop').value = m_mapViewer.getExtent().getTop();
	document.getElementById('hvBottom').value = m_mapViewer.getExtent().getBottom();
	document.getElementById('hvRight').value = m_mapViewer.getExtent().getRight();
	document.getElementById('hvImageWidth').value = m_mapViewer.getTagWidth();
	document.getElementById('hvImageHeight').value = m_mapViewer.getTagHeight();
}


/*
 *  added URL parameters for service/gazetteer specific requests
 */
function submit() {


	//added to disable 6 month coverage
	//document.getElementById('coverageFuture').disabled = "disabled";
	//document.getElementById('coverageFuture').title = "Coming Soon";

	if(document.getElementById('hvRefreshMap').value == '')
	{
		
		setMapDimensions();
		
		//this is the wifi layer toggle
		checkWifi();		
		var wifi = ""
		if(		document.getElementById('mobileDataMap').checked == true
			&&  document.getElementById("mobile_wifi").checked == true
			&&  document.getElementById("mobile_wifi").disabled == "")
		{
			wifi = "&wifi=on";
		}

		//this is the main url string
		var sURL = m_hvMapPage.value+
				"?XMIN="+m_mapViewer.getExtent().getLeft()+
				"&YMIN="+m_mapViewer.getExtent().getBottom()+
				"&XMAX="+m_mapViewer.getExtent().getRight()+
				"&YMAX="+m_mapViewer.getExtent().getTop()+
				"&WIDTH="+m_mapViewer.getTagWidth()+
				"&HEIGHT="+m_mapViewer.getTagHeight() +
				"&service="+document.getElementById('hvMapService').value +
				"&mode=" + document.getElementById('hvMode').value +
				"&modeValue=" + document.getElementById('hvModeValue').value + 
				"&searchEasting=" + document.getElementById('hvSearchEasting').value + 
				"&searchNorthing=" + document.getElementById('hvSearchNorthing').value + 
				"&searchMapService=" + document.getElementById('hvSearchMapService').value + 
				"&searchType=" + document.getElementById('listGazetteerType').value +
				"&activeLayer=" + document.getElementById('hvLayer').value +
				"&scale=" + m_mapViewer.getLevel() +
				wifi;
				
		//alert('sURL=' +sURL);

		updateZoomLevel(m_mapViewer.getLevel());
		
		doGraph(m_mapViewer.getExtent(),document.getElementById('hvMapService').value,document.getElementById('hvLayer').value,document.getElementById('listGazetteerType').value);
		
		//this modifies the toolbar button appearance depending on scale
		var imgIdentify = document.getElementById('imgIdentify');
		var imgEnhancement = document.getElementById('imgEnhancement');
		
		//imgIdentify
		//if (m_mapViewer.getLevel() < 4 && document.getElementById('mobileDataMap').checked == false && document.getElementById("mobile_wifi").checked != true) {
		if (document.getElementById('mobileDataMap').checked == true && document.getElementById("mobile_wifi").checked == true &&  document.getElementById("mobile_wifi").disabled == "") {
			imgIdentify.alt = "Retrieve information about WLAN Hotspots";
			imgIdentify.title = "Retrieve information about WLAN Hotspots";
			imgIdentify.src = imgIdentify.src.replace("_disabled.gif", ".gif");
		} else {
		/*
			var iLen = String(imgIdentify.src).length;
			if (imgIdentify.src.substring(iLen, iLen - 13) != "_disabled.gif"){
				toggleOff('imgIdentify')
				imgIdentify.src = imgIdentify.src.replace(".gif", "_disabled.gif");
				document.getElementById('hvToolMode').value = "2";
				imgIdentify.alt = "WLAN hotspot layer must be enabled";
				imgIdentify.title = "WLAN hotspot layer must be enabled";
				checkToolMode();
			}
			*/
		}
		 
		//imgEnhancement
		if (m_mapViewer.getLevel() <= 4) {
			imgEnhancement.alt = "Coverage Feedback";
			imgEnhancement.title = "Coverage Feedback";
			
			imgEnhancement.src = imgEnhancement.src.replace("_disabled.gif", ".gif");
		} else {
			var iLen = String(imgEnhancement.src).length;
			if (imgEnhancement.src.substring(iLen, iLen - 13) != "_disabled.gif"){
				imgEnhancement.src = imgEnhancement.src.replace(".gif", "_disabled.gif");
				imgEnhancement.alt = "Please zoom in closer";
				imgEnhancement.title = "Please zoom in closer";
			}
		}
				
		
		showWaitImage();

		if (navigator.userAgent.indexOf('Netscape6/6') > -1) {
			m_lTimerID = setInterval("hideWaitImageForNetscape6();",100);
		}

		m_imgMapCanvas.src = sURL;

		//Persist extent in Hidden variables
		persistExtent();	
		
		//reset the mode if it is full extent
		if (document.getElementById('hvMode').value == "fullExtent")
		{
			document.getElementById('hvMode').value = "";
			updateZoomLevel(m_ExtentWidths.length + 1); //top level zoom
			//similar to persistExtent();
		}
	}
	else if(document.getElementById('hvRefreshMap').value == 'search') 
	{
		//do zoom to point for exact match
		zoomToPoint(document.getElementById('listSearchResults'));
	}
	else
	{
		//dont refresh the map now but reset the value
		//document.getElementById('hvRefreshMap').value = "";
		resetRefreshMapValue();
	}
	
CheckComboVis();
}


 //disable combobox visibility if in map view
function CheckComboVis()
{
	
			var selectElements = document.getElementsByTagName("SELECT");
			var searchListBox;
		//alert('PopulateSearchDropdown');
	
	//document.getElementById('searchValue').value = "";

	for(var elementCounter = 0; elementCounter < selectElements.length; elementCounter++)
	{
		// drop down we are looking for is an ASP.NET control.
		// Therefore ASP.NET alters the name of the control at runtime, so we
		// have to try and find it. The original name gets appended at the end with
		// an underscore - so we can use the underscrore to find it
		var idSplit = selectElements[elementCounter].id.split('_');

		if(idSplit[idSplit.length - 1] == 'comboList')
		{
			// we have found the drop down we are interested in
			selectElements[elementCounter].length = 0;
			searchListBox = selectElements[elementCounter];
			searchListBox.style.visibility = "hidden";
			break;
			alert('found');
		}
	}
		
			
}	



function updateImgMapSize(sSize) {
    m_imgMapSize = document.getElementById("imgMapSize");
    switch(sSize) { 
        case 'SMALL':
            m_imgMapSize.name = 'SMALL';
            m_imgMapSize.src= 'images/smallmap.gif';
        break;
        case 'LARGE':
            m_imgMapSize.name = 'LARGE';
            m_imgMapSize.src= 'images/largemap.gif';
        break;
    }
}

function updateZoomLevel(inLevel) {
        var nLevels = m_ExtentWidths.length;
		for (i=1;i<nLevels+1;i++) {
			document.getElementById('imgZoomLevel' + i).src = 'images/map/tick.gif';
			if (i==inLevel) {
			    document.getElementById('imgZoomLevel' + i).src = 'images/map/tick_selected.gif';
			}
		}
	
}

 /******************************************************************************
 * toggle activation of tool icon
 * added c.harris
 *****************************************************************************/
function toggleOff(element) {
	
	var imgCentre = document.getElementById(element);
	if (imgCentre != null) {
		var iLen = String(imgCentre.src).length;
		if (imgCentre.src.substring(iLen, iLen - 7) == "_on.gif"){
			imgCentre.src = imgCentre.src.replace("_on.gif", ".gif");
		}
	}
}

function toggleOn(element) {
	var imgCentre = document.getElementById(element);
	var iLen = String(imgCentre.src).length;
	if (imgCentre != null) {
		if (imgCentre.src.substring(iLen, iLen - 7) != "_on.gif"){
			imgCentre.src = imgCentre.src.replace("_disabled", "");
			imgCentre.src = imgCentre.src.replace(".gif", "_on.gif");
		}
	}

}

 /******************************************************************************
 * check current tool mode (on page load) and set tool menu appropriately
 * added c.harris
 *****************************************************************************/
function checkToolMode() {
	var toolVal = document.getElementById('hvToolMode').value;
	if (toolVal != undefined && toolVal != ""){
		m_iToolMode = Number(toolVal);
	} else {
		m_iToolMode = 2;
	}
	toggleOff('imgCentre');
	toggleOn(m_iToolName[m_iToolMode][0]);
	
	if (m_iToolName[m_iToolMode][1] != "") {
		m_imgMapCanvas.style.cursor = m_iToolName[m_iToolMode][1];
		
	}
	
	if (m_iToolName[m_iToolMode][2] != "") {
		document.getElementById('imgMapCanvas').title = document.getElementById('imgMapCanvas').alt = m_iToolName[m_iToolMode][2];
		
	}
	
	if (m_iToolMode != 4){
		if (document.getElementById('dgIdentifyResults') != undefined){
			document.getElementById('dgIdentifyResults').style.visibility = "hidden";
			document.getElementById('closeResults').style.visibility = "hidden";
		}
	}
	
}	
	
 /******************************************************************************
 * limit entry into coverage enhancement form text area
 * added c.harris
 *****************************************************************************/
	
function imposeMaxLength(Object, MaxLen)
	{
		return (Object.value.length <= MaxLen);
	}

/******************************************************************************
 * limit entry into coverage enhancement form text area
 * added c.harris
 *****************************************************************************/
function HighlightAll(theField) {
	var tempval= document.getElementById(theField);
	tempval.focus()
	tempval.select()
}

 /******************************************************************************
 * dragging functions
 * added c.harris
 *****************************************************************************/
			
					
			function BeginDrag(e)
			{
				if (m_iToolMode == 6){
				document.getElementById('panelImage').style.clip = "rect(0px 384px 400px 0px)";
				lastX = startX = e.clientX;
				lastY = startY = e.clientY;
				}
			}
			
			function Dragging(e)
			{
				//if (event.button==1&&mouseDown==true){
					if (m_iToolMode == 6){
					if ( (e.which == 1 || event.button == 1) && mouseDown==true){
					
						dx = e.clientX - lastX;
						dy = e.clientY - lastY;
						
						newX = parseInt(document.getElementById('imgMapCanvas').style.left) + dx;
						newY = parseInt(document.getElementById('imgMapCanvas').style.top) + dy;
						
						document.getElementById('imgMapCanvas').style.left = newX + "px";
						document.getElementById('imgMapCanvas').style.top = newY + "px";
						
						lastX = e.clientX;
						lastY = e.clientY;
						
						
													
						return false;
					}
					}

			}
			
			function EndDrag(e)				   
			{
				if (m_iToolMode == 6){
				dx = e.clientX - startX;
				dy = e.clientY - startY;
					
				var centreX = parseInt(document.getElementById('panelImage').style.left.replace('px','')) + parseInt(document.getElementById('imgMapCanvas').style.width.replace('px','')/2 ) - dx;
				var centreY = parseInt(document.getElementById('panelImage').style.top.replace('px','')) + parseInt(document.getElementById('imgMapCanvas').style.height.replace('px','')/2 ) - dy;
				
				doRecentre(centreX, centreY);
				
				//submit();
				
				//reset dragpan
				startX = 0;
				startY = 0;
				lastX = 0;
				lastY = 0;
				}
					
			}
			
 /******************************************************************************
 * close identify results dialog
 * added c.harris
 *****************************************************************************/			
function closeResults() {
    if(document.getElementById('dgIdentifyResults') != undefined){
		document.getElementById('closeResults').style.visibility = "hidden";
		document.getElementById('dgIdentifyResults').style.visibility = "hidden";
	}
}
			
 /******************************************************************************
 * adds the relevant historic search terms to the search drop down based
 * on the selected category
 * added N. Peters
 * modified C. Harris
 *****************************************************************************/			

function PopulateSearchDropdown(catDropDownID)
{
	
	var divSearchForm = document.getElementById('divSearchForm');
	if (divSearchForm != undefined){
	if (divSearchForm.style.visibility == "visible") {
	
	var categoryDropDown = document.getElementById(catDropDownID);

	var selectElements = document.getElementsByTagName("SELECT");
	var searchListBox;
	
	//alert('PopulateSearchDropdown');
	
	//document.getElementById('searchValue').value = "";

	for(var elementCounter = 0; elementCounter < selectElements.length; elementCounter++)
	{
		// drop down we are looking for is an ASP.NET control.
		// Therefore ASP.NET alters the name of the control at runtime, so we
		// have to try and find it. The original name gets appended at the end with
		// an underscore - so we can use the underscrore to find it
		var idSplit = selectElements[elementCounter].id.split('_');

		if(idSplit[idSplit.length - 1] == 'comboList')
		{
			// we have found the drop down we are interested in
			selectElements[elementCounter].length = 0;
			searchListBox = selectElements[elementCounter];
			break;
			//alert('found');
		}
	}

	searchListBox.style.visibility = "hidden";
	
	// clear existing entries
	searchListBox.value='';
	
	var searchLength = "Search".length;
	var cookieNameLength = "searchHistory".length;

	var aCookie = document.cookie.split("; ");
	for(var i = 0; i < aCookie.length; i++)
	{
		if(aCookie[i].length > cookieNameLength)
		{
			var beginText = aCookie[i].substring(0, cookieNameLength);
			
			if(beginText == "searchHistory")
			{
				// we have found the cookie we are interested in
				var cookieText = aCookie[i].substring(cookieNameLength + 1, aCookie[i].length);
				var searchTexts = cookieText.split('&');
				
				for(var j = 0; j < searchTexts.length; j++)
				{
					// assuming we are working with the correct cookie,
					// the first part of the text is not important
					// this begins SearchN where N is an integer value
					// therefore, we shall ignore that part.
					// after the SearchN there is an equals, therefore, 
					// we want the text after the first equals
					//alert(searchTexts[j]);
					var searchText = searchTexts[j];
					var firstEqualsPosition = searchText.indexOf('=') + 1;
					var secondPartOfText = searchText.substring(firstEqualsPosition, searchText.length);
					// now, we have the the text that the server side code
					// created as category_searchText
					// we want to split it in two so we have
					//		a. the category to compare to the currently 
					//			selected value in the drop down passed in
					//		b. the search text to populate the search drop 
					//			down if the above criteria is a match
					var firstUnderScorePosition = secondPartOfText.indexOf('_');
					// must check that it is valid
					if(firstUnderScorePosition > -1)
					{
						var category = secondPartOfText.substring(0, firstUnderScorePosition);
						var actualSearchText = secondPartOfText.substring(firstUnderScorePosition + 1, secondPartOfText.length);
						
						//alert(category + " " + actualSearchText);
						// now must check that the selected value in the drop down
						// passed in is that of the category
						// if it is, add it to the search list
						
						if(category == categoryDropDown.options[categoryDropDown.selectedIndex].value)
						{
							if(searchListBox != null)
							{
								var optn = document.createElement("OPTION");
								
								optn = document.createElement("OPTION");
								optn.text = actualSearchText;
								optn.value = category;
							
								searchListBox.options.add(optn);
								searchListBox.style.visibility = "visible";
							}
						}
					}
				}
			}
		}
	}			
}
}
}
 
// Fix for when users click Back after viewing FAQ for a place name search with multiple options 
function checkValidResults() {
	var LastSearch = document.getElementById('LastSearch').value;
	if (document.getElementById('listSearchResults') != undefined) {
		var listSearchResults = document.getElementById('listSearchResults').value;
		if (LastSearch != '' && listSearchResults != '0') {
			//zoomToPoint(document.getElementById('listSearchResults'));
			
			document.getElementById('divSearchForm').style.visibility = 'hidden';
			document.getElementById('listSearchResults').style.visibility = 'hidden';
			document.getElementById('panelGraph').style.visibility = 'visible';
			CheckComboVis();
		}
	}
}

