//DIDB40087 added the distance and measurement tools.
function Map(cover, divId, ctxPath, layers) {
	this.cover=cover;
	this.ctxPath=ctxPath;
	this.layers=layers;
	this.offsetBottom=0;
	this.offsetRight=0;
	this.coverLatLon=null;

	this.zoomBox = 1;
    this.pan = 2;
    this.select = 3;
    this.rangeSelect = 4;
    this.regionSelect = 5;
    this.mapPosition = 6;

    //DIDB33771 add buffer select
    this.bufferSelect = 10;

	//DIDB40087 added the distance and measurement tools.    
	this.measurementTransientLayer = null;
    this.distanceMeasurement= 7;
    this.areaMeasurement = 8;

    //DIDB40644 added the redline tool
    this.redTransientLayer = null;
    this.redline = 9;
	this.curRedlineTool = 6;  //6:select, 0:point, 1:line, 3:polygon, 2: text 

	this.prevMapTool=this.zoomBox;
	this.previousSelection= "";

	//DIDB42282 added the targets layer
	this.targetsTransientLayer = null;

    //DIDB41749 Added target replay variables
	this.targetsReplay = false;
	this.replayPaused = false;
	this.targetsReplayTime = null;
	this.targetsReplayEnd = null;
	this.targetsReplaySpeed = 1;
	this.refreshSpeed = null;
    this.prevReplayTime = null;

    this.refreshingTargetsImage = false;

	//DIDB41758 Added target options
	this.rateOfTurn = false;
    this.speed = false;
    this.labels = false;
    this.targetTrack = false;
    this.type = "count";
	this.lengthOfTrack = 25;

	this.divContainer=document.getElementById(divId);
	this.divId = divId;
	//DIDB40853 Status bar supports geo and ground units.
	this.srsType = null;
	this.groundUnitsDesired = null; 
	document.onmousedown = this.mousedown.bindAsEventListener(this);
	document.onmousemove = this.mousemove.bindAsEventListener(this);
	document.onmouseup = this.mouseup.bindAsEventListener(this);		

	var tempMapImg=document.createElement('img');
	tempMapImg.setAttribute('id','mapImg');
	tempMapImg.setAttribute('name','mapImg');
	tempMapImg.setAttribute('hspace','0');
	tempMapImg.setAttribute('vspace','0');
	tempMapImg.setAttribute('galleryimg','false');

	this.divContainer.innerHTML='';
	this.mapImg = this.divContainer.appendChild(tempMapImg);
	this.mapImg.onload = this.onload.bindAsEventListener(this);
	this.mapImg.onerror = this.onerror.bindAsEventListener(this);                  
	this.mapImg.onmousedown = function() {return false;}
	this.mapImg.onmousemove = function() {return false;}
	this.mapImg.onmouseup = function() {return false;}

	//DIDB40644 clicking on redline icons flag
	this.clickingOnRedlineIcon = false;

	//DISB40644 if display the redline layer
	this.displayRedline = true;

	this.setMapTool(this.zoomBox);
	this.selectionLayer='';

    //DIDB41740 Added variable to determine if replay is being initialized
    this.initializingReplay = false;

	//DIDB42282 added the target layer refresh interval
	targetLayerRefreshInterval=null;
}

Map.prototype.cover=null;

function Cover(minx,miny,maxx,maxy,srs) {
	this.minx = minx;
	this.miny = miny;
	this.maxx = maxx;
	this.maxy = maxy;
	this.srs = srs;
}

//DIDB40087 added this method.
//This method create a transient layer object    
function TransientLayer(name, displayPriority) {
	this.name = name;
	this.displayPriority = displayPriority;
	this.image = null;
}

//DIDB42282 added this method.
//This method sets the targets layer object
function map_setTargetsLayer(tlayer) {
	targetsTransientLayer = tlayer;
	targetsTransientLayer.image.style.width=this.getWidth() + "px";		
	targetsTransientLayer.image.style.height=this.getHeight() + "px";
	targetsTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";	
}  

//DIDB40087 added this method.
//This method set the measurement layer object
function map_setMeasurementLayer(mlayer) {
	measurementTransientLayer = mlayer;
}    

//DIDB40087 added this method.
//This method adds a transient layer to the map   
function map_addTransientLayer(tl) {
	tl.image=document.createElement('img');
	tl.image.setAttribute('id','tl_' + tl.name);
	tl.image.setAttribute('name','tl_' + tl.name);
	tl.image.setAttribute('hspace','0');
	tl.image.setAttribute('vspace','0');
	tl.image.setAttribute('galleryimg','false');

	tl.image = this.divContainer.appendChild(tl.image);
	tl.image.onload = function(){this.style.display='';}
//	tl.image.onerror = this.onerror.bindAsEventListener(this);                  
	tl.image.onmousedown = function() {return false;}
	tl.image.onmousemove = function() {return false;}
	tl.image.onmouseup = function() {return false;}  
	
	tl.image.style.position='absolute';
	tl.image.style.top=this.getTop() + 'px';
	tl.image.style.left=this.getLeft() + 'px';
	tl.image.style.zIndex=tl.displayPriority;	
}

//DIDB40087 added this method.
//This method sends the inputted point to the server to draw the new measurement image 
//and then replace the measurement transient layer image with it.    
function map_measure(xCord,yCord) {
	if(measurementTransientLayer == null) {
		return;
	}
	var measurementTool='';
	if (this.mapTool == this.distanceMeasurement) {
		measurementTool='distance'; 
	} else if (this.mapTool == this.areaMeasurement) {
		measurementTool='area';
	}
	var u = this.ctxPath + '/measure.image?measurementTool=' + measurementTool +'&mupx=' + xCord + '&mupy=' + yCord;
	if(document.all) {		
		measurementTransientLayer.image.style.width=this.getWidth() + "px";
		measurementTransientLayer.image.style.height=this.getHeight() + "px";						
		measurementTransientLayer.image.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + u + "', sizingMethod='scale')";
		measurementTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
	} else {
		measurementTransientLayer.image.src = u;
	}	

}


//DIDB41758 Add this method.
/**
 * Function set the target options.
 */
function map_setTargetOptions(rateOfTurn, speed, labels, targetTrack, type, lengthOfTrack) {
   
    this.rateOfTurn = rateOfTurn;
    this.speed = speed;
    this.labels = labels;
    this.targetTrack = targetTrack;
    this.type=type;
    this.lengthOfTrack=lengthOfTrack;
    this.refreshTargetsLayerImage(false);
    
}



//DIDB41749 Added map_startTargetsReplay, map_togglePauseTargetsReplay and
//map_stopTargetsReplay methods.
//DIDB45750 Modified to clear the current refresh interval and pass true to the
//call to refreshTargetsLayerImage so it resets it with the update interval
//for the current replay speed.
/**
 * Function to start a replay with the given start and end times (in
 * milliseconds) and a given speed to use for the replay speed multiplier.
 */
function map_startTargetsReplay(start, end, speed) {
    clearTimeout(targetLayerRefreshInterval);

    this.targetsReplayTime = start;
    this.targetsReplayEnd = end;
    this.targetsReplaySpeed = speed;
    this.targetsReplay = true;

    if(speed == 1) {
        this.refreshSpeed = targetsTransientLayer.refreshInterval;
    } else if(speed == 50) {
        this.refreshSpeed = 8000;
    } else if(speed == 100) {
        this.refreshSpeed = 5000;
    } else {
        this.refreshSpeed = 10000;
    }

    this.prevReplayTime = (new Date()).getTime();
    this.refreshTargetsLayerImage(true);
}

/**
 * Function to pause/unpause a targets replay.
 */
function map_togglePauseTargetsReplay() {
    if(this.replayPaused) {
        this.prevReplayTime = (new Date()).getTime();
        this.replayPaused = false;
    } else {
        this.replayPaused = true;
    }

    this.refreshTargetsLayerImage(false);
}

/**
 * Function to stop a targets replay.
 */
function map_stopTargetsReplay() {
    this.targetsReplay = false;
    this.replayPaused = false;

    if(document.all) {
        targetsTransientLayer.image.style.filter='';
    } else {
        targetsTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
    }

    this.refreshTargetsLayerImage(false);
}

//DIDB42282 added this method
//DIDB41749 Modified the call to get the targets image for a given time to allow
//for starting/stopping/pausing a replay.  Added check to see if a replay is
//being initialized (skip the draw if it is).
//DIDB41758 Pass the target options
//This method get the targets layer image from the server and refresh the client
//side image.
//DIDB45964 Added 'refreshingTargetsImage' variable and code that uses it to
//check if the targets image is already being refreshed, if so it skips this
//draw request.
function map_refreshTargetsLayerImage(resetTimer) {

    if(this.refreshingTargetsImage) {
        if(resetTimer) {
            clearTimeout(targetLayerRefreshInterval);

            targetLayerRefreshInterval = setTimeout(
            		'm.refreshTargetsLayerImage(true)', this.refreshSpeed);
        }

        return;
    }

    this.refreshingTargetsImage = true;

    if(targetsTransientLayer == null || this.initializingReplay) {
        if(document.all) {
            targetsTransientLayer.image.style.filter = '';
        } else {
            targetsTransientLayer.image.src = this.ctxPath + "/images/pixel.gif";
        }

        if(resetTimer) {
            clearTimeout(targetLayerRefreshInterval);

            targetLayerRefreshInterval = setTimeout(
                    'm.refreshTargetsLayerImage(true)', this.refreshSpeed);
        }

        this.refreshingTargetsImage = false;

        return;
    }

    var u = this.ctxPath + '/drawTargets.image' + '?force=';
    if(this.targetsReplay) {
        if(this.replayPaused) {
            u += this.targetsReplayTime;
        } else {
            var displayTimeDate = new Date();
            var timeDiff = displayTimeDate.getTime() - this.prevReplayTime;

            this.targetsReplayTime += timeDiff * this.targetsReplaySpeed;
            this.prevReplayTime = displayTimeDate.getTime();

            if(this.targetsReplayTime > this.targetsReplayEnd) {
                this.targetsReplayTime = this.targetsReplayEnd;
            }

            u += this.targetsReplayTime;
        }
    } else {
        u += (new Date()).getTime();
    }

    u +='&rateOfTurn='+this.rateOfTurn;
    u +='&speed='+this.speed;
    u +='&labels='+this.labels;
    u +='&targetTrack='+this.targetTrack;
    u +='&type='+this.type;
    u +='&lengthOfTrack='+this.lengthOfTrack;

    if(document.all) {
        targetsTransientLayer.image.style.filter =
            "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + u +
            "', sizingMethod='scale')";
    } else {
        targetsTransientLayer.image.src = u;
    }

    if(!resetTimer) {
        this.refreshingTargetsImage = false;
        return;
    }

    clearTimeout(targetLayerRefreshInterval);

    if(this.targetsReplay && !this.replayPaused) {
        targetLayerRefreshInterval = setTimeout(
            'm.refreshTargetsLayerImage(true)', this.refreshSpeed);
    } else {
        targetLayerRefreshInterval = setTimeout('m.refreshTargetsLayerImage(true)',
                targetsTransientLayer.refreshInterval);
    }

    this.refreshingTargetsImage = false;
}

//DIDB42282 added this method
//DIDB43676 fixed the panning problem 
//This method clears the targets layer
function map_clearTargetsLayer() {
	if (typeof(targetsTransientLayer) != "undefined") {
		if(document.all) {
			targetsTransientLayer.image.style.filter='';
		}
		targetsTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
	}
}

//DIDB40087 added this method.
//This method gets the measurement image from the server and 
//replace the measurement transient layer image with it.    
function map_refreshMeasurement() {
	if(measurementTransientLayer == null) {
		return;
	}
	var u = this.ctxPath + '/drawMeasurement.image' + '?force=' + (new Date()).getTime();
	if(document.all) {		
		measurementTransientLayer.image.style.width=this.getWidth() + "px";
		measurementTransientLayer.image.style.height=this.getHeight() + "px";						
		measurementTransientLayer.image.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + u + "', sizingMethod='scale')";
		measurementTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
	} else {
		measurementTransientLayer.image.src = u;
	}	

}

//DIDB40144 added this method
//This method clear the measurement image
//DIDB41077 fixed the IE issue
function map_clearMeasurement() {
	if(document.all) {
		measurementTransientLayer.image.style.filter='';
	}
	measurementTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
}

//DIDB40644 added this method
function map_replaceRedlineLayerImage(url) {
	if(redlineTransientLayer == null || this.displayRedline == false) {
		return;
	}
	if(document.all) {		
		redlineTransientLayer.image.style.width=this.getWidth() + "px";
		redlineTransientLayer.image.style.height=this.getHeight() + "px";								
		redlineTransientLayer.image.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale')";
		redlineTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
	} else {
		redlineTransientLayer.image.src = url;
	}
}


//DIDB40644 added this method
//This method sends the inputted point to the server to draw the new redline image 
//and then replace the redline transient layer image with it.    
function map_redlining(xCord,yCord, text) {
	if(redlineTransientLayer == null) {
		return;
	}	
	var u = this.ctxPath + '/redline.image?' +'&mupx=' + xCord + '&mupy=' + yCord 
				+ '&text=' + text + '&tool=' + this.curRedlineTool;
	this.replaceRedlineLayerImage(u);
}

//DIDB40644 added this method.
//This method gets the redline image from the server and 
//replace the redline transient layer image with it.    
function map_refreshRedline() {
	//alert(redlineTransientLayer.image.style.display);
	if(redlineTransientLayer == null || this.displayRedline == false) {
		return;
	}
	
	var u = this.ctxPath + '/drawRedline.image' + '?force=' + (new Date()).getTime();
	this.replaceRedlineLayerImage(u);

}

//DIDB40644 added this method
//This method finish the current editting redline feature and refresh the redline image
function map_finishRedline() {
    	var u = this.ctxPath +  "/finishRedline.html"; 
    	this.replaceRedlineLayerImage(u);
}

//DIDB40644 added this method
//This method deletes the selected redline feature from the map
function map_deleteSelectedRedline() {
	if(redlineTransientLayer == null) {
		return;
	}
	var u = this.ctxPath + '/deleteSelectedRedline.image' + '?force=' + (new Date()).getTime();
	this.replaceRedlineLayerImage(u);
}

//DIDB40644 added this method
//This method hides the redline layer
function map_hideRedline() {
	if (redlineTransientLayer != null) {
		redlineTransientLayer.image.style.display='none';
		this.displayRedline = false;
	}
}

//DIDB40644 added this method
//This method shows the redline layer
function map_showRedline() {
	if (redlineTransientLayer != null) {
		redlineTransientLayer.image.style.display='';
		this.displayRedline = true;
	}
}

//DIDB40644 added this method.
//This method set the redline layer object
function map_setRedlineLayer(mlayer) {
	redlineTransientLayer = mlayer;
}    

//DIDB40644 added this method
//This method clear the redline image
function map_clearRedline() {
	if(document.all) {
		redlineTransientLayer.image.style.filter='';
	}
	redlineTransientLayer.image.src=this.ctxPath + "/images/pixel.gif";
}

//DIDB40644 added this method
//This method sets current redline tool
function map_setCurRedlineTool(tool) {	
	//var u = this.ctxPath +  "/setRedLiningTool.image?tool=" + tool; 
    //this.replaceRedlineLayerImage(u);
    this.curRedlineTool = tool;
    
	var activeRedlineIcons = document.getElementsByClassName('redlineIconOn');
	if (activeRedlineIcons!=null) {
		for (var i=0; i<activeRedlineIcons.length; i++) {
			activeRedlineIcons[i].className = 'redlineIconOff';
		}
	}
			
	if (tool == 6)
		document.getElementById('redlineSelectIcon').className='redlineIconOn';		
	else if (tool == 0)
		document.getElementById('redlinePointIcon').className='redlineIconOn';		
	else if (tool == 1)
		parent.document.getElementById('redlineLineIcon').className='redlineIconOn';		
	else if (tool == 2)
		parent.document.getElementById('redlineTextIcon').className='redlineIconOn';		
	else if (tool == 3)
		parent.document.getElementById('redlinePolygonIcon').className='redlineIconOn';		
    
}


function map_getLeft() {
	return getAbsoluteLeft(this.divId);
}

function map_getTop() {
	return getAbsoluteTop(this.divId);
}

function map_getWidth() {
	return this.divContainer.offsetWidth;
}

function map_getHeight() {
	return this.divContainer.offsetHeight;		
}

function map_getRight() {
	return this.getLeft() + this.getWidth();
}

function map_getBottom() {
	return this.getTop() + this.getHeight();		
}

function map_cursorOnMap(e){ 
  //this.updateMouseCoords(e); //comment out to fix the popup window problem in Firefox
  if(!onMenu && this.mx > this.getLeft() && this.my > this.getTop() && this.mx < this.getRight() && this.my < this.getBottom())  
    return true;
  else 
    return false;
}

function map_redraw() {
	callToServer(this.ctxPath + "/redraw.html", "mapIFrame");
}
          
var downloadingMessagePopupWin = null;
function map_startLoadingMessage() {

   downloadingMessagePopupWin = new PopupWindow("downloadingMessage");
   var offsetX=this.mapImg.width/2-85;
   var offsetY=this.mapImg.height/2-20;	
   //alert(offsetX);alert(offsetY);
   
   //a temporary fix for Firefox where the initial width and height of the map are 0.
   if (offsetX<0)
   		offsetX=600/2-100;
   if (offsetY<0)
   		offsetY=400/2-20;   
   //alert(offsetX);alert(offsetY);				
   
   downloadingMessagePopupWin.offsetY = offsetY;
   downloadingMessagePopupWin.offsetX = offsetX;
   var imgURL = this.ctxPath+'/images/progressBar.gif';
   //alert(imgURL);
   var message = '<img src="'+imgURL+'"/>';
   downloadingMessagePopupWin.populate(message);   
   
   downloadingMessagePopupWin.showPopup('downloadingMessageAnchor');
         	
   if(this.mapImg) {
   	this.mapImg.className='transparent';
   }          

}

/*
Deprecated: using the dynamic progress bar image instead
This method uses intervals to display the downloading message dynamicly
*/
var lmCounter = -1;
function mapLoadingMessageUpdate() {

	var message = '<h1 style="font-weight:bold;">Receiving Map Image';
	lmCounter++;
	switch (lmCounter) {
	case 0:
		downloadingMessagePopupWin.populate(message+ " &nbsp;&nbsp;&nbsp;</h1>");
		break;
	case 1:
		downloadingMessagePopupWin.populate(message + " .&nbsp;&nbsp;</h1>");
		break;
	case 2:
		downloadingMessagePopupWin.populate(message + " ..&nbsp;</h1>");
		break;
	case 3:
		downloadingMessagePopupWin.populate(message + " ...</h1>");
		break;
	}
	
	downloadingMessagePopupWin.refresh();
	if (lmCounter >= 3) lmCounter = -1;
}

function map_stopLoadingMessage() {

	if(this.mapImg) {
		this.mapImg.style.position='relative';
		this.mapImg.style.clip='rect(' + this.getTop() + 'px ' +  this.getRight() + 'px ' + this.getBottom() + 'px ' + this.getLeft() +'px)';
		this.mapImg.style.left = "0px";
  	    this.mapImg.style.top = "0px";
  	    
	}

  if (downloadingMessagePopupWin!=null)
  	downloadingMessagePopupWin.hidePopup();

  if(this.mapImg) {
	this.mapImg.className='';
  }  
  this.mapSubmitted=false;
}

function map_zoomIn() {
	callToServer(this.ctxPath + "/zoomIn.html", "mapIFrame");
}

function map_changeScale(scaleValue) {
	callToServer(this.ctxPath + "/setScale.html?scaleValue=" + scaleValue, "mapIFrame");
}

function map_zoomOut() {
	callToServer(this.ctxPath + "/zoomOut.html", "mapIFrame");
}

function map_overview() {
	callToServer(this.ctxPath + "/overview.html", "mapIFrame");
}

function map_clearSelection() {
    gridOpen = true;
	callToServer(this.ctxPath + "/clearSelection.html", "mapIFrame");
}

function map_centerOnSelection() {
	callToServer(this.ctxPath + "/centerOnSelection.html", "mapIFrame");
}

function map_setMapTool(mt) {
    this.mapTool=mt;
}

function map_resize(e) {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement &&
	      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  this.setSize(myWidth - this.getLeft() - this.offsetRight - 30, myHeight - this.getTop() - this.offsetBottom - 30);
	  this.refreshImage();
}

//DIDB40644 set the clickingOnRedlineIcon flag
//DIDB45673 found javascript error in Report Dialog
//DIDB45925 Return true if mouse click in the report area
function map_mousedown(e) {
	this.updateMouseCoords(e);

    var grid = document.getElementById('dataGrid');
    var report = document.getElementById('reportInfo');
    var srTop;
    var srLeft;
    var srBottom;
    var srRight;
    var srReportTop;
    var srReportLeft;
    var srReportBottom;
    var srReportRight;

    if(grid && gridOpen) {
        srTop = parseInt(grid.style.top.substr(0, grid.style.top.length - 2));
        srLeft = parseInt(grid.style.left.substr(0, grid.style.left.length - 2));
        srBottom = srTop + parseInt(grid.contentarea.style.height.substr(0, grid.contentarea.style.height.length - 2)) + 25;
        srRight = srLeft + parseInt(grid.style.width.substr(0, grid.style.width.length - 2));
    	
    }

    if(!onMenu && this.mx > srLeft && this.my > srTop && this.mx < srRight && this.my < srBottom) {
 
        return false;
    }
	

    if(report && reportOpen) {
        srReportTop = parseInt(report.style.top.substr(0, report.style.top.length - 2));
        srReportLeft = parseInt(report.style.left.substr(0, report.style.left.length - 2));
        srReportBottom = srReportTop + parseInt(report.contentarea.style.height.substr(0, report.contentarea.style.height.length - 2)) + 25;
        srReportRight = srReportLeft + parseInt(report.style.width.substr(0, report.style.width.length - 2));
    }
    
    if(!onMenu && this.mx > srReportLeft && this.my > srReportTop && this.mx < srReportRight && this.my < srReportBottom) {
 
        return true;
    }
	
	
	if(this.cursorOnMap(e)) {
		this.mdownx=this.mx;
		this.mdowny=this.my;
		this.mupx=this.mdownx+1;
		this.mupy=this.mdowny+1;
	    if(this.mapTool==this.zoomBox || this.mapTool==this.rangeSelect) {  // Zoom or rangeSelect
	        this.startBox();
	    } else if(this.mapTool==this.pan) { // Pan
	        this.startPan();	
	    //DIDB40644 set the clickingOnRedlineIcon flag
	    } else if (this.mapTool==this.redline) {
			var targ;
			if (!e) 
				var e = window.event;
			if (e) {
				if (e.target) targ = e.target;
				else if (e.srcElement) targ = e.srcElement;
				if(targ) {
					if(targ.name == 'redlineIcons' ) {
						this.clickingOnRedlineIcon=true;
					} else {
						this.clickingOnRedlineIcon=false;    	
					}	
	    		}
	    	}
	    }
	    this.clickedOnMap=true;
	    return false;
  	}
  	return true;
}

//DIDB45673 found javascript error in report dialog
//DIDB45925 Return true if mouse click in the report area
function map_mousemove(e) {
	this.updateMouseCoords(e);

    var grid = document.getElementById('dataGrid');
    var report = document.getElementById('reportInfo');
    var srTop;
    var srLeft;
    var srBottom;
    var srRight;
	var srReportTop;
    var srReportLeft;
    var srReportBottom;
    var srReportRight;

    if(grid && gridOpen) {
        srTop = parseInt(grid.style.top.substr(0, grid.style.top.length - 2));
        srLeft = parseInt(grid.style.left.substr(0, grid.style.left.length - 2));
        srBottom = srTop + parseInt(grid.contentarea.style.height.substr(0, grid.contentarea.style.height.length - 2)) + 25;
        srRight = srLeft + parseInt(grid.style.width.substr(0, grid.style.width.length - 2));
    }

	  if(!onMenu && this.mx > srLeft && this.my > srTop && this.mx < srRight && this.my < srBottom) {

        return false;
    }
    
    if(report && reportOpen) {
        srReportTop = parseInt(report.style.top.substr(0, report.style.top.length - 2));
        srReportLeft = parseInt(report.style.left.substr(0, report.style.left.length - 2));
        srReportBottom = srReportTop + parseInt(report.contentarea.style.height.substr(0, report.contentarea.style.height.length - 2)) + 25;
        srReportRight = srReportLeft + parseInt(report.style.width.substr(0, report.style.width.length - 2));
    }

    if(!onMenu && this.mx > srReportLeft && this.my > srReportTop && this.mx < srReportRight && this.my < srReportBottom) {

        return true;
    }

	if(this.cursorOnMap(e)){
	    this.mupx=this.mx; 
	    this.mupy=this.my;
	    if(this.drawingBox) this.refreshBox();
	    if(this.drawingPan) this.refreshPan();
	    this.updateStatusBar();
	    return false;
    } else {
    	if(this.drawingBox) {
    		this.endBox();
    	} else if(this.drawingPan) {
    		this.endPan();
    		this.processMapClick();
    	}
    }
    return true;
}

//DIDB40644 don't process the point if this click point is on a redline tool icon. 
//DIDB45673 found javascript error in report dialog
//DIDB45925 Return true if mouse click in the report area
function map_mouseup(e) {
    var grid = document.getElementById('dataGrid');
    var report = document.getElementById('reportInfo');
    var srTop;
    var srLeft;
    var srBottom;
    var srRight;
	var srReportTop;
    var srReportLeft;
    var srReportBottom;
    var srReportRight;

    if(grid && gridOpen) {
        srTop = parseInt(grid.style.top.substr(0, grid.style.top.length - 2));
        srLeft = parseInt(grid.style.left.substr(0, grid.style.left.length - 2));
        srBottom = srTop + parseInt(grid.contentarea.style.height.substr(0, grid.contentarea.style.height.length - 2)) + 25;
        srRight = srLeft + parseInt(grid.style.width.substr(0, grid.style.width.length - 2));
    }
	
    if(!onMenu && this.mx > srLeft && this.my > srTop && this.mx < srRight && this.my < srBottom) {

        return false;
    }

    if(report && reportOpen) {
        srReportTop = parseInt(report.style.top.substr(0, report.style.top.length - 2));
        srReportLeft = parseInt(report.style.left.substr(0, report.style.left.length - 2));
        srReportBottom = srReportTop + parseInt(report.contentarea.style.height.substr(0, report.contentarea.style.height.length - 2)) + 25;
        srReportRight = srReportLeft + parseInt(report.style.width.substr(0, report.style.width.length - 2));

  
    }
    
    if(!onMenu && this.mx > srReportLeft && this.my > srReportTop && this.mx < srReportRight && this.my < srReportBottom) {
	
        return true;
    }
	if(this.cursorOnMap(e)){	
		
	    this.mupx=this.mx;
	    this.mupy=this.my;

	    if(this.drawingBox) {
	        this.endBox();
	    } else if(this.drawingPan) {
	    	this.endPan();
	    }

		// Code added to prevent IE from submitting the map when the drop down is clicked	
		var targ;
		if (!e) 
			var e = window.event;
		if (e) {
			if (e.target) targ = e.target;
			else if (e.srcElement) targ = e.srcElement;
			if(targ) {
				if(targ.tagName == 'SELECT' || targ.tagName == 'OPTION' ) {
					return false;
				}
			}
		}

        if(this.clickedOnMap){
        	//DIDB40644 don't process the point if this click point is on a redline tool icon.
        	if (this.mapTool!=this.redline || this.clickingOnRedlineIcon!=true) {       		
        		this.processMapClick();
            	this.clickedOnMap=false;
            }
        }
        return false;
	}
	return true;
}

//DIDB40087 refresh the measurement image when refreshing the map 
//DIDb42282 restart the targets layer refresh timer and refresh the target layer
//DIDB41749 Changed the call to setTimeout to fix an error when performing
//replays where the replay call was only performed once.
function map_load(e) {
    this.refreshMeasurement();
    this.refreshRedline();
    if (typeof(targetsTransientLayer) != "undefined") {
        clearTimeout(targetLayerRefreshInterval);
        targetLayerRefreshInterval = this.refreshTargetsLayerImage(true);
    }

    this.stopLoadingMessage(e);
    this.onrefreshed(e);
}

function map_error(e) {
	this.stopLoadingMessage(e);    
	this.onrefreshed(e);	
}

function map_updateMouseCoords(e) {

	if (!e) {		
		var e = window.event;
	}
	if (e.pageX || e.pageY)
	{
		this.mx = e.pageX;
		this.my = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		var scrOfY = 0;
		var scrOfX = 0;
	
	  if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
	    //DOM compliant
	    scrOfY = document.body.scrollTop;
	    scrOfX = document.body.scrollLeft;
	  } else if( document.documentElement &&
	      ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
	    //IE6 standards compliant mode
	    scrOfY = document.documentElement.scrollTop;
	    scrOfX = document.documentElement.scrollLeft;
	  }
	
	
		this.mx = e.clientX + scrOfX;
		this.my = e.clientY + scrOfY;
	}
	
  window.status = 'mx=' + this.mx + ' my=' + this.my + ' left=' + this.getLeft() + ' right=' + this.getRight() + ' top=' + this.getTop() + ' bottom=' + this.getBottom();
}

function map_startBox() {
  this.box = document.getElementById("box");
  if(!this.box) {
      var tempBox=document.createElement('div');
      tempBox.setAttribute('id','box');
      tempBox.style.border='1px solid red';
      tempBox.style.position='absolute';  
      this.box = document.body.appendChild(tempBox);
  }
  
  if(this.mapTool==this.zoomBox) {
  	this.box.style.border='1px solid blue';
  } else if(this.mapTool==this.pan) {
  	this.box.style.border='1px solid red';  
  }
  
  if(this.drawingBox){
    this.endBox();
  }else{
    this.drawingBox=true;
  }  
  
}

function map_refreshBox() {

 	if(this.mdownx>this.mupx){
    	bright=this.mdownx; 
    	bleft=this.mupx;
	}else{
		bright=this.mupx;
		bleft=this.mdownx; 
	}
	if(this.mdowny>this.mupy){
    	bbottom=this.mdowny; 
    	btop=this.mupy;
	}else{
		bbottom=this.mupy;
    	btop=this.mdowny; 
	}	

	this.box.style.visibility="visible";
	this.box.style.top=btop + "px";
	this.box.style.left=bleft + "px";
	this.box.style.width=bright-bleft + "px";
	this.box.style.height=bbottom-btop + "px";
}

function map_endBox() {
    this.drawingBox=false;
	this.box.style.visibility="hidden";    
    window.scrollTo(0,0);
    return true;
}

//DIDB40087 remove the measurement image when refreshing since 
//the map image returned has included it and adjust it according to the current cover already
//DIDB40144 call the clearMeasurement method when paning
//DIDB40644 remove the redline image when refreshing since 
//the map image returned has included it and adjust it according to the current cover already
//DIDB42282 clear targets when start panning
function map_startPan() {
  this.clearMeasurement();
  this.clearRedline();
  this.clearTargetsLayer();
  if(this.drawingPan){
    this.endPan();
  } else {
    this.refreshPan();
    this.drawingPan=true;
  }
  return false;    
}

function map_refreshPan() {
  var clipTop, clipRight, clipBottom, clipLeft;
  
  this.panCenterX = this.getWidth()/2-(this.mupx-this.mdownx);
  this.panCenterY = this.getHeight()/2-(this.mupy-this.mdowny);
  var currentLeft = this.getLeft()+this.mupx-this.mdownx;
  var currentTop = this.getTop()+this.mupy-this.mdowny;
  var currentRight = currentLeft+this.getWidth();
  var currentBottom = currentTop+this.getHeight();
  
  if(currentTop>this.getTop()) {
  	clipTop = 0;
  } else  {
  	clipTop = this.getTop() - currentTop;
  }
  
  if(currentRight > this.getRight()) {
  	clipRight = this.getRight() - currentLeft;
  } else {
  	clipRight = currentRight - currentLeft;
  }
  
  if(currentBottom > this.getBottom()) {
  	clipBottom = this.getBottom() - currentTop;
  } else { 
  	clipBottom = currentBottom - currentTop;
  }
  
  if(currentLeft > this.getLeft()) {
  	clipLeft=0;
  } else {
  	clipLeft = this.getLeft() - currentLeft;
  }
  
  if(this.mupx > this.getRight() || this.mupx < this.getLeft() || this.mupy > this.getBottom() || this.mupy < this.getTop()) {
    this.endPan();
  }else{
  	this.mapImg.style.position='absolute';
  	this.mapImg.style.left = currentLeft + "px";
  	this.mapImg.style.top = currentTop + "px";
  	this.mapImg.style.clip = 'rect(' + clipTop + 'px ' +  clipRight + 'px ' + clipBottom + 'px ' + clipLeft +'px)';
  } 
}

function map_endPan() {
    this.drawingPan=false;
}

//DIDB40853 Cursor coordinates in the status bar should support geographic
// or ground units and ground units should support choice of horizontal units.
function map_updateStatusBar() {
	var statusBar = document.getElementById("statusBar");
  	if(statusBar) {
  		var longValue = document.getElementById("longitudeValue");
  		var latValue = document.getElementById("latitudeValue");   
  		if(this.srsType == "LLDG") {
	  		if(longValue) {
	    		var x=convertLong((this.coverLatLon.maxx-this.coverLatLon.minx)*((this.mupx-this.getLeft())/this.getWidth())+this.coverLatLon.minx);
	  			longValue.innerHTML=x;
	  		}
	  		if(latValue) {
			    var y=convertLat((this.coverLatLon.maxy-this.coverLatLon.miny)*((this.getHeight()+this.getTop()- this.mupy)/this.getHeight())+this.coverLatLon.miny);  		  		
	  			latValue.innerHTML=y;
	  		}
  		} else {
	  		if(longValue) {
	    		var x=convertToVariousUnits((this.cover.maxx-this.cover.minx)*((this.mupx-this.getLeft())/this.getWidth())+this.cover.minx, this.groundUnitsDesired);
	  			longValue.innerHTML=x;
	  		}
	  		if(latValue) {
			    var y=convertToVariousUnits((this.cover.maxy-this.cover.miny)*((this.getHeight()+this.getTop()- this.mupy)/this.getHeight())+this.cover.miny, this.groundUnitsDesired);
	  			latValue.innerHTML=y;
	  		}  		
  		}
  	}
}

//DIDB40087 added code to process distance and area measurement.
//DIDB33771 added code to handle buffer selection 
function map_processMapClick() {
    if(this.mapTool == -1) {
        return false;
    }
 
    if(this.mapTool == this.zoomBox) {
      if((Math.abs(this.mdownx-this.mupx)<=5)||(Math.abs(this.mdowny-this.mupy)<=5)){
      	if(langId == 3){
      		alert("Advertencia: El Tama\u00F1o de la Vista es muy peque\u00F1o.");
      	}
      	else if(langId == 2){
      		alert("Attention : la zone \u00E0 agrandir est trop petite.");
      	}
      	else{//English - default
      		alert("Warning: Zoom Box is too small.");
      	}        return false;
      }
    }
        
    if(!this.mapSubmitted){
      this.mapSubmitted=true;
      if(this.mapTool == this.zoomBox) {
          callToServer(this.ctxPath + "/zoomBox.html?mdownx=" + (this.mdownx - this.getLeft()) + "&mdowny=" + (this.mdowny - this.getTop()) + "&mupx=" + (this.mupx - this.getLeft()) + "&mupy=" + (this.mupy - this.getTop()), "mapIFrame");
      } else if (this.mapTool == this.pan) { 
          callToServer(this.ctxPath + "/pan.html?mupx=" + this.panCenterX + "&mupy=" + this.panCenterY, "mapIFrame");
      } else if (this.mapTool == this.select) {
          var selection = "/select.html?&mupx=" + (this.mupx - this.getLeft()) +
              "&mupy=" + (this.mupy - this.getTop()) + "&selectionLayer=" +
              this.selectionLayer;

          gridOpen = false;
          reportOpen = false;
          callToServer(this.ctxPath + selection, "mapIFrame");
          previousSelection = selection;
      } else if (this.mapTool == this.rangeSelect) {
          var selection = "/rangeSelect.html?mdownx=" + (this.mdownx - this.getLeft()) +
              "&mdowny=" + (this.mdowny - this.getTop()) + "&mupx=" +
              (this.mupx - this.getLeft()) + "&mupy=" + (this.mupy - this.getTop()) +
              "&selectionLayer=" + this.selectionLayer;

          gridOpen = false;
          reportOpen = false;
          callToServer(this.ctxPath + selection, "mapIFrame");
          previousSelection = selection;
      } else if (this.mapTool == this.bufferSelect) {
      	  var bufSize = document.getElementById("selectionBuffer");
      	  if (bufSize != null) {
      	  	if (isPositiveNumber(bufSize.value)) {
	          var selection = "/bufferSelect.html?&mupx=" + (this.mupx - this.getLeft()) +
    	          "&mupy=" + (this.mupy - this.getTop()) + "&selectionLayer=" +
        	      this.selectionLayer + "&bufSize=" + bufSize.value;
	          gridOpen = false;
    	      callToServer(this.ctxPath + selection, "mapIFrame");
        	  previousSelection = selection;
        	} else {
        		this.mapSubmitted=false;
	  	    	if(langId == 3){
   	   				message="Buffer size must be greater than 0.";
	      	 	 }
    	  	 	 else if(langId == 2){ 
      				message="La dimension de la zone tampon doit \u00eatre plus grande que 0.";      	  	
      			 }
      	 		 else{//English and default
      				message="Buffer size must be greater than 0.";        		
    	    	}
    	    	alert(message);
          	}
          }          
      } else if (this.mapTool == this.regionSelect) {
          callToServer(this.ctxPath + "/regionSelect.html?mdownx=" + (this.mdownx - this.getLeft()) + "&mdowny=" + (this.mdowny - this.getTop()) + "&mupx=" + (this.mupx - this.getLeft()) + "&mupy=" + (this.mupy - this.getTop()), "mapIFrame");              
      } else if (this.mapTool == this.mapPosition) {
          setPoiMapPosition(this.mdownx - this.getLeft(), this.mdowny - this.getTop(), this.mupx - this.getLeft(), this.mupy - this.getTop());
      } //DIDB40087 process distance measurement.
        //DIDB40088 process area measurement. 
      	else if (this.mapTool == this.distanceMeasurement || this.mapTool == this.areaMeasurement) {
      	  this.measure(this.mupx - this.getLeft(), this.mupy - this.getTop());
      	  this.mapSubmitted=false;
      } //DIDB40644 process redline. 
      	else if (this.mapTool == this.redline) {
      	  var text = null;  
      	  if (this.curRedlineTool == 2) {//text tool  
      	  	var message = null;      	  	
	  	    if(langId == 3){
   	   			message="Input the text to be added.";
      	 	 }
      	 	 else if(langId == 2){ 
      			message="Ins\u00e9rer le texte \u00e0 \u00eatre ajouter.";      	  	}
      	 	 else{//English and default
      			message="Input the text to be added.";
      	 	 }          	   
      	 	 var x = this.mx;
      	 	 var y = this.my;
      	 	 var clickedX = this.mupx;
      	 	 var clickedY = this.mupy;
      	  	 text = promptQuestion(message);
      	  	 //recover the x and y that may be changed when clicking on the prompt window
      	  	 this.mupx = clickedX;
      	 	 this.mupy = clickedY;
      	 	 this.mx = x;
      	 	 this.my = y; 
      	 	 if (text==null || text.length==0) {
      	 	 	this.mapSubmitted=false;
      	 	 	return;
      	 	 }
      	 	 
      	  }
      	  
      	  this.redlining(this.mupx - this.getLeft(), this.mupy - this.getTop(), text);      	
      	  this.mapSubmitted=false;
      }
    }else{
    	if(langId == 3){
      		alert("Advertencia: Consulta sobre el mapa ya realizada.");
      	}
      	else if(langId == 2){
      		alert("Attention : une requ\u00EAte carte a d\u00E9j\u00E0 \u00E9t\u00E9 soumise.");
      	}
      	else{//English and default
      		alert("Warning: Map request already submitted.");
      	}    }
}

function map_setSize(w,h) {
	this.divContainer.style.width=w + 'px';
	this.divContainer.style.height=h + 'px';
	
	if(this.mapImg) {
		this.mapImg.style.width=w + 'px';
		this.mapImg.style.height=h + 'px';
	}
}

function map_setScale(s) {
	this.s = s;
	var sv = document.getElementById("scaleValue");
	//sv.innerHTML=s;
	sv.value=s;
}

function map_getScale() {
	return this.s;
}

function map_setCover(c) {
	this.cover = c;
}

function map_getCover() {
	return this.cover;
}

//DIDB40853 added map_getSRSType and map_setGroundUnitsType.
function map_setSRSType(t) {
    this.srsType = t;
}

function map_setGroundUnitsType(groundUnitType) {
    this.groundUnitsDesired = groundUnitType;
}

var firstLoad = true;
function map_refreshImage() {
	if (firstLoad == true)
	{
		firstLoad=false;
	} else 
	{
		var mapTable = document.getElementById('mapTable');
		var bgUrl=this.ctxPath+"/images/grid.gif";
		//alert(bgUrl);
		mapTable.style.background="url("+bgUrl+")";	
	}
	this.startLoadingMessage();
    this.mapImg.src=this.ctxPath + '/drawMap.image?height=' + this.getHeight() + "&width=" + this.getWidth() + "&layers=" + this.layers + "&force=" + new Date();    
    this.onrefresh();
}

function map_centerOnPoint(x,y,srs,scale) {
	callToServer(this.ctxPath + '/centerOnPoint.html?inputPointX='+x+'&inputPointY='+y+'&inputSRS='+srs+'&inputScale='+scale, "mapIFrame");	
}

function map_setLayers(layers) {
	this.layers = layers;
}

//DIDB42167 removed the code that resets transient layers  
//so that the MapAction.load() is not called when refreshing
//DIDB42282 clear target layer refresh interval when staring refresh
function map_onrefresh() {	
    clearTimeout(targetLayerRefreshInterval);
}

function map_onrefreshed() {
}

function map_setCoverLatLon(c) {
	this.coverLatLon = c;
}
function map_getCoverLatLon() {
	return this.coverLatLon;
}


Map.prototype.setCoverLatLon=map_setCoverLatLon;
Map.prototype.getCoverLatLon=map_getCoverLatLon;
Map.prototype.redraw=map_redraw;
Map.prototype.changeScale=map_changeScale;
Map.prototype.zoomIn=map_zoomIn;
Map.prototype.zoomOut=map_zoomOut;
Map.prototype.overview=map_overview;
Map.prototype.clearSelection=map_clearSelection;
Map.prototype.centerOnSelection=map_centerOnSelection;
Map.prototype.centerOnPoint=map_centerOnPoint;
Map.prototype.setMapTool=map_setMapTool;
Map.prototype.mousedown=map_mousedown;
Map.prototype.mousemove=map_mousemove;
Map.prototype.mouseup=map_mouseup;
Map.prototype.updateMouseCoords=map_updateMouseCoords;
Map.prototype.startBox=map_startBox;
Map.prototype.refreshBox=map_refreshBox;
Map.prototype.endBox=map_endBox;
Map.prototype.startPan=map_startPan;
Map.prototype.refreshPan=map_refreshPan;
Map.prototype.endPan=map_endPan;
Map.prototype.updateStatusBar=map_updateStatusBar;
Map.prototype.cursorOnMap=map_cursorOnMap;
Map.prototype.processMapClick=map_processMapClick;
Map.prototype.getLeft=map_getLeft;
Map.prototype.getTop=map_getTop;
Map.prototype.getWidth=map_getWidth;
Map.prototype.getHeight=map_getHeight;
Map.prototype.getRight=map_getRight;
Map.prototype.getBottom=map_getBottom;
Map.prototype.setSize=map_setSize;
Map.prototype.startLoadingMessage=map_startLoadingMessage;
Map.prototype.stopLoadingMessage=map_stopLoadingMessage;
Map.prototype.setScale=map_setScale;
Map.prototype.getScale=map_getScale;
Map.prototype.setCover=map_setCover;
Map.prototype.getCover=map_getCover;
//DIDB40853 Added map_setSRSType;
Map.prototype.setSRSType=map_setSRSType;
Map.prototype.setGroundUnitsType=map_setGroundUnitsType;
Map.prototype.refreshImage=map_refreshImage;
Map.prototype.setLayers=map_setLayers;
Map.prototype.resize=map_resize;
Map.prototype.onrefresh=map_onrefresh;
Map.prototype.onrefreshed=map_onrefreshed;
Map.prototype.onload=map_load;
Map.prototype.onerror=map_error;
//DIDB40087 added the methods
Map.prototype.measure=map_measure;
Map.prototype.refreshMeasurement=map_refreshMeasurement;
Map.prototype.addTransientLayer=map_addTransientLayer;
Map.prototype.setMeasurementLayer=map_setMeasurementLayer;
//DIDB40144 added the clearMeasurement method
Map.prototype.clearMeasurement=map_clearMeasurement;

//DIDB40644 added the methods
Map.prototype.redlining=map_redlining;
Map.prototype.setRedlineLayer=map_setRedlineLayer;
Map.prototype.clearRedline=map_clearRedline;
Map.prototype.refreshRedline=map_refreshRedline;
Map.prototype.finishRedline=map_finishRedline;
Map.prototype.replaceRedlineLayerImage=map_replaceRedlineLayerImage;
Map.prototype.deleteSelectedRedline=map_deleteSelectedRedline;
Map.prototype.setCurRedlineTool=map_setCurRedlineTool;
Map.prototype.hideRedline=map_hideRedline;
Map.prototype.showRedline=map_showRedline;

//DIDB42282 added the methods
Map.prototype.refreshTargetsLayerImage = map_refreshTargetsLayerImage;
Map.prototype.setTargetsLayer= map_setTargetsLayer;
Map.prototype.clearTargetsLayer=map_clearTargetsLayer;

Map.prototype.startTargetsReplay = map_startTargetsReplay;

Map.prototype.togglePauseTargetsReplay = map_togglePauseTargetsReplay;

Map.prototype.stopTargetsReplay = map_stopTargetsReplay;


//DIDB41758 Added this methods
Map.prototype.setTargetOptions = map_setTargetOptions;

Function.prototype.bind = function(object) {
	var method = this;
//	var preappliedArguments = arguments;
	return function() {
		method.apply(object, arguments);
//		method.apply(object, preappliedArguments.concat(arguments));
	};
}

Function.prototype.bindAsEventListener = function (object) {
	var method = this;
	//var preappliedArguments = arguments;
	return function(event) {
		method.call(object, event || window.event);
		//method.apply(object, [event || window.event].concat(preappliedArguments));
	};
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

function convertLong(longitude){
  if(isNaN(longitude)) {
    return;
  }
  var dir="E";
  if(longitude<0){
    dir="W";
    longitude=-1*longitude;  
  }
  var degrees=Math.floor(longitude);
  var minutes=Math.floor(((longitude-degrees)*60));
  var seconds=Math.round((((longitude-degrees)*60)-minutes)*60);
  if((minutes/10)<1) minutes="0"+minutes;
  if((seconds/10)<1) seconds="0"+seconds;
  return (degrees+"-"+minutes+"-"+seconds+dir);    
}

function convertLat(latitude){
  if(isNaN(latitude)) return;
  var dir="N";
  if(latitude<0){
    dir="S";
    latitude=-1*latitude;
  }
  var degrees=Math.floor(latitude);
  var minutes=Math.floor(((latitude-degrees)*60));
  var seconds=Math.round((((latitude-degrees)*60)-minutes)* 60);
  if((minutes/10)<1) minutes="0"+minutes;
  if((seconds/10)<1) seconds="0"+seconds;
  return (degrees+"-"+minutes+"-"+seconds+dir);    
}

//DIDB40853 Cursor coordinates in the status bar should support geographic
// or ground units, added convertToVariousUnits and roundNumber.
//DIDB45383 Accuracy for two digits to the right of the decimal
function convertToVariousUnits(groundUnits, groundUnitType) {
  if(isNaN(groundUnits)) return;
  
  if(groundUnitType == "Kilometres") {
  	  convertedgroundUnits = (groundUnits / 1000);
  	  textAbbreviatedUnits = "km";
  	  
  } else if(groundUnitType == "Nautical Miles") {
      convertedgroundUnits = (groundUnits * 0.000539956803455724);
      textAbbreviatedUnits = "nm";
      
  } else if(groundUnitType == "Int. Feet") {
      convertedgroundUnits = (groundUnits * 3.2808398950131235);
      textAbbreviatedUnits = "ft";
      
  } else if (groundUnitType == "Int. Yards") {
      convertedgroundUnits = (groundUnits * 1.0936132983377078);
      textAbbreviatedUnits = "yd";
      
  } else if (groundUnitType == "Int. Miles") {
      convertedgroundUnits = (groundUnits * 0.0006213711922373339);
      textAbbreviatedUnits = "mi";
      
  } else if (groundUnitType == "US Survey Feet") {
       convertedgroundUnits = (groundUnits * 3.2808333333333333333333333333333);
       textAbbreviatedUnits = "usft";
       
  } else if (groundUnitType == "US Survey Yards") {
       convertedgroundUnits = (groundUnits * 1.0936111100174999999999999999999);
       textAbbreviatedUnits = "usyd";
       
  } else if (groundUnitType == "US Survey Miles") {
       convertedgroundUnits = (groundUnits * 0.000621369948202499999);
       textAbbreviatedUnits = "usmi";
       
  } else if (groundUnitType == "US Chains") {
       convertedgroundUnits = (groundUnits * 0.049709695378986719696969696969697);
       textAbbreviatedUnits = "ch";
       
  } else {
  		//default is metres, so no conversion necessary.
       convertedgroundUnits = groundUnits;
       textAbbreviatedUnits = "m"
  }
   
   //round the number to 2 decimal places after the point.
   return roundNumber(convertedgroundUnits, 2) + "&nbsp;" + textAbbreviatedUnits;
}

function roundNumber(num, dec) {
	var result = num.toFixed(dec);
	return result;
}
