// $Header$
////////////////////////////////////////////////////////////////////////////////

// Used to determine whether initalisation has completed
// Mouse over events in mapping_body.jsp should test for this eg.
// onmouseover="if(loaded)imagemapMouseOver()"
// This will prevent functionality be actived by user before map has initialised
var loaded=false;

////////////////////////////////////////////////////////////////////////////////
// The following variables are initalise by mappong_hdr.jsp
////////////////////////////////////////////////////////////////////////////////

// Define the area of the map in metres east and north
var eLeft, eRight, eTop, eBottom;

// Height and width of map in pixcels
var iHeight, iWidth;


// Mode of interaction with map
// 1=in; 2=out; 
var toolMode;

// Top left corner of the map relative to the "div" containing the background image
var hspc, vspc

// The URL to be executed to obtain next map
var formAction

// Array containing the x and y cordinates (pixcels) of "popup" text to be displayed on map
var popuptextx, popuptexty

// The prefix used to name "popup" divs
var popuptextdiv

// Width and height of map browser in pixcels
var browserWidth, browserHeight


////////////////////////////////////////////////////////////////////////////////
// These rectangles are defined in metres North and East)
////////////////////////////////////////////////////////////////////////////////

// Restrict display of map to the following rectangle (metres North and East)
var limitLeft = 0;
var limitRight = 700000.0;
var limitTop = 1300000.0;
var limitBottom = 0;


/////////////////////////////////////////////
// TILED MAPPING
/////////////////////////////////////////////

var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);



////////////////////////////////////////////////////////////////////////////////
// Dimensions & saleses
////////////////////////////////////////////////////////////////////////////////

// How far to pan when using pan buttons
// 0.5 represents half of the map
var panFactor = 0.5;

// Horizontal distance of map in metres
var xDistance = Math.abs(eRight-eLeft);

// Vertical distance of map in metres
var yDistance = Math.abs(eTop-eBottom);

// Half width of map in metres
var xHalf = xDistance / 2;

// Half height of map in metres
var yHalf = yDistance / 2;

// Distance to pan left, right using pan buttons in meters
var panX = xDistance * panFactor;

// Distance to pan up or down using pan buttons in meters
var panY = yDistance * panFactor;

// Number of metrrs per horizontal pixcel
var pixelX = xDistance/iWidth;

// Number of metres per vertical pixcel
var pixelY = yDistance/iHeight;

// Width of lines that make up the zoom box
var zoomBoxSize = 2;

// Width of lines that make up box on overview
var ovBoxSize = 1;


////////////////////////////////////////////////////////////////////////
// The follwoing variables control user interaction with map
/////////////////////////////////////////////////////////////////////////

// Position of map click in pixcels from left of map
var mouseX=0;

// Position of map click in pixcels from top of map
var mouseY=0;

// Position of map click in meters East
var mapX = eLeft;

// Positin of map click in metres North
var mapY = eTop;

// Is the user dragging a zoom box
var zooming = false;

// Is the user draging the map
var panning = false;

// Control the dragging of the zoom box
var x1= 0, y1=0;
var x2=0 , y2=0;
var zleft=0, zright=0, ztop=0, zbottom=0;

// Set to true when request for map is sent
// Prevents multiple zoom ins experience with Mozilla
var sent=false;


///////////////////////////////////////////////////////////////////////////////
// Variables to manage array of Popup text
//////////////////////////////////////////////////////////////////////////////

// The div currently being poped up
var divPopup;

// The id of the div currently being poped up
var divPopupId;

// Off set to ensure mouse is inside div when poped up
var divPopupDelta=-10;

///////////////////////////////////////////////////////////////////////////
// Called from <body onload=""     >
// To load map
////////////////////////////////////////////////////////////////////////////
function loadMap()
{


  // Initialse broswer independent functionality
  // to manage divs and mouse clicks (see dynamicobjects.js)
  initialiseMouse();
  initialiseDivs();

  // Specify functions to handle mouse events
  mouse.ondown  = mapMouseDown;
  mouse.onup    = mapMouseUp;
  mouse.onmove  = mapMouseMove;

  // Initialise zoom butons
  initZoom();

  
  loaded=true;
//  findInitalOffset();

//document.mapForm.X.value = "null";
}


function findFirstFourTiles(minxV, maxxV, minyV, maxyV){

    findFirstTile(minxV, maxyV, 1);
    findFirstTile(maxxV, maxyV, 2);
    findFirstTile(minxV, minyV, 3);
    findFirstTile(maxxV, minyV, 4);
}

var map1minx = 0;
var map1maxy = 0;

function findFirstTile(cX, cY, mapNumber) {

    var notx = ((cX + curZoom.xcor - parseInt(limitLeftTile)) / mmpx)-curZoom.gridx;
    var noty = ((cY + curZoom.ycor - parseInt(limitBottomTile)) / mmpy)-curZoom.gridy;

    var firstminx = (Math.round(notx) * mmpx) + parseInt(limitLeftTile);
    var firstminy = (Math.round(noty) * mmpy) + parseInt(limitBottomTile);
    var firstmaxx = firstminx + mmpx;
    var firstmaxy = firstminy + mmpy;

    if(mapNumber == 1){
        map1minx = firstminx;
        map1maxy = firstmaxy;   
        
    }
//    setTimeout("getImageTile("+firstminx+","+ firstmaxx+","+ firstminy+","+ firstmaxy+","+ curZoom.width+","+ mapNumber+")",5000);
      getImageTile(firstminx, firstmaxx, firstminy, firstmaxy, curZoom.width, mapNumber);
      return true;
}



var count=0;

function getImageTile(minx, maxx, miny, maxy, s, mapNumber) {

if(type == "sbs_"){
	if(curZoom.width == 10000){
		curZoom.layerid = 3;
	}
	if(curZoom.width == 5000){
		if (city == "true"){
			curZoom.layerid = 1;
		}else{
			curZoom.layerid = 2;
		}
	}
}

var urlS = "http://"+tiledMapServer+"/tiles/GetTileMapFinder?" +  "minx=" + minx.toFixed(2) + "&miny=" + miny.toFixed(2) + "&maxx=" + maxx.toFixed(2) + "&maxy=" + maxy.toFixed(2) + "&scale=" + type+ curZoom.width + "&width=" + iWidth + "&height=" + iHeight +"&layerid=" + curZoom.layerid;

try {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
dojo.io.bind({
    url: urlS,
    method: "GET", 
    load: function(type, data, evt){if(count<5){
    	if (data=="WEB-7") {count++; getImageTile(minx, maxx, miny, maxy, s, mapNumber);} 
    	else { count=0; var mapno = "map" + mapNumber; addImage(mapno, data);}}},
    mimetype: "text/plain",
    sync: true
});
} catch (err) {
dojo.io.bind({
    url: urlS,
    method: "GET", 
    load: function(type, data, evt){if(count<5){
    	if (data=="WEB-7") {count++; getImageTile(minx, maxx, miny, maxy, s, mapNumber);} 
    	else { count=0; var mapno = "map" + mapNumber; addImage(mapno, data);}}},
    mimetype: "text/plain",
    sync: true
});
}
}

function setVisibility(objId, sVisibility) {
    var obj = document.getElementById(objId);
    obj.style.visibility = sVisibility;
}

function addImageSrc(id, response){
    // Netscape 4
    if(ns4){
        document.layers[id].src = response;
    }
    // Explorer 4
    else if(ie4){
        document.all[id].src = response;
    }
    // W3C - Explorer 5+ and Netscape 6+
    else if(ie5 || ns6){
        document.getElementById(id).src = response;
    }
    
    //setVisibility(id, "visible");
}

var map1src;
var map2src;
var map3src;
var map4src;

function addImage(id, response){
    if(id == "map1"){
        map1src = response;
    }
    if(id == "map2"){
        map2src = response;
    }
    if(id == "map3"){
        map3src = response;
    }
    if(id == "map4"){
        map4src = response;
    }
}

function setTop(id, px){
    
    // Netscape 4
    if(ns4){
        document.layers[id].style.top = px + 'px';
    }
    // Explorer 4
    else if(ie4){
        document.all[id].style.top = px + 'px';
    }
    // W3C - Explorer 5+ and Netscape 6+
    else if(ie5 || ns6){
        document.getElementById(id).style.top = px+ 'px';
    }
}

function setLeft(id, px){
    
    // Netscape 4
    if(ns4){
        document.layers[id].style.left = px+ 'px';
    }
    // Explorer 4
    else if(ie4){
        document.all[id].style.left = px+ 'px';
    }
    // W3C - Explorer 5+ and Netscape 6+
    else if(ie5 || ns6){
        document.getElementById(id).style.left = px+ 'px';
    }
}

function findInitalOffset(){
    var difTileX = map1minx - eLeft - curZoom.xcor;
    var difTileY = eTop - map1maxy - curZoom.ycor; 

    var initialx = (difTileX/metresPerPixcelX);
    var initialy = (difTileY/metresPerPixcelY);

    addImageSrc("map1", map1src);
    addImageSrc("map2", map2src);
    addImageSrc("map3", map3src);
    addImageSrc("map4", map4src);   
    setStyles(Math.round(initialy), Math.round(initialx));
}
var offsetX=0;
var offsetY=0;
function setStyles(topd, leftd) {
	offsetX = leftd;
	offsetY = topd;
    var topNheight = topd + iHeight;
    var leftNwidth = leftd + iWidth;

    setTop("map1", topd);
    setLeft("map1", leftd); 
    setTop("map2", topd);
    setLeft("map2", leftNwidth);
    setTop("map3", topNheight);
    setLeft("map3", leftd);
    setTop("map4", topNheight);
    setLeft("map4", leftNwidth);
//
//    setTop("circleDiv", circleY);
//    setLeft("circleDiv", circleX);

    setVisibility("map1", "visible");
    setVisibility("map2", "visible");
    setVisibility("map3", "visible");
    setVisibility("map4", "visible");
//	document.mapForm.scale.value = curZoom.width;
//    document.mapForm.X.value = null;
//    document.mapForm.Y.value = null;
}
// Dynamically define the properties of the zoom buttons
var zoomBtns=new Array();

//without offsets
//
zoomBtns[0] =new Zoom("00", "1:2000000", 2000000, 529.1653116 * iWidth, 12, 0, 0, 0.5, 0.5);
zoomBtns[1] =new Zoom("01", "1:1000000",  1000000,  262.5873523 * iWidth, 11, 0, 0, 0.5, 0.5);
zoomBtns[2] =new Zoom("02", "1:500000",  500000, 132.2923366 * iWidth, 10, 0, 0, 0.5, 0.5);
zoomBtns[3] =new Zoom("03", "1:200000",  200000, 52.91635363 * iWidth, 9, 0, 0, 0.5, 0.5);
zoomBtns[4] =new Zoom("04", "1:100000",   100000, 26.45817682 * iWidth, 8, 0, 0, 0.5, 0.5);
zoomBtns[5] =new Zoom("05", "1:50000",   50000, 13.22891311 * iWidth, 7, 0, 0, 0.5, 0.5);
//zoomBtns[6] =new Zoom("06", "1:25000",   25000, 6.614456556 * iWidth, 6, 0, 0, 0.5, 0.5);
zoomBtns[6] =new Zoom("06", "1:25000",   25000, 6.614456556 * iWidth, 6, 0, 0, 0.5, 0.5);
if(type == "sbs_"){
	zoomBtns[7] =new Zoom("07", "1:10000",   10000, 2.645502646 * iWidth, 5, 0, 0, 0.5, 0.5);
}
if(type == "vu_"){
	zoomBtns[7] =new Zoom("07", "1:10000",   10000, 2.645502646 * iWidth, 5, 0, 0, 0.5, 0.5);
}

// with offsets ?
//zoomBtns[0] =new Zoom("00", "1:2000000", 2000000, 529.1653116 * iWidth, 12, 0, 0, 0.5, 0.5);
//zoomBtns[1] =new Zoom("01", "1:1000000",  1000000,  262.5873523 * iWidth, 11, 0, 0, 0.5, 0.5);
//zoomBtns[2] =new Zoom("02", "1:500000",  500000, 132.2923366 * iWidth, 10, 6000, 10000, 0.5, 0.8);
//zoomBtns[3] =new Zoom("03", "1:200000",  200000, 52.91635363 * iWidth, 9, 0, 0, 0.5, 0.5);
//zoomBtns[4] =new Zoom("04", "1:100000",   100000, 26.45817682 * iWidth, 8, 0, 0, 0.5, 0.5);
//zoomBtns[5] =new Zoom("05", "1:50000",   50000, 13.22891311 * iWidth, 7, 1300, 1100, 0.5, 0.8);
//zoomBtns[6] =new Zoom("06", "1:25000",   25000, 6.614456556 * iWidth, 6, 270, 700, 0.5, 0.9);
//
//if(type == "sbs_"){
//zoomBtns[7] =new Zoom("07", "1:10000",   10000, 2.645502646 * iWidth, 5, 215, 170, 0.5, 0.75);
//	if(city == "true"){
//
//zoomBtns[8] =new Zoom("08", "1:5000",   5000, 1.322820978 * iWidth, 4, 105, 50, 0.5, 0.6);
//	}else{
//
//zoomBtns[8] =new Zoom("08", "1:5000",   5000, 1.322820978 * iWidth, 4, 20, 50, 0.5, 0.5);	
//	}
//}
//
//if(type == "vu_"){
//
//zoomBtns[7] =new Zoom("07", "1:10000",   10000, 2.645502646 * iWidth, 5, 100, 80, 0.5, 0.45);
//
//zoomBtns[8] =new Zoom("08", "1:5000",   5000, 1.322820978 * iWidth, 4, 20, 50, 0.5, 0.6);
//}




// Assume initally we are zoomed out
var curZoom=zoomButton[0];
//////////////////////////////////////////////////////////////////////////
// Object to repesent a zoom button
//////////////////////////////////////////////////////////////////////////
// pId   :  "01", "02" ... two character numeric strings to identify button
// pLabel:  Text to be used to describe button eg "100km"
// pWidth:  Width of map to be shown at this scale 
// actWidth:Width of map in actual metres
//////////////////////////////////////////////////////////////////////////
function Zoom(pId, pLabel, pWidth, actWidth,layId, xCorr, yCorr, gridX, gridY){

    // Integer repesenting scale 0 = zoomed right out , 11 = zoomed right in
    this.level  = parseInt(pId,10);

    // id of the button image in page
    this.id     = "zoom"+pId;

    // lable used to describe button eg "100km"
    this.label  = pLabel;

    // Width of map to be shown (metres)
    this.width  = pWidth;

    //Real world distance in x and y plane
    this.acwidth = actWidth;

    // Ensure button images is preload for speed
    this.on     = new Image();
    this.on.src = "/images/maps/zoom_bar_yellow.gif";
    this.off    = new Image();
    this.off.src    = "/images/maps/zoom_bar_white.gif";

    // "alt" label for button
   this.alt    = "Zoom to "+pLabel;
    
    this.layerid = layId;
    
    this.xcor = xCorr;
    
    this.ycor = yCorr;
    
    this.gridx = gridX;
    
    this.gridy = gridY;
    
}

function getObj(id){
var obj;        
    // Netscape 4
    if(ns4){
        obj = document.layers[id];
    }
    // Explorer 4
    else if(ie4){
        obj = document.all[id];
    }
    // W3C - Explorer 5+ and Netscape 6+
    else if(ie5 || ns6){
        obj = document.getElementById(id);
    }
    return obj;
    
}

//////////////////////////////////////////////////////////////////////////
// Initialises zoom bar ad zoom drop down
//////////////////////////////////////////////////////////////////////////
function initZoom(){

    // Define functins used to set hightlight on and off on zoom buttons
    Zoom.prototype.setOn      = new Function("document.images[this.id].src = this.on.src");
    Zoom.prototype.setOff     = new Function("document.images[this.id].src = this.off.src");

    // Get a handle on the sclae drop down list
    var scale = document.mapGo.scale;
    var opts = scale.options;
    
    opts.length=0;


    // Go through all the zoom levels
    for (var i=0;i<zoomBtns.length;i++){

        // Intialise zoom buttons events
       var btn = zoomBtns[i];
//        document.images[btn.id].onblur      = new Function("zoomOff("+i+")");
//        document.images[btn.id].onfocus     = new Function("zoomOn ("+i+")");
//        document.images[btn.id].onmouseover     = new Function("zoomOn ("+i+")");
//        document.images[btn.id].onmouseout      = new Function("zoomOff("+i+")");
//        document.images[btn.id].alt   =     btn.alt;

        // Initialise drop down list with same values as zoom bar
        opts[opts.length] = new Option(i);
        opts[i].text      = btn.label;
    }



    curZoom.setOn();


    // Ensure scale drop down consistent with zoom level
    synchScaleDropDown();

    // Ensure map tools shows current value
    synchToolMode();


}


var scale = 0;
var mmppsc = 0;


//////////////////////////////////////////////////////////////////////////
// Called to switch images as user plays with zoom bar
//////////////////////////////////////////////////////////////////////////
// level: 0 - 11
function zoomOn(level){
    var btn = zoomBtns[level];
    if(curZoom.id!=btn.id)
        btn.setOn();


}
//////////////////////////////////////////////////////////////////////////
// Called to switch images as user plays with zoom bar
//////////////////////////////////////////////////////////////////////////
// level: 0 - 11
function zoomOff(level){
    var btn = zoomBtns[level];
    if(curZoom.id!=btn.id)
        btn.setOff();
}

//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on a button in the zoom bar
//////////////////////////////////////////////////////////////////////////
// level: 0 - 11
function zoomTo(level){
    zoomToLevel(zoomBtns[level], (eLeft +eRight)/2, (eBottom+eTop)/2);

}


//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on a button in the zoom bar -- v2
//////////////////////////////////////////////////////////////////////////
// level: 0 - 11
function zoomToLevelXY(level, x, y){
    zoomToLevel(zoomBtns[level], x, y);

}

//////////////////////////////////////////////////////////////////////////
// Called when the user clicks 'go' having chosen a new scale from drop down
//////////////////////////////////////////////////////////////////////////
function zoomGo(){
    zoomTo(document.mapGo.scale.selectedIndex);
}


//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on the "zoom plus" button in the zoom bar
//////////////////////////////////////////////////////////////////////////
function zoomPlus(){
    if(curZoom.level+1<zoomBtns.length)
        zoomTo(curZoom.level+1);
}

//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on the "zoom plus" button in the zoom bar -- v2
//////////////////////////////////////////////////////////////////////////
function zoomPlusXY(x , y){
    if(curZoom.level+1<zoomBtns.length)
        zoomTo(curZoom.level+1, x ,y);
}

//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on the "zoom minus" button in the zoom bar
//////////////////////////////////////////////////////////////////////////
function zoomMinus(){
    if(curZoom.level>0)
        zoomTo(curZoom.level-1);
}

//////////////////////////////////////////////////////////////////////////
// Called when the user clicks on the "zoom minus" button in the zoom bar -- v2
//////////////////////////////////////////////////////////////////////////
function zoomMinusXY(x , y){
    if(curZoom.level>0)
        zoomTo(curZoom.level-1, x ,y);
}

//////////////////////////////////////////////////////////////////////////
// Called when the user zooms in a level by clicking somwhere on the map
//////////////////////////////////////////////////////////////////////////
// x: metres east
// y: metres north
function zoomIn(x,y) {
      // Netscape seems to be sending two zoom to point events !
      if(sent==true)
        return;
      else
         sent=true;

      if(curZoom.level+1<zoomBtns.length){
    	zoomToLevel(zoomBtns[curZoom.level+1], x, y);  	
      }else{
      	zoomToLevel(zoomBtns[curZoom.level], x, y);  	
      }
    
}

//////////////////////////////////////////////////////////////////////////
// Called when the user zooms out a level by clicking somewhere on the map
//////////////////////////////////////////////////////////////////////////
// x: metres east
// y: metres north
function zoomOut(x,y) {
      // Netscape seems to be sending two zoom to point events !
      if(sent==true)
        return;
      else
         sent=true;

      if(curZoom.level>0){
    zoomToLevel(zoomBtns[curZoom.level-1], x, y);
      }  else{
      	zoomToLevel(zoomBtns[curZoom.level], x, y);  	
      }
}

//////////////////////////////////////////////////////////////////////////
// Given a zoom level and a point, zooms to a envelope centred on that
// point at that level
//////////////////////////////////////////////////////////////////////////
// x: metres east
// y: metres north
function zoomToLevel(zoomBtn, x , y){

    // Construct new rectangle for map
    eLeft       = x - (zoomBtn.acwidth/2);
    eRight      = x + (zoomBtn.acwidth/2);
    eTop        = y + (zoomBtn.acwidth*iHeight/iWidth/2);
    eBottom     = y - (zoomBtn.acwidth*iHeight/iWidth/2);

   // Ensure new rectangle is within limits
    if(eLeft<limitLeft){
        eRight  +=limitLeft-eLeft;
        eLeft   =limitLeft;
    }
    if(eRight>limitRight){
        eLeft   -=eRight-limitRight;
        eRight  =limitRight;
    }
    if(eBottom<limitBottom){
        eTop    +=limitBottom-eBottom;
        eBottom =limitBottom;
    }
    if(eTop>limitTop){
        eBottom -=eTop-limitTop;
        eTop    =limitTop;
    }

    // Highlight new zoom level button
    curZoom.setOff();
    curZoom=zoomBtn;
    curZoom.setOn();

    // Ensure scale drop down shows correct value
    synchScaleDropDown();

    // Send request for new page
    sendMapXMLAfterZooming(x,y);

}

////////////////////////////////////////////////////////////////////////////
// Synchronise sclae drop down list with current zoom level
///////////////////////////////////////////////////////////////////////////
function synchScaleDropDown(){
    var scale = document.mapGo.scale;
    scale.options[curZoom.level].selected=true;
}

///////////////////////////////////////////////////////////////////////
// Called when user select a new tool (radio button)
///////////////////////////////////////////////////////////////////////
// 1=in; 2=out; 
//
function zoomButton(zoomType) {
  toolMode = zoomType;
}

///////////////////////////////////////////////////////////////////////////
// Synchronise map tool radio buttons to correct value
//////////////////////////////////////////////////////////////////////////
function synchToolMode(){
    var tools = document.getElementById("tools");
    for(i=0; i<tools.tools.length;i++){
        if (tools.tools[i].value==toolMode)
            tools.tools[i].checked=true;
    }
}

//////////////////////////////////////////////////////////////////////////
// Given a width return best suited zoom level button
//////////////////////////////////////////////////////////////////////////
function getZoomLevelForWidth(acwidth){
    var rtnBtn=zoomBtns[0];
    for (var i=zoomBtns.length-1; i>=0; i--){
        btn = zoomBtns[i];	
        // Allow 25% margin of error above and below
        if(btn.acwidth+(btn.acwidth/2)>acwidth){
            rtnBtn = btn;
            break;
        }

    }
    return rtnBtn;
}

//////////////////////////////////////////////////////////////////////////
// Called when user clicks a pan button
//////////////////////////////////////////////////////////////////////////
function panButton(panType) {
    

  switch(panType) {

    case 1:
      //west
      eLeft  = eLeft - panX;
      eRight = eLeft + xDistance;
      break
    case 2:
      // north
      eTop    = eTop + panY;
      eBottom = eTop - yDistance;
      break
    case 3:
      // east
      eRight = eRight + panX;
      eLeft  = eRight - xDistance;
      break
    case 4:
      // south
      eBottom = eBottom - panY;
      eTop   = eBottom + yDistance;
      break
    case 5:
      // north west
      eLeft  = eLeft - panX;
      eRight = eLeft + xDistance;
      eTop    = eTop + panY;
      eBottom = eTop - yDistance;
      break
    case 6:
      // north east
      eRight = eRight + panX;
      eLeft  = eRight - xDistance;
      eTop    = eTop + panY;
      eBottom = eTop - yDistance;
      break
    case 7:
      // south east
      eRight = eRight + panX;
      eLeft  = eRight - xDistance;
      eBottom = eBottom - panY;
      eTop   = eBottom + yDistance;
      break
    case 8:
      // south west
      eLeft  = eLeft - panX;
      eRight = eLeft + xDistance;
      eBottom = eBottom - panY;
      eTop   = eBottom + yDistance;
      break
          
  }

  sendMapXML();

  return;

}

//////////////////////////////////////////////////////////////////////////////////
// Determine the position of mouse event in pixcels
// from the top left corner of map and in metres east and north
//////////////////////////////////////////////////////////////////////////////////
function getImageXY(e) {

    // mouse is the broswer indepenent object that gives the x and y
    // of the mouse event in pixcels relative to top left of
    // browesr window
    mouseX=mouse.x;
    mouseY=mouse.y;

    // Subtract out the position of the map image in the maplayer
    // This gives us position of the click relative to the map image (pixcels)
    mouseX -= divs.theMap.windowOffsetLeft();
    mouseY -= divs.theMap.windowOffsetTop();
    // Subtract out the position of the map div relative to the browser window
    // This gives us the position relative to the map div
    if        (ns4) { // Netscape 4
    } else if (ie4) { // Explorer 4
    } else if (ie5) { // W3C - Explorer 5+
    } else if (ns6) { // W3C - Netscape 6+
        mouseX -= divs.maplayer.windowOffsetLeft();
        mouseY -= divs.maplayer.windowOffsetTop();
    }


    // Also calculate the position of the click in metres east and north
    mapX = pixelX * mouseX + eLeft;
    mapY = pixelY * (iHeight-mouseY) + eBottom;
    
//    document.outputF.X.value = mapX;
//    document.outputF.Y.value = mapY;
//    document.outputF.pixX.value = mouseX;
//    document.outputF.pixY.value = mouseY;
}


////////////////////////////////////////////////////////////////////////////////////
// Called when user clicks down on mouse
///////////////////////////////////////////////////////////////////////////////////
function mapMouseDown (e) {

  // Dont allow user to use tools if
  // the mouse in in a "popup" div
  if(!divPopup){

      // Work out where the use has clicked in pixcels and metres
      getImageXY(e)

      // Make sure we are over the map
      if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {

        switch(toolMode) {
          case 1:
            zoomIn(mapX,mapY);
            break
          case 2:
            zoomOut(mapX, mapY);
            break
          case 3:
            startZoomInBox(e);
            break

          case 4:
            startPan(e);
            break

          default:
        break
        }
      }
      // Forward events on
      else if (!document.all)
        routeEvent(e);
  }
  return (!zooming && !panning);
}

////////////////////////////////////////////////////////////////////////
// Called when user lets the map button up
////////////////////////////////////////////////////////////////////////
function mapMouseUp(e) {

  // If we are showing a "popup" div then ignore this event
  if (divPopup)
    return true;

  // If we are dragging a zoom in box the zoom in
  if ((toolMode == 3) && (zooming)) {
    stopZoomInBox(e);
  }

  // If we are dragging the map then get the new  map
  if ((toolMode == 4) && (panning)) {
    stopPan(e);
  }

  // next line needed for Mac
  return (!zooming && !panning);
}

//////////////////////////////////////////////////////////////////////////////
// Called when the user hovers over the image map corresponding to a "popup" div
//////////////////////////////////////////////////////////////////////////////
function imagemapMouseOver()
{
    // Ignore if we are dragging a zoom box or draging the map
    if(panning || zooming) {
        return;
    }
    // If we are showing an old "popup" then hide it
    if (divPopup!=null  && divPopup.isVisible())
    {
      divPopup.hide();
    }

    // The id of the popup is passed into this function
    divPopupId= arguments[0];

    // get a handle on the popup div
    divPopup = eval('divs.'+popuptextdiv+divPopupId);

    // The popup div might not exist if there are too many
    // If it does not exist the display the default popup
    if(!divPopup)
    {
      divPopup=divs.mapDefaultText;

    } else {
//            +" divs.maplayer.windowOffsetLeft()="+divs.maplayer.windowOffsetLeft()
//            +" divs.mapDisplay.windowOffsetLeft()="+divs.mapDisplay.windowOffsetLeft()
//            +" divs.theMap.windowOffsetLeft()="+divs.theMap.windowOffsetLeft()
//            +" hspc="+hspc);
    }

    // Calculate where the divs should be relative to top left corner of browser
    var divX = divs.theMap.windowOffsetLeft() + popuptextx[divPopupId];
    var divY = divs.theMap.windowOffsetTop() + popuptexty[divPopupId];
    if        (ns4) { // Netscape 4
    } else if (ie4) { // Explorer 4
    } else if (ie5) { // W3C - Explorer 5+
    } else if (ns6) { // W3C - Netscape 6+
        divX += divs.maplayer.windowOffsetLeft();
        divY += divs.maplayer.windowOffsetTop()
    }

    // If we are on the right side of the map popup the div towards the left
    if (popuptextx[divPopupId] > (iWidth/2))
    {
        divX -= divPopup.getWidth();

        // Ensure that the popup is above the mouse position to allow hyperlinks
        // embedded in the popup to work
        divX -= divPopupDelta;
    } else {
    // otherwise let it flow to the left
        divX += divPopupDelta;
    }
    // If we are on the bottom half of the map, popup the div highe up
    if (popuptexty[divPopupId]> (iHeight/2))
    {
        divY -= divPopup.getHeight();

        // Popup over mouse position (again)
        divY -= +divPopupDelta;
    } else {
    // Otherwise let the div flow down
        divY += divPopupDelta;
    }
    // Display the popup div
    divPopup.moveTo(divX, divY);
    divPopup.setZIndex(1);
    divPopup.show();

    // Move the border for the div to correct place
    divs.mapTextNorth.moveTo(divX-1, divY-1);
    divs.mapTextSouth.moveTo(divX-1, divY-1);
    divs.mapTextEast.moveTo(divX-1, divY-1);
    divs.mapTextWest.moveTo(divX-1, divY-1);

    // Clip border to fit popup div
    divs.mapTextNorth.setClip(0, divPopup.getWidth()+2, 1, 0);
    divs.mapTextSouth.setClip(divPopup.getHeight()+1, divPopup.getWidth()+2, divPopup.getHeight()+2, 0);
    divs.mapTextEast.setClip(0, divPopup.getWidth()+2, divPopup.getHeight()+2, divPopup.getWidth()+1);
    divs.mapTextWest.setClip(0, 1, divPopup.getHeight()+2, 0);

    // Show borders
    divs.mapTextNorth.setZIndex(1);
    divs.mapTextSouth.setZIndex(1);
    divs.mapTextEast.setZIndex(1);
    divs.mapTextWest.setZIndex(1);

    divs.mapTextNorth.show();
    divs.mapTextSouth.show();
    divs.mapTextEast.show();
    divs.mapTextWest.show();
}

////////////////////////////////////////////////////////////////////////////////
// Called when user moves mouse
////////////////////////////////////////////////////////////////////////////////
function mapMouseMove(e) {

  // window.status="";

  // Get the position odf the mouse in pixcels and in metres
  getImageXY(e);

  // change mouse cursor when drag or drag zoom
  if ((mouseX>=0) && (mouseX<iWidth) && (mouseY>=0) && (mouseY<iHeight)) {
                switch(toolMode) {
                  case 1:
                        //document.body.style.cursor = "default";
                break
                  case 2:
                        //document.body.style.cursor = "default";
                break
                  case 3:
                        document.body.style.cursor = "crosshair";
                break

                  case 4:
                        document.body.style.cursor = "move";
                break

                  default:

                break
                }
          }
          else{
                document.body.style.cursor = "default";
      }


  // If we have "popedup" a div the check to see
  // if we have moved off it and if so hide it
  if(divPopup){

    var minX = popuptextx[divPopupId];
    var maxX = popuptextx[divPopupId];
    var minY = popuptexty[divPopupId];
    var maxY = popuptexty[divPopupId];

    // Work out where we positioned the popup
    if (popuptextx[divPopupId] > (iWidth/2)) {
      minX -= divPopup.getWidth();
      minX -= divPopupDelta;
      maxX -= divPopupDelta;
    }
    else {
      maxX += divPopup.getWidth();
      maxX += divPopupDelta;
      minX += divPopupDelta;
    }

    if (popuptexty[divPopupId] > (iHeight/2)) {
      minY -= divPopup.getHeight();
      minY -= divPopupDelta;
      maxY -= divPopupDelta;
    }
    else {
      maxY += divPopup.getHeight();
      maxY += divPopupDelta;
      minY += divPopupDelta;
    }


    // Hide the popup div if we have slipped off
    if ( (mouseX<maxX) && (mouseX>minX) && (mouseY<maxY) && (mouseY>minY)) {
    } else {
      divs.mapTextNorth.hide();
      divs.mapTextSouth.hide();
      divs.mapTextEast.hide();
      divs.mapTextWest.hide();

      divPopup.hide();
      divPopup=null;
      divPopupId=-1;
    }
  }

  // If we have moved of the map then simulate a mouse up event
  if ((mouseX>iWidth) || (mouseY>iHeight) || (mouseX<=0) ||(mouseY<=0)) {
    mapMouseUp(e);
  } else {

    if (zooming) {
      // Update corner of zoom box
      x2=mouseX;
      y2=mouseY;
      moveZoomBox();

    } else if (panning) {
      // Update map drag position
      x2=mouseX;
      y2=mouseY;
      moveMap();
    }

    var mouseString = "";
    if (zooming) mouseString += "ZoomBox: [" + x1 + "," + y1 + " x " + x2 + "," + y2 + "]    ";
    mouseString += "Coords: " + mouseX + " , " + mouseY +"  "+parseInt(mapY)+"N "+parseInt(mapX)+"E";
    // 12/02/04 removed due to legal reasons
    //window.status = mouseString;
  }
  return (!zooming && !panning);
}



/////////////////////////////////////////////////////////////////////
// Move the zoom in box
// (x1, y1) Initial corner of zoom box
// (x2, y2) Dynamic cornr of zoom box
/////////////////////////////////////////////////////////////////////
function moveZoomBox() {
  var tempX=x1;
  var tempY=y1;

  if (x1>x2) {
    zright=x1;
    zleft=x2;
  } else {
    zleft=x1;
    zright=x2;
  }
  if (y1>y2) {
    zbottom=y1;
    ztop=y2;
  } else {
    ztop=y1;
    zbottom=y2;
  }

  if ((x1 != x2) && (y1 != y2)) {
    boxIt(zleft,ztop,zright,zbottom);
  }
  return false;
}



//////////////////////////////////////////////////////////////////////////////
// gets map form and initialises it's values -- v2
//////////////////////////////////////////////////////////////////////////////

function getAndInitialiseMapForm(){
	var mapForm=window.divs.maplayer.div.document.mapForm;
      if (formAction!="") {
       mapForm.action=formAction;
	 }

	// Speicy new image
      mapForm.minx.value        = eLeft;
      mapForm.miny.value        = eBottom;
      mapForm.maxx.value        = eRight;
      mapForm.maxy.value        = eTop;

	// Height and with currently do not change
      mapForm.height.value      = iHeight;
      mapForm.width.value       = iWidth;

	// Preseve current map tool mode
      mapForm.toolMode.value        = toolMode;

	// Ensure we havea map displayed
      mapForm.gp.value              = "map";

      mapForm.scale.value = curZoom.width;
 
	  return mapForm;
}




//////////////////////////////////////////////////////////////////////////////
// Send request for new map afterZooming --v2
//////////////////////////////////////////////////////////////////////////////
function sendMapXMLAfterZooming(x,y) {
if (loaded==true){

      var mapForm=getAndInitialiseMapForm();
   
      mapForm.X.value = x;
      mapForm.Y.value = y;
 
      mapForm.submit();
}
}


//////////////////////////////////////////////////////////////////////////////
// Send request for new map
//////////////////////////////////////////////////////////////////////////////
function sendMapXML() {
if (loaded==true){

      var mapForm=getAndInitialiseMapForm();
      if (formAction!="")
       mapForm.action=formAction;

	  mapForm.X.value = eLeft + xDistance;
      mapForm.Y.value = eBottom + yDistance;
 
      mapForm.submit();
}
}
////////////////////////////////////////////////////////////////////////////////////
// Function used in page to request a new page when not actually intreacting with map
// The specified url is used additional params are added from mapForm
// Ensures map state is preserved by examining mapForm
/////////////////////////////////////////////////////////////////////////////////////
function mappingRedirect(url)
{
  if (!url)
  {
      if (formAction!="")
        url=formAction;
      else
        url=window.location.href.replace(/\?.*/, "");
  }
  url+="?";
  var mapForm=window.divs.maplayer.div.document.mapForm;
  var elems = mapForm.elements;

  // Update on the form any additional values passed
  for (var i=1; i+1<arguments.length; i++)
  {
    var found=false;
    for (var j=0; j<elems.length; j++)
    {
      if(elems[j].name == arguments[i])
      {
        elems[j].value= escape(arguments[i+1]);
        found=true;
      }
    }
    if(found==false)
    {
      url+="&"+arguments[i] +"=" +escape(arguments[i+1]);
    }
    i++;
  }
  // Construct URL adding query params from form
  for ( i=0; i<elems.length; i++)
  {
    url+="&" + elems[i].name +"=" + escape(elems[i].value);
  }
  window.document.location.href=url;
  return false;
}
////////////////////////////////////////////////////////////////////////////////////
// Function used in page to request a new page when not actually intreacting with map
// Parameters from the specified form is usedmand supllement with params from map form
// Ensures map state is preserved by examining mapForm
/////////////////////////////////////////////////////////////////////////////////////
function mappingFormRedirect(form)
{
  var url;

  if (form)
  {
      url = formAction;
      url+="?";
      var elems =form.elements;

      // use params from supplied form
      for (var i=0; i<elems.length; i++)
      {
        if (elems[i].type!='checkbox' || elems[i].checked )
          url+="&" + elems[i].name + "=" +escape(elems[i].value);
      }

      if(document.mapForm)
      {
        // Add missing elems from MapForm
        var mapForm=document.mapForm;
        var mapElems = mapForm.elements;

        // Update on the form any additional values passed
        for (var i=0; i<mapElems.length; i++)
        {
          var found=false;
          for (var j=0; j<elems.length; j++)
          {
            if(elems[j].name == mapElems[i].name)
            {
              found=true;
              break;
            }
          }
          if(found==false)
          {
            url+="&"+mapElems[i].name +"=" +escape(mapElems[i].value);
          }
        }
      }
      window.document.location.href=url;
  }
  return false;
}

function startPan(e) {

  // Make sur we are on the map
  if ((mouseX<iWidth) && (mouseY<iHeight)) {
      x1=mouseX;
      y1=mouseY;
      x2=x1+1;
      y2=y1+1;
      panning=true;

  }
  return false;
}

//////////////////////////////////////////////////////////////////////////////////
// Stop dragging the map
//////////////////////////////////////////////////////////////////////////////////
function stopPan(e) {

  var ixOffset = x2-x1;
  var iyOffset = y1-y2;
  panning=false;

  // Make sure the map has been moved at least 5 pixcels !
  if (Math.abs(ixOffset)>5  || Math.abs(iyOffset)>5) {

      var theY  = iHeight - ztop;
      var xOffset   = pixelX * ixOffset;
      var yOffset   = pixelY * iyOffset;

      eTop      = eTop      - yOffset;
      eRight    = eRight    - xOffset;
      eLeft     = eLeft     - xOffset;
      eBottom   = eBottom   - yOffset;
      divs.theMap.hide();

      sendMapXML();

  } else{
    // Move the map back!
//    divs.theMap.moveTo(hspc,vspc);
	findInitalOffset();
  }
  return true;
}
function moveMap() {
  var xMove = x2-x1;
  var yMove = y2-y1;
  var cLeft = -xMove;
  var cTop  = -yMove;
  var cRight = iWidth;    // - xMove;
  var cBottom = iHeight;  // - yMove;

  if (xMove>0) {
    cLeft = 0;
    cRight = iWidth - xMove;
  }
  if (yMove>0) {
    cTop = 0;
    cBottom = iHeight - yMove;
  }

  // Move the map and make sure it is clipped
 //   divs.theMap.setClip(cTop,cRight,cBottom, cLeft);
 // divs.theMap.moveTo(xMove+hspc,yMove+vspc);
      
      
      
    setTop("map1", yMove+vspc+offsetY);
    setLeft("map1",xMove+hspc+offsetX); 
    setTop("map2", yMove+vspc+offsetY);
    setLeft("map2", xMove+hspc+iWidth+offsetX);
    setTop("map3", yMove+vspc+iHeight+offsetY);
    setLeft("map3", xMove+hspc+offsetX);
    setTop("map4", yMove+vspc+iHeight+offsetY);
    setLeft("map4", xMove+hspc+iWidth+offsetX);
	
//	divs.map1.moveTo(xMove+hspc+offsetX,yMove+vspc+offsetY);
//	divs.map2.moveTo(xMove+hspc+iWidth+offsetX,yMove+vspc+offsetY);
//	divs.map3.moveTo(xMove+hspc+offsetX,yMove+vspc+iHeight+offsetY);
//	divs.map4.moveTo(xMove+hspc+iWidth+offsetX,yMove+vspc+iHeight+offsetY);	
}

/////////////////////////////////////////////////////////////////////
// Move the zoom in box
// (x1, y1) Initial corner of zoom box
// (x2, y2) Dynamic cornr of zoom box
/////////////////////////////////////////////////////////////////////
function moveZoomBox() {
  var tempX=x1;
  var tempY=y1;

  if (x1>x2) {
    zright=x1;
    zleft=x2;
  } else {
    zleft=x1;
    zright=x2;
  }
  if (y1>y2) {
    zbottom=y1;
    ztop=y2;
  } else {
    ztop=y1;
    zbottom=y2;
  }

  if ((x1 != x2) && (y1 != y2)) {
    boxIt(zleft,ztop,zright,zbottom);
  }
  return false;
}
function stopZoomInBox() {

    zooming=false;

    // Hide zoom in box
    divs.zoomBoxTop.hide();
    divs.zoomBoxLeft.hide();
    divs.zoomBoxRight.hide();
    divs.zoomBoxBottom.hide();

    // Make sure we have draged a box at least 5 pixcels in size!
    if (Math.abs(zright-zleft)>5  && Math.abs(zbottom-ztop)>5)
    {
        var theY    = iHeight - ztop;

        eTop    = pixelY * theY   + eBottom;
        eRight  = pixelX * zright + eLeft;
        eLeft   = pixelX * zleft  + eLeft;

        theY    = iHeight - zbottom;
        eBottom = pixelY * theY + eBottom;

        zoomToLevel(
            getZoomLevelForWidth(eRight-eLeft),
            (eLeft + eRight)/2,
            (eTop  + eBottom)/2);
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////
// Start to drag zoom in box
////////////////////////////////////////////////////////////////////////////////
function startZoomInBox() {

  // Make sure we are on the map
  if ((mouseX<iWidth) && (mouseY<iHeight)) {
      x1=mouseX;
      y1=mouseY
      x2=x1+1;
      y2=y1+1;
      zleft=x1;
      ztop=y1;
      zbottom=y1;
      zright=x1

      // Show the zoom box
      zooming=true;
      boxIt(x1,y1,x2,y2);
  }
  return false;
}

function boxIt(theLeft,theTop,theRight,theBottom) {
  divs.zoomBoxTop.setClip(theTop,theRight,theTop+zoomBoxSize, theLeft);
  divs.zoomBoxLeft.setClip(theTop,theLeft+zoomBoxSize,theBottom, theLeft);
  divs.zoomBoxRight.setClip(theTop,theRight,theBottom, theRight-zoomBoxSize);
  divs.zoomBoxBottom.setClip(theBottom-zoomBoxSize,theRight,theBottom, theLeft);

  divs.zoomBoxTop.show();
  divs.zoomBoxLeft.show();
  divs.zoomBoxRight.show();
  divs.zoomBoxBottom.show();
}
