// ----------------------------------------------------------------
//     				   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_activeTool;
    
    var m_txtXCoord;
    var m_txtYCoord;
    var m_imgLoading;
    var m_imgMapCanvas;
    var m_divMapCanvas;
    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 m_divLegend;
	
	var isPan=false;
	var x1=0;                           //posisjon tid t-1
    var y1=0;
    var x2=0;                           //Posisjon tid t    
    var y2=0;
    
    var loadMapCounter;

	//Variables used to track start position when using panning
	var m_startPanX;
	var m_startPanY;

	// 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;    // Indicates the currently selected tool, where
	var m_ToolModeName  //				+ zoom in  = 1
				        //				+ recenter = 2	

	var m_sClientBrowserType;	// Possible values: "IE", "Netscape"
	var m_sClientPlatform;		// Possible values: "Windows","Mac"
    
    		           // The array that stores the level extent widths				  
	//var m_ExtentWidths = new Array(0.005, 0.015, 0.035, 0.1, 0.3, 0.75, 2, 6, 10, 30, 110);
	var m_ExtentWidths = new Array(10000, 25000, 75000, 150000, 350000, 750000, 1000000, 1250000, 1500000, 1750000, 2000000,2000000);
	var m_ExtentWidths = new Array(10000,12500,15000,18000,22500,30000,37500,52500,67500,97500,127500,150000,200000,250000,325000,450000,575000,700000,850000,1000000,1150000,1300000,1450000,1600000,1750000,1900000,2000000);
	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";
	}

	if (navigator.userAgent.indexOf("Win") >= 0) {
		m_sClientPlatform = 'Windows';
	} else if (navigator.platform.indexOf("Mac") >= 0) {
		m_sClientPlatform = 'Mac';
	} else {
	//	window.location = "unsupported.htm";
	}
    

// *******************************************************************
// *********************** STARTUP FUNCTION **************************
// *******************************************************************

var isNS = false;
var isIE = false;
var isOpera = false;

var detect = navigator.userAgent.toLowerCase();
var browser,thestring;

if (checkIt('opera')) isOpera = true;
else if (checkIt('msie')) isIE = true;
else if (!checkIt('compatible'))
{
	isNS = true;
}


function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function setVariables()

{
    //m_activeTool=document.getElementById("toolname");
	
	////m_radZoomIn = document.getElementById("radZoomIn");
	
	//m_radRecenter = document.getElementById("radRecenter");
	
	
	
	
	//m_imgMapCanvas = document.getElementById("imgMapCanvas1");
    
    //m_imgLoading = document.getElementById("imgLoading");
	//m_divZoomBox = document.getElementById("divZoomBox");
	
	//Brukes denne?
	//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");
	
	
	//Brukes ikke i fobindelse med WMS
	//m_hvMapPage = document.getElementById("hvMapPage");
	
	//m_divLegend=document.getElementById("divLegend");
	
	
	setVariablesServer();
	
	//This code needs to have these elements registered on the page. The component MapCoords is deploying these input-boxes.
	//The variables is used in reportCoords function.
	m_txtXCoord = document.getElementById("txtXCoord");
	m_txtYCoord = document.getElementById("txtYCoord");
	
	
}
function startUp() {

// Purpose: Fires when the page first loads.  


		// Find the HTML tags that will be used throughout the
		// page.
	
	setVariables();
	
	loadMapCounter=0;//No maps have been loaded yet. When this number is equal to the number of maplayers the loadimage can be hidden.
	
		// Create a map coordinate manager.OffsetTop refers to the offset inside av div element. 
	//m_mapViewer = new map(m_imgMapCanvas.offsetLeft+200,
  	//					  m_imgMapCanvas.offsetTop+145+83,
	//					  m_imgMapCanvas.width,	
	//					  m_imgMapCanvas.height,
	//					  m_ExtentWidths,
	//					  new rect(m_hvMinX.value, m_hvMinY.value, m_hvMaxX.value, m_hvMaxY.value)
	//					  );//m_imgMapCanvas.offsetTop+145

		// 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.
	if(m_txtXCoord)
	{
	    m_txtXCoord.value = "";
	    m_txtYCoord.value = "";
    }
		// Assign custom event handlers to mousedown, mousemove, 
		// and mouseup.
	//Add  mouse events
	if(document.addEventListener)//DOM level 2 event model
	{
	    document.addEventListener("mousedown",handleMouseDown,true);
	    document.addEventListener("mousemove",handleMouseMove,true);
	    document.addEventListener("mouseup",handleMouseUp,true);
	
	}
	else if(document.attachEvent)//IE5+ event model
	{
	    document.attachEvent("onmousedown",handleMouseDown);
	    document.attachEvent("onmousemove",handleMouseMove);
	    document.attachEvent("onmouseup",handleMouseUp);

	}
	else//IE 4 event model
	{
	    document.onmousedown = handleMouseDown;
	    document.onmousemove = handleMouseMove;
	    document.onmouseup = handleMouseUp;
	
	}
	
	
	
	//window.onresize=handleResize;
	//window.onmousedown=handleWinM;
	
	// Assign an event handler to the m_imgMapCanvas onload event.
	//m_imgMapCanvas.onload = hideWaitImage;
	
	for( i=0;i<arrMapID.length;i++)
    {
        var m=document.getElementById(arrMapID[i]);
	    m.onload=hideWaitImage;	
	    m.onerror=hideWaitImage;	//if imageloading is unavailable an onerror event is generated. imageLoadErrorEvent;
	   
    }   
	
	    //Request a map.
	//submitMap();
	
	if (typeof m_mapViewer != 'undefined')
			{ 
//			    var extent=m_mapViewer.getExtent();
//			    var w=extent.getWidth();
//			    var h=extent.getHeight();
			    startCoordWidth=m_mapViewer.getExtent().getWidth();
			    startCoordHeight=m_mapViewer.getExtent().getHeight();
			}
 
	
	//Initializes the slider control if  it exists
	  var sliderVal=document.getElementById("sliderZoomValue");   
     var s = new Slider(document.getElementById("slider-1"), document.getElementById("slider-input-1"), "vertical");
     s.setValue(sliderVal.value);
    s.setMinimum(1);
    s.setMaximum(27);
   
    s.onchange = function () 
    {
	//document.getElementById("h-value").value = s.getValue();
	//document.getElementById("h-min").value = s.getMinimum();
	//document.getElementById("h-max").value = s.getMaximum();
//	s.setValue(s.getValue());
//	s.setMinimum(s.getMinimum());
//	s.setMaximum(s.getMaximum());
	document.getElementById("sliderZoomValue").value=s.getValue();
	//Change imgMapSize only if a map is present on the html form.
	if (typeof m_mapViewer != 'undefined')
	{
	    //if(sliderVal.value==s.getValue())
	    {
	        m_mapViewer.resizeMapFromZoomSlider(startCoordWidth,startCoordHeight,s.getValue());
	    }
	}
	
    };
    
    

    window.onresize = function () {
	s.recalculate();
	
	};
	
}
function imageLoadErrorEvent(evt)
{
alert('error loading image');
}
function handleWinM(evt)
{
alert('window click');
}
function handleResize(evt)
{
alert('Resize');
}
// *******************************************************************
// *********************** EVENT HANDLERS  ***************************
// *******************************************************************
///////////////////////////7
/////////////////////////////7
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 (!evt) evt = window.event; // works on IE, but not NS (we rely on NS passing us the event)

    if (evt)
    { 
        if (evt.pageX || evt.pageY)
        { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
          eventX = evt.pageX;
          eventY = evt.pageY;
          
        }
        else if (evt.clientX || evt.clientY)
        { // works on IE6,FF,Moz,Opera7
          //eventX = evt.clientX + document.body.scrollLeft;
          //eventY = evt.clientY + document.body.scrollTop;
          
         eventX = evt.clientX+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
         eventY = evt.clientY +(document.documentElement.scrollTop ?   document.documentElement.scrollTop : document.body.scrollTop);

          
        }
    }
    ///////////////
	//alert(' ' + evt.button);
	//alert(' ' +evt);
    //alert('HandleMouseDown before over map');
	
	// Check to see if click is over map
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 
//	alert('HandleMouseDown after over map');
//	alert('Aktiv verktøy:'+m_activeTool.value);
	switch(m_activeTool.value) {
		case 'zoomin': // zoom in mode
		//alert(' ' +m_sClientBrowserType +' '+isOpera);
//			if ((m_sClientBrowserType == 'IE') && (m_sClientPlatform == 'Windows'))
			if (isIE)
			{
	  		// 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(); 
			}
			//alert('ZoomBox.Show starter');
			m_zbxZoom.show();
			m_zbxZoom.start(eventX, eventY);
			if(evt.stopPropagation)
              {
                evt.stopPropagation();
              }else
              {
              evt.cancelBubble=true;
              }
              if(evt.preventDefault)
              {
                evt.preventDefault();
              }
              else
              {
                evt.returnValue=false;
              }
			break;
		case 'zoomout':
			if (isIE) {
	  		// 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);
			if(evt.stopPropagation)
              {
                evt.stopPropagation();
              }else
              {
              evt.cancelBubble=true;
              }
              if(evt.preventDefault)
              {
                evt.preventDefault();
              }
              else
              {
                evt.returnValue=false;
              }
			break;
		case 'recenter': // recenter mode
  			
  			
  			//var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
			//m_mapViewer.recenter(ptUserClick);
			//Request a new map.
			//submitMap();
			break;
		case 'identify':
			break;
		case 'pan':
		    startPan(evt,eventX,eventY);
		    isPan=true;
		    if (isIE)
			{
	  		// 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(); 
			}
		    if(evt.stopPropagation)
              {
                evt.stopPropagation();
              }else
              {
              evt.cancelBubble=true;
              }
              if(evt.preventDefault)
              {
                evt.preventDefault();
              }
              else
              {
                evt.returnValue=false;
              }
		    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 (!evt) evt = window.event; // works on IE, but not NS (we rely on NS passing us the event)

  if (evt)
  { 
    if (evt.pageX || evt.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      eventX = evt.pageX;
      eventY = evt.pageY;
      
    }
    else if (evt.clientX || evt.clientY)
    { // works on IE6,FF,Moz,Opera7
     // eventX = evt.clientX + document.body.scrollLeft;
     // eventY = evt.clientY + document.body.scrollTop;
      eventX = evt.clientX+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
      eventY = evt.clientY +(document.documentElement.scrollTop ?   document.documentElement.scrollTop : document.body.scrollTop);      
    }
   
   } ///////////////

    // If the mouse isn't currently over the map, we
    // have nothing to do.
	if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;
	} 		
	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.
  if (m_activeTool.value == 'zoomin' || m_activeTool.value == 'zoomout') 
  {
	if (m_zbxZoom.isInProgress) {
		m_zbxZoom.update(eventX, eventY);
	}
	
  }
  if(m_activeTool.value=='recenter')
  {
  
  }
  
  
  if(evt.stopPropagation)
  {
    evt.stopPropagation();
  }else
  {
  evt.cancelBubble=true;
  }
  
  //Note: switch pan1 to pan when pan is switched to recenter.
  //Pan1 is paning the image
  if(m_activeTool.value=='pan' && isPan==true)
  {
    //Update x2 and y2 with the newest position
    x2=eventX;
    y2=eventY;
    //calculates the clipping and position of the maps
    movePan();
    
  
  }
}
/////////////////////////////////77
////////////////////////////////////
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.
	//m_activeTool=document.getElementById("toolname");
	var eventX;
	var eventY;

	/////////////////
	if (!evt) evt = window.event; // works on IE, but not NS (we rely on NS passing us the event)

  if (evt)
  { 
    if (evt.pageX || evt.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      eventX = evt.pageX;
      eventY = evt.pageY;
      
    }
    else if (evt.clientX || evt.clientY)
    { // works on IE6,FF,Moz,Opera7
     // eventX = evt.clientX + document.body.scrollLeft;
     // eventY = evt.clientY + document.body.scrollTop;
        eventX = evt.clientX+(document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        eventY = evt.clientY +(document.documentElement.scrollTop ?   document.documentElement.scrollTop : document.body.scrollTop);
         
      
    }
   } 
    ///////////////
	if ((m_activeTool.value == 'graph')){
		//Identify code place here
		//Checks if mouse is over map
		if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;}
		var pixelTolerance=10;
		var r=m_mapViewer.getExtent();
		var xDistance=Math.abs(r.getRight()-r.getLeft());
		var searchTolerance=60000;//(xDistance/m_mapViewer.getTagWidth())*pixelTolerance;
		
		var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
		
		var sURL = "SnowGraph.aspx"+
		         "?X="+ptUserClick.x+
				     "&Y="+ptUserClick.y+
				       "&searchT="+searchTolerance;
		//http://imsdal.nve.no/seNorgeGraph/GraphPage.aspx


//This varibale originates from a hidden field generated by mappage.aspx
//It is used to send current language to graphPage via qurystring.
        senorgeLang = document.getElementById('senorgeLanguage');

		var layerid=GetCheckedClickAbleNodes();
		
		//If layerid is empty we should have a test which returned without opening a new winodow
		sURL="http://imsdal.nve.no/seNorgeGraph/GraphPage.aspx"+
		         "?X="+ptUserClick.x+
				     "&Y="+ptUserClick.y+
				       "&searchT="+searchTolerance+
				            "&layerId="+layerid+
				            "&lang="+senorgeLang.value;;
	//	<PRE>[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])</PRE>
//<P>Where windowFeatures is a comma-separated list of any of the following 
//options and values: </P><PRE>   toolbar[=yes|no]|[=1|0]
 //  location[=yes|no]|[=1|0]
 //  directories[=yes|no]|[=1|0]
 //  status[=yes|no]|[=1|0]
 //  menubar[=yes|no]|[=1|0]
 //  scrollbars[=yes|no]|[=1|0]
 //  resizable[=yes|no]|[=1|0]
 //  width=pixels
 //  height=pixels</PRE>
      //  GetCheckedClickAbleNodes();
		window.open(sURL,"Graf","scrollbars=yes,status=no,menubar=yes,resizable=yes,width=1050,height=1000");
					
					
					
						
		return;
		
	}
	if ((m_activeTool.value == 'webcam'))
	{
	//Identify code place here
		//Checks if mouse is over map
		if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;}
		var pixelTolerance=10;
		var r=m_mapViewer.getExtent();
		var xDistance=Math.abs(r.getRight()-r.getLeft());
		var searchTolerance=(xDistance/m_mapViewer.getTagWidth())*pixelTolerance;
		var sURL="";
		var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
		
		
		//If wbcam layerid is empty we should have a test which returned without opening a new winodow
		sURL="WebCamPage.aspx"+
		         "?X="+ptUserClick.x+
				     "&Y="+ptUserClick.y+
				       "&searchT="+searchTolerance;
				    
				    
		//window.open(sURL,"Web Kamera","scrollbars=yes,status=no,menubar=yes,resizable=yes");
	window.open(sURL,"Web","scrollbars=yes,menubar=yes,resizable=yes");
	}
	
	if ((m_activeTool.value == 'recenter'))
	{
		if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;}
		var ptUserClick = m_mapViewer.toMapPoint(eventX, eventY);
		m_mapViewer.recenter(ptUserClick);
		submitMap();
		return;
	}
	
	if ((m_activeTool.value == 'pan'))
	{
	    //panning is done
	    isPan=false;

       if (isIE) 
	    {
		    document.releaseCapture();
	    }

        
        if (!(m_mapViewer.isEventOverMap(eventX, eventY))) {	
		return;}
		
		var diffx=x1-x2; //calculates the difference between the starting pixel position and the position when mousebutton is released.
        var diffy=y2-y1;
        //Get the extent of the map
        var mapExtent=m_mapViewer.getExtent();
        //calculate how many map units there are per pixel. This should be the same for x and y 
        //if the aspect ratio is the same (as it should be).
        var mapUnitPerPixelX=mapExtent.getWidth()/m_mapViewer.getTagWidth();
        var mapUnitPerPixelY=mapExtent.getHeight()/m_mapViewer.getTagHeight();
        
        //Calculates the offset in map units of the map movement done by den panning.
		var diffMapX=diffx*mapUnitPerPixelX;
		var diffMapY=diffy*mapUnitPerPixelY;
		
		//Set the new extent to the map variable.
		m_mapViewer.setExtent(new rect(mapExtent.getLeft()+diffMapX,mapExtent.getTop()+diffMapY,mapExtent.getRight()+diffMapX,mapExtent.getBottom()+diffMapY));
		//Postback the new extent.
        submitMap();
		return;
	}
	
		
	if (!(m_activeTool.value == 'zoomin') &&  !(m_activeTool.value=='zoomout')){
		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).
	
	//alert(' ' +m_sClientBrowserType +' '+isOpera);
	if (isIE) 
	{
		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
		}
		//if zoom In is activated
		
		if(m_activeTool.value=='zoomin')
		{
			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));
			submitMap();
		}
		if(m_activeTool.value=='zoomout')
		{
			//get the height and width of the zoombox in pixels
			var zwidth=Math.abs(m_zbxZoom.getStartX()-m_zbxZoom.getEndX());
			var zheight=Math.abs(m_zbxZoom.getStartY()-m_zbxZoom.getEndY());
			var xRatio=m_mapViewer.getTagWidth()/zwidth;
			var yRatio=m_mapViewer.getTagHeight()/zheight;
			//Fetches the current maps extent in an  Rect class structure(se Rect.js).
			var r=m_mapViewer.getExtent();
			//Fetches the extent of the map in mapUnits(meters when using UTM).
			var mapWidth=r.getWidth();
			var mapHeight=r.getHeight();
			
			var xAdd=xRatio*mapWidth/2;
			var yAdd=yRatio*mapHeight/2;
	
			var extentLeft = r.getLeft() - xAdd;
			var extentRight = r.getRight() + xAdd;
			var extentTop = r.getTop() + yAdd;
			var extentBottom = r.getBottom() - yAdd;
			
			//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(extentLeft,extentTop,extentRight,extentBottom));
			submitMap();
		}
		
		
	}
	//Request a new map.
	//submit();

}

function handleToolClick(iToolMode) {
	switch(iToolMode.value) {
		case 'zoomin':
			// zoom in mode
			m_imgMapCanvas.style.cursor = "crosshair";
			break;
		case 'zoomout':
			m_imgMapCanvas.style.cursor = "crosshair";
		case 'pan':
			// pan mode
			m_imgMapCanvas.style.cursor = "hand";
			break;
		case 'identify':
			m_imgMapCanvas.style.cursor = "crosshair";				
			break;
		case 'graph':
			m_imgMapCanvas.style.cursor = "crosshair";	
	}
	//m_activeTool.value = iToolMode;
}

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_imgMapCanvas.offsetLeft,
  				    m_imgMapCanvas.offsetTop,
				    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()

    submitMap();
}

function ZoomToLevel(iLevel) {           
	m_mapViewer.setLevel(iLevel);
    //Request a new map.
    submitMap();
}

// *******************************************************************
// ********************** HELPER FUNCTIONS  **************************
// *******************************************************************

function hideWaitImage() {
   
   loadMapCounter=loadMapCounter+1;
   
   
   if(loadMapCounter == arrMapID.length)
   {
    m_zbxZoom.hide();
    m_imgLoading.style.visibility = 'hidden';
   }
//   for( i=0;i<arrMapID.length;i++)
//    {
//        var m=document.getElementById(arrMapID[i]);
//		
//	    m.style.top=(cliptop - m_mapViewer.getTagTop())+'px';
//	    m.style.left=(clipleft - m_mapViewer.getTagLeft())+'px';
//    }   
//   
   
   //The image has loaded and we want to update the TabViewer.aspx frame
  // top.frames[1].document.Form1.submit();
 //if(top.frames[1].document.Form1!=null)
//	{
//		top.frames[1].document.Form1.submit();
//	}
}

function hideWaitImageForNetscape6() {
	if (m_imgMapCanvas.complete) {
		clearInterval(m_lTimerID);
		m_divZoomBox.style.visibility = 'hidden';
		m_imgLoading.style.visibility = 'hidden';
	}
}

function moveEast() {
    m_mapViewer.moveEast();
    submitMap();
}

function moveNorth() {
    m_mapViewer.moveNorth();
    submitMap();
}

function moveSouth() {
    m_mapViewer.moveSouth();
    submitMap();
}

function moveWest() {
    m_mapViewer.moveWest();
    submitMap();
}

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_imgMapCanvas.offsetLeft - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
//		m_divMapBorder.style.top = m_imgMapCanvas.offsetTop - parseInt(m_divMapBorder.style.borderWidth.replace('px',''));
//	} else { // browser must be IE
//		m_divMapBorder.style.left = m_imgMapCanvas.offsetLeft;
//		m_divMapBorder.style.top = m_imgMapCanvas.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_imgMapCanvas.offsetTop - (parseInt(m_divNorth.style.height.replace('px',''))) - borderOffset;
    m_divNorth.style.left = m_imgMapCanvas.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divNorth.style.width.replace('px','')) / 2);    

         //align the SOUTH DIV
    m_divSouth.style.top = m_imgMapCanvas.offsetTop + m_imgMapCanvas.height + borderOffset;
    m_divSouth.style.left = m_imgMapCanvas.offsetLeft + (m_imgMapCanvas.width / 2)- (parseInt(m_divSouth.style.width.replace('px','')) / 2);   
  
         //align the EAST DIV       
    m_divEast.style.top = m_imgMapCanvas.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divEast.style.height.replace('px','')) / 2));
    m_divEast.style.left = m_imgMapCanvas.offsetLeft + m_imgMapCanvas.width + borderOffset;    

         //align the WEST DIV       
    m_divWest.style.top = m_imgMapCanvas.offsetTop + ((m_imgMapCanvas.height / 2) - (parseInt(m_divWest.style.height.replace('px','')) / 2));
    m_divWest.style.left = m_imgMapCanvas.offsetLeft - (parseInt(m_divWest.style.width.replace('px',''))) - borderOffset;   
}

function posLoadingImage() {
    m_imgLoading.style.top = (parseInt(m_imgMapCanvas.style.top.replace('px','')) + (m_imgMapCanvas.height / 2) - (m_imgLoading.height / 2) );
    m_imgLoading.style.left = (parseInt(m_imgMapCanvas.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.
  if(m_txtXCoord)
	{
	    m_txtXCoord.value = " "+(Math.round(ptReport.x)).toString();
	    m_txtYCoord.value = " "+(Math.round(ptReport.y)).toString();
	}
}

function returnActiveTool() {
		
	return m_activeTool;
	//if (m_radZoomIn.checked) {
	//	return 1;
	//} else if(m_radRecenter.checked) {
	//	return 2;
	//}
	
}

function showWaitImage() {
	m_imgLoading.style.visibility = 'visible';
}

function submitMap() {

	//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();


    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();
	
	
	

	
  //updateZoomLevel(m_mapViewer.getLevel());
	showWaitImage();

	//if (navigator.userAgent.indexOf('Netscape6/6') > -1) {
	//	m_lTimerID = setInterval("hideWaitImageForNetscape6();",100);
	//}

 // m_imgMapCanvas.src = sURL;

   	//alert(top.frames[0].document.title);
 //Forces an page reload. Used to update the layerlist in the treview structure
  //top.frames[1].location="TabViewer.aspx";
  //top.frames[1].action="TabViewer.aspx";

//Test
//	if(top.frames[1].document.Form1!=null)
//	{
//		top.frames[1].document.Form1.submit();
//	}
  //Persist extent in Hidden variables
 
 //setTimeout('updateTreeStructureFrame()',1000);
  persistExtent();	
  
  //Set zoomlevel.
  var zoomLevel=m_mapViewer.getLevel();
  document.getElementById("sliderZoomValue").value=zoomLevel;
  
  
  
  
  top.document.aspnetForm.submit();

}
function updateTreeStructureFrame()
{
    //Forces an page reload. Used to update the layerlist in the treview structure
    //top.frames[1].location="TabViewer.aspx";
    //top.frames[1].action="TabViewer.aspx";

    //Test
	//if(top.frames[1].document.Form1!=null)
	{
	//	top.frames[1].document.Form1.submit();
	}
}


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/tick.gif';
			if (i==inLevel) {
			    document.getElementById('imgZoomLevel' + i).src = 'images/tick_selected.gif';
			}
		}
}


//Functions delivered from Geodata AS (Joachim Juell)
function findObjX(name) {
	var obj = document.getElementById(name);
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findObjY(name) {
	var obj = document.getElementById(name);
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
/////////////////////////////////////////////////////
//Added 20.02.2006 by Nils Kristian Orthe
//Purpose : Making a new extent from a centerpoint and a width and 
//          then applying the extent to the map.
//Used by searchResult.
function makeRectFromCenter(ptCenter,width)
{
   
//The necessary javascripts is not initilized.
//There exists no map on the html-browser.
	if(m_mapViewer==null)
	    return;

	var dblX1;
	var dblY1;
	var dblX2;
	var dblY2;
	
	dblX1 = ptCenter.x - (width / 2);
	dblX2 = ptCenter.x + (width / 2);
	dblY1 = ptCenter.y - (width / 2);
	dblY2 = ptCenter.y + (width / 2);    
	 
	var r=new rect(dblX1, dblY1, dblX2, dblY2) ;
	m_mapViewer.setExtent(r);
	//Adding the new extent to the hidden filelds so
	//that the serverside is also updated.
	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 setMapExtentFromSliderValue(sliderVal)
{
    //var r=m_mapViewer.getExtent();
    m_mapViewer.setLevel(sliderVal);
    submitMap()


}
//Initialize the pan function
function startPan(e,mouseX,mouseY)
{
    
     x1=mouseX;
     y1=mouseY;
     x2=x1+1;
     y2=y1+1;

}


//Flytter på kartbildet
function movePan() {

    var xMove = x2-x1;
    var yMove = y2-y1;
    var cLeft = -xMove;
    var cTop = -yMove;
    var cRight = m_mapViewer.getTagWidth(); //iWidth;
    var cBottom =  m_mapViewer.getTagHeight();//iHeight;
    if (xMove>0) {
        cLeft = 0;
        cRight = m_mapViewer.getTagWidth() - xMove;
    }
    if (yMove>0) {
        cTop = 0;
        cBottom = m_mapViewer.getTagHeight() - yMove;
    }       
    clipLayer("theMap",cLeft,cTop,cRight,cBottom); 
    //moveLayer("theMap",xMove+xMapOffset,yMove+yMapOffset);
    moveLayer("theMap",xMove,yMove);
}

//Støttefunksjon for å få lagene til å visualisere tegning av rektangel + bevegelse av kartbildet
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {
	
    var m=document.getElementById(arrMapID[0]);    
//	//Keep original image size when panning
//	//if (!moveing) {
//	var newWidth = clipright - clipleft;
//	var newHeight = clipbottom - cliptop;
	for( i=0;i<arrMapID.length;i++)
    {
        var m=document.getElementById(arrMapID[i]);
		
	    m.style.top=(cliptop - m_mapViewer.getTagTop())+'px';
	    m.style.left=(clipleft - m_mapViewer.getTagLeft())+'px';
    }   
}

//Flytter laget til x,y
function moveLayer(divMap, x, y) {		
	
	var m=document.getElementById(arrMapID[0]);
    for( i=0;i<arrMapID.length;i++)
    {
        var m=document.getElementById(arrMapID[i]);
        m.style.left=x+'px';
        m.style.top=y+'px';
    }
}