﻿
// Javascript file for Web Mapping Application

var reloadTimer;
var webMapAppLeftPanelWidth = 262;
var webMapAppToggleWidth = 10;
var webMapAppTopBannerHeight = 80;
var newLoad = false;
var webMapAppCloseCallback = "";
var webMapAppCopyrightCallback = "";
var webMapAppMoveFunction = null;
var webMapAppMapDisplay = null;
var webMapAppPanelDisplay = null;
var webMapAppPanelDisplayCell = null;
var webMapAppPanelDisplayTableCell = null;
var webMapAppPanelScrollDiv = null;
var webMapAppToggleDisplay = null;
var webMapAppSpacerDiv = null;
var webMapAppPanelBottomSlider = null;
var webMapAppScaleBar = null;
var webMapAppCacheZoom = null;
var webMapAppInMapNav = null;
var webMapAppCopyrightText = null;
var webMapAppWindowWidth = 500;
var webMapAppLeftOffsetX = 0;
var webMapAppRightOffsetX = 0
var webMapAppDefaultMinDockWidth = 125;
var webMapAppMinDockWidth = webMapAppDefaultMinDockWidth;
var webMapAppMapLeft = 262;
var webMapAppHasScroll = false;
var webMapAppLastHasScroll = false;
//RTD added vars
var webMapCoordUnits = "stateplane";

// function to set initial sizes of page elements
function setPageElementSizes() {
        // set body style 
        document.body.style.overflow = "hidden";
        document.body.style.height = "100%"; 
        // get necessary elements
        webMapAppMapDisplay = document.getElementById("Map_Panel");
        webMapAppPanelDisplay = document.getElementById("LeftPanelCellDiv");
        webMapAppPanelDisplayCell = document.getElementById("LeftPanelCell");
        webMapAppPanelScrollDiv = document.getElementById("LeftPanelScrollDiv");
        webMapAppToggleDisplay = document.getElementById("ToggleCell");
        webMapAppPanelSlider = document.getElementById("PanelSlider");
        webMapAppPanelDisplayTableCell = document.getElementById("LeftPanelTableCell");
        webMapAppPanelBottomSlider = document.getElementById("PanelSliderBottom");
        webMapAppScaleBar = document.getElementById("ScaleBar1");
        webMapAppInMapNav = document.getElementById("Navigation2");
        webMapAppCacheZoom = document.getElementById("ZoomControl");
        webMapAppCopyrightText = document.getElementById("CopyrightTextHolder");
        webMapAppCompassWorker = document.getElementById("BusyIndicator");
        var headerDisplay = document.getElementById("PageHeader");
        var linkDisplay = document.getElementById("LinkBar");
        var pageHeader = document.getElementById("PageHeader");
        // set scroll on Dock
        webMapAppPanelScrollDiv.style.overflowY = "auto";
        if (isIE) {
            webMapAppPanelDisplay.style.overflow = "hidden";
        } 
        // get the set widths and heights
        webMapAppLeftPanelWidth = webMapAppPanelDisplay.clientWidth;
        webMapAppToggleWidth = parseInt(webMapAppToggleDisplay.style.width);
        webMapAppTopBannerHeight = headerDisplay.clientHeight + linkDisplay.clientHeight;
        // get browser window dimensions
        var sWidth = getWinWidth();
        var sHeight = getWinHeight();
        // set map display dimensions
        var mWidth = sWidth - 20 - webMapAppLeftPanelWidth - webMapAppToggleWidth;
        var mHeight = sHeight - webMapAppTopBannerHeight -2;
        webMapAppMapLeft = webMapAppLeftPanelWidth + webMapAppToggleWidth;
        webMapAppMapDisplay.style.width =  (mWidth-0) + "px";
        linkDisplay.style.width = (sWidth-20) + "px";
        pageHeader.style.width = (sWidth-20) + "px";
        webMapAppMapDisplay.style.height = mHeight  + "px";
        if (webMapAppScaleBar!=null) {
            var sbWidth = webMapAppScaleBar.clientWidth;
            var sbHeight = webMapAppScaleBar.clientHeight;
            webMapAppScaleBar.style.left = (sbWidth + 90) + "px";
            webMapAppScaleBar.style.top = (sHeight - sbHeight - 10) + "px";
            webMapAppScaleBar.style.width = "auto";
            webMapAppScaleBar.style.height = "auto";
        } 
        if (webMapAppInMapNav!=null) {
            var sbWidth = webMapAppInMapNav.clientWidth;
            var sbHeight = webMapAppInMapNav.clientHeight;
            webMapAppInMapNav.style.left = (webMapAppMapLeft + 23) + "px";
            //webMapAppInMapNav.style.top = 70 + "px"; //(105 + 0) + "px";
            webMapAppCompassWorker.style.left = (webMapAppMapLeft + 29) + "px";
            //webMapAppCompassWorker.style.top = 52 + "px";
            webMapAppInMapNav.style.width = "auto";
            webMapAppInMapNav.style.height = "auto";
        } 
        if(webMapAppCacheZoom != null)
        {
            webMapAppCacheZoom.style.left = (webMapAppMapLeft + 37) + "px";
            //webMapAppCacheZoom.style.top = 205 + "px";
            webMapAppCacheZoom.style.width = "auto";
            webMapAppCacheZoom.style.height = "auto";
        }
//        if (webMapAppCopyrightText!=null) {
//            //webMapAppCopyrightText.onmousedown = webMapAppGetCopyrightText;
//            var crtHeight = webMapAppCopyrightText.clientHeight;
//            webMapAppCopyrightText.style.left = (webMapAppMapLeft + 10) + "px";
//            webMapAppCopyrightText.style.top = (sHeight - crtHeight - 10) + "px";
//        }
        // set heights of left panel and toggle bar
        webMapAppToggleDisplay.style.height = mHeight  + "px";
        webMapAppPanelScrollDiv.style.height = mHeight  + "px";
}

// function to toggle Dock visibility
function togglePanelDock() {
    if (webMapAppPanelDisplay.style.display=="none") {
        expandPanelDock();
    } else {
        collapsePanelDock();
    }     
}

function expandPanelDock() {
    var image = document.images["CollapseImage"];
    webMapAppPanelDisplay.style.display = "block";
    image.src = "images/collapse_left.gif";
    image.alt = "Collapse";
    webMapAppPanelSlider.style.cursor = "e-resize";
    webMapAppPanelBottomSlider.style.cursor = "e-resize"; 
    webMapAppMapLeft = webMapAppLeftPanelWidth + webMapAppToggleWidth;
    webMapAppMapDisplay.style.left =  webMapAppMapLeft + "px";
    AdjustMapSize(); 
}

function collapsePanelDock() {
    var image = document.images["CollapseImage"];
    dockWidthString = webMapAppPanelDisplayCell.clientWidth + "px";
    webMapAppPanelDisplay.style.display = "none";
    //webMapAppPanelDisplayCell.style.width = "1px";
    image.src = "images/expand_right.gif";
    image.alt = "Expand";
    webMapAppPanelSlider.style.cursor = "default"; 
    webMapAppPanelBottomSlider.style.cursor = "default"; 
    webMapAppMapLeft = webMapAppToggleWidth; 
    webMapAppMapDisplay.style.left =  webMapAppMapLeft + "px";  
    AdjustMapSize();  
   
}  

// function for adjusting element sizes when brower is resized
function AdjustMapSize() {
   // set element widths 
    webMapAppPanelDisplay.style.width =  webMapAppLeftPanelWidth + "px";
    webMapAppToggleDisplay.style.width = webMapAppToggleWidth + "px";
   // get browser window dimensions 
    var sWidth = getWinWidth();
    var sHeight = getWinHeight();
    // calc dimensions needed for map
    var mWidth = sWidth - webMapAppPanelDisplayCell.clientWidth -20;
    var mHeight = sHeight - webMapAppTopBannerHeight - 2;
    var linkDisplay = document.getElementById("LinkBar");
    var pageHeader = document.getElementById("PageHeader");
    if (mWidth<5) mWidth = 5;
    if (mHeight<5) mHeight = 5;  
    webMapAppMapDisplay.style.width = (mWidth-0) + "px";
    linkDisplay.style.width = (sWidth-20) + "px";
    pageHeader.style.width = (sWidth-20) + "px";
    webMapAppMapDisplay.style.left =  webMapAppPanelDisplayCell.clientWidth + "px"; 
   // set heights on elements 
    webMapAppMapDisplay.style.height = mHeight  + "px";
    webMapAppToggleDisplay.style.height = mHeight  + "px";
    webMapAppPanelScrollDiv.style.height = mHeight  + "px";
    if (webMapAppScaleBar!=null) {
        var sbWidth = webMapAppScaleBar.clientWidth;
        var sbHeight = webMapAppScaleBar.clientHeight;
        webMapAppScaleBar.style.left = (sbWidth + 90) + "px";
        webMapAppScaleBar.style.top = (sHeight - sbHeight - 10) + "px";
    } 
    if (webMapAppInMapNav!=null){
        var sbWidth = webMapAppInMapNav.clientWidth;
        var sbHeight = webMapAppInMapNav.clientHeight;
         webMapAppInMapNav.style.left = (webMapAppMapLeft + 23) + "px";
         webMapAppCompassWorker.style.left = (webMapAppMapLeft + 29) + "px";
        //webMapAppInMapNav.style.top = (105 + 0) + "px";
//         webMapAppInMapNav.style.left = (sWidth-sbWidth)/2 - 32 + "px"; //(sWidth - sbWidth - 10) + "px";
//         webMapAppInMapNav.style.top = 30 + "px"; //(105 + 0) + "px";
//         webMapAppCompassWorker.style.left = (sWidth-sbWidth)/2 - 9 + "px";
//            webMapAppCompassWorker.style.top = 52 + "px";
    }
    if(webMapAppCacheZoom != null)
        {
//            var box = calcElementPosition("Map_Panel"); 
              webMapAppCacheZoom.style.left = (webMapAppMapLeft + 37) + "px";
//            webMapAppCacheZoom.style.top = 105 + "px";
        }
   // resize the map 
    window.setTimeout("resizeTheMap(" + mWidth + ", " + mHeight + ", false);", 500);
   // update map properties 
     
    var box = calcElementPosition("Map_Panel"); 
    map.containerLeft = box.left;
	map.containerTop = box.top;
//    if (webMapAppCopyrightText!=null) {
//        var crtHeight = webMapAppCopyrightText.clientHeight;
//        webMapAppCopyrightText.style.left = (box.left + 10) + "px";
//        webMapAppCopyrightText.style.top = (sHeight - crtHeight - 10) + "px";
//    }
    return false;
}

// function for resizing map in Web Map App
function resizeTheMap(width, height, resizeExtent) {
    if (resizeExtent==null) resizeExtent = true;
    map.resize(width, height, resizeExtent);
    var div = document.getElementById("LeftPanelCellDiv"); 
    // update overview, if doc panel is expanded 
    if (ov!=null && div.style.display!="none") { 
        var argument = "ControlType=OverviewMap&EventArg=OverviewZoom";
        var context = ov.controlName; 
        eval(ov.callBackFunctionString);
    }
    return false; 
}

// handler for window resize
function AdjustMapSizeHandler(e) {
    window.clearTimeout(reloadTimer);
	reloadTimer = window.setTimeout("AdjustMapSize();",1000);
}

// function run at startup
function startUp() {
        // set up identify mode for javascript
        map.ctrlMode = "MapIdentify";
        map.ctrlAction = "Point";
        map.ctrlCursor = "pointer";
        map.ctrlFunction = "MapIdClick(e)";
        if (newLoad) {
            // execute only on intial load.... not callbacks
            map.divObject.style.cursor = "wait";
            // move magnifier and measure toolbar to top left corner of map display 
            var box = calcElementPosition("Map_Panel"); 
            var mag = document.getElementById("Magnifier1");
            if (mag!=null && typeof(esriMagnifiers)!="undefined" && esriMagnifiers!=null) { 
                    floatingPanel = esriMagnifiers["Magnifier1"].floatingPanel; 
                    if (floatingPanel!=null) moveTo(box.left, box.top);
            }
            var tb = document.getElementById(m_measureToolbarId);
			if (tb!=null) {
			    tb.style.left = box.left + "px";
			    tb.style.top = box.top + "px";
			}
			var fp = document.getElementById("CopyrightText_Panel");
			if (fp!=null) {
			    floatingPanel = fp;
			    moveTo(box.left, box.top);
			}
 
        } 
        // set window resize event handler
       window.onresize = AdjustMapSizeHandler;
       for (var fp in FloatingPanels) {
            FloatingPanels[fp].onDockFunction = scrollDockToPanel;
       }   
       
}  

// function to request closing of session items.... only called if at least one resource is local non-pooled
function CloseOut() {
	var argument = "ControlID=Map1&ControlType=Map&EventArg=CloseOutApplication";
	var context = map.controlName;
	eval(webMapAppCloseCallback);
}

// response function to close out browser ... request sent to server by CloseOut()
function CloseOutResponse(response, context) {
    window.close(); 
    // if user selects Cancel in close dialog, send to close page 
    document.location = response; 
}


function startWebMapAppDockDrag(e) {
    webMapAppMoveFunction = document.onmousemove;
    document.onmouseup = stopWebMapAppDocDrag;  
    if (webMapAppPanelDisplay.style.display!="none") {
        webMapAppWindowWidth = getWinWidth();
        getXY(e); 
        webMapAppLeftOffsetX = mouseX - webMapAppPanelDisplay.clientWidth;
        var box = calcElementPosition("Map_Panel");
        webMapAppRightOffsetX = box.left - mouseX; 
        document.onmousemove = moveWebMapAppDockDrag;
        var ovPanel = document.getElementById("OverviewMap_Panel_BodyRow");
        var ovDisplay =  document.getElementById("OVDiv_OverviewMap_Panel_OverviewMap1");
        // because the panel cell will be as wide as the overview map image, keep the element width larger than the image. 
        if (FloatingPanels["OverviewMap_Panel"]!=null &&FloatingPanels["OverviewMap_Panel"].docked)
            webMapAppMinDockWidth = parseInt(ovDisplay.style.width) + 20;
        else    
            webMapAppMinDockWidth = webMapAppDefaultMinDockWidth; 
    }
    return false;  
}

function moveWebMapAppDockDrag(e) {
    getXY(e);
    webMapAppLeftPanelWidth =  mouseX - webMapAppLeftOffsetX;
    if (webMapAppLeftPanelWidth < webMapAppMinDockWidth) webMapAppLeftPanelWidth = webMapAppMinDockWidth; 
    var mapLeftString =  (webMapAppLeftPanelWidth + webMapAppToggleDisplay.clientWidth) + "px";
    //if (webMapAppPanelDisplayTableCell.clientWidth - webMapAppToggleDisplay.clientWidth > webMapAppLeftPanelWidth) webMapAppLeftPanelWidth = webMapAppPanelDisplayTableCell.clientWidth - webMapAppToggleDisplay.clientWidth;
    var widthString =  webMapAppLeftPanelWidth + "px";
    webMapAppPanelDisplay.style.width = widthString;
    //var width =  webMapAppWindowWidth - webMapAppMapDisplay.clientWidth;
    var width =  webMapAppWindowWidth - webMapAppPanelDisplayCell.clientWidth; 
    webMapAppMapDisplay.style.width = (width-0) + "px";
    webMapAppMapDisplay.style.left = mapLeftString;
    return false;
}

function stopWebMapAppDocDrag(e) {
    document.onmousemove = webMapAppMoveFunction;
    document.onmouseup = null;   
    webMapAppCheckPanelWidths();
    AdjustMapSize();  
    return false;
}

function OpenWindow(url) {
    window.open(url);
}

function webMapAppCheckPanelScroll() {
    if (webMapAppPanelScrollDiv.scrollHeight>webMapAppPanelScrollDiv.clientHeight) {
        webMapAppHasScroll = true;
    }  else {
        webMapAppHasScroll = false;
    }  
    //webMapAppCheckPanelWidths(); 
    if (webMapAppHasScroll!=webMapAppLastHasScroll)
        AdjustMapSize();
    webMapAppLastHasScroll = webMapAppHasScroll;    
    return false; 
}

function webMapAppCheckPanelWidths() {
    var maxWidth = 0;
    var node; 
    for (var i=0; i< webMapAppPanelDisplay.childNodes.length; i++) {
        if (webMapAppPanelDisplay.childNodes[i].tagName=="TABLE") {
            node = webMapAppPanelDisplay.childNodes[i];
            if (node.clientWidth>maxWidth) maxWidth = node.clientWidth; 
        }
    }  
     webMapAppPanelDisplay.style.width = maxWidth + "px";
    return false;
}

function webMapAppGetCopyrightText() {
	var argument = "ControlID=Map1&ControlType=Map&EventArg=GetCopyrightText";
	var context = map.controlName;
	eval(webMapAppCopyrightCallback);
	showFloatingPanel('CopyrightText_Panel');
}

function scrollDockToPanel(panelElement) {
    if (panelElement==null) return;
    var yPos = panelElement.offsetTop;
    webMapAppPanelScrollDiv.scrollTop = yPos;      
}

function toggleMagnifier() {
    var mag = document.getElementById("Magnifier1");
    if (mag!=null) { 
            toggleFloatingPanelVisibility('Magnifier1'); 
    } else 
        alert("Magnifier is not available"); 
    
}


//RTD added functions

//Fires a Callback to the Server
//Parameters:
//  ServerFunction - The case to execute on the server
//  ServerMode -    The mode being exected
//  ServerVars - Any values used in executing serverside function.  Values need to be in var=value&var=value&var=value format
//  Example ServerVars: objectid=34&layer=Roads
//  Author: David Jones - Idea Integration
function FireCallBack(ServerFunction,ServerMode,ServerVars)//,Async)
{
    if(ServerVars != "")
    {
        ServerVars = "&" + ServerVars;
    }
    var message = "ControlID=Map1&ControlType=Map&EventArg=" + ServerFunction + "&Map1_mode=" + ServerMode + ServerVars; 
    var context = map.controlName;
   
    WebForm_DoCallback('__Page',message,processCallbackResult,context,postBackError,true);

}

//Repositions scalebar.  Called after callback update on scalebar.
function resetScalebar(){
    var sWidth = getWinWidth();
    var sHeight = getWinHeight();
    webMapAppScaleBar = document.getElementById("ScaleBar1");
    if (webMapAppScaleBar!=null) {
            var sbWidth = webMapAppScaleBar.clientWidth;
            var sbHeight = webMapAppScaleBar.clientHeight;
            webMapAppScaleBar.style.left = (sbWidth + 90) + "px";
            webMapAppScaleBar.style.top = (sHeight - sbHeight - 10) + "px";
            webMapAppScaleBar.style.width = "auto";
            webMapAppScaleBar.style.height = "auto";
            //alert("scalebar reset to left:" +  webMapAppScaleBar.style.left + ", top:" +  webMapAppScaleBar.style.top);
        } 
}

function showMapPropertiesFP()
{
    toggleFloatingPanelVisibility("MapProperties");
    UpdateZOrder("MapProperties");
}
function showDownload()
{
    document.getElementById('datadownload').src = "datadownload.aspx";
    toggleFloatingPanelVisibility("DownloadPanel");
    UpdateZOrder("DownloadPanel");
}
function showEmail()
{
     document.getElementById('commentframe').src = "comment.aspx";
     toggleFloatingPanelVisibility("CommentPanel");
     UpdateZOrder("CommentPanel");
}
function showPrintPage()
{
    showFloatingPanel('PrintPanelFP');
    UpdateZOrder("PrintPanelFP");
}
function resetCoordUnits(coordType){
    webMapCoordUnits = coordType;
    alert("coord units changed");
}

function showCoordsFP()
{
    toggleFloatingPanelVisibility("CoordinatePanel");
    UpdateZOrder("CoordinatePanel");
    if(ShowingCoords)
    {
        ShowingCoords = false;
    }else{
        ShowingCoords = true;
    }
}

function showCoords(e)
{
    if(ShowingCoords)
    {

       e=(window.event)? window.event:e;

    
        var cx = document.getElementById("coordinate_x");
        var cy = document.getElementById("coordinate_y");
        var cu = document.getElementById("coordinate_units");
        
        //retrieves current coord unit from hidden variable.  If Map Properties floating panel id is changed, this must be updated.
        webMapCoordUnits = document.getElementById("MapProperties_SelectedCoordUnit").value;
        
        getXY(e);
        
        
        
        var box = calcElementPosition(map.containerDivId);
	    zleft = mouseX - box.left;
	    ztop = mouseY - box.top;
	    //box.width = box.width * 1.1;
	    
	    zleft = mouseX - map.containerLeft;
	    ztop = mouseY - map.containerTop;
//	vo.clear();
//	vo.crosshair(zleft, ztop);
//	vo.draw();

//	map.xMin=zleft;
//	map.yMin=ztop;
//	map.getTopLeftTile();
//    coordString = + zleft + ":" + ztop;
	    
	    iWidth = map.viewWidth;
    iHeight = map.viewHeight;  
    zleft = mouseX - iWidth;
    ztop = mouseY - iHeight;
//    mapminx = parseFloat(ext[1]); 
//    mapminy = parseFloat(ext[2]); 
//    mapmaxx = parseFloat(ext[3]); 
//    mapmaxy = parseFloat(ext[4]);
//    xDistance = Math.abs(mapminx - mapmaxx);
//    yDistance = Math.abs(mapmaxy - mapminy);  
	    

	    var ExtentStr = document.getElementById("MapExtent").value;
	    var ExtentAr = ExtentStr.split(",");
    	
	    var x = Math.round((ExtentAr[0]*1 + (ExtentAr[1]*1 - ExtentAr[0]*1) * zleft / iWidth)*100/100);  
        var y =  Math.round((ExtentAr[3]*1 + (ExtentAr[2]*1 - ExtentAr[3]*1) * ztop / iHeight)*100/100);
        
        if(webMapCoordUnits == "latlong"){
            var latLonDdStr = convertSP(x,y);
	        var ll = latLonDdStr.split("|");
	        var LonDD = ll[0];
	        var LatDD = ll[1];
	        x = (Math.round(LatDD * 1000000)) / 1000000;
	        y = (Math.round(LonDD * 1000000)) / 1000000;
	        cx.innerHTML = "Latitude: " + x;
            cy.innerHTML = "Longitude: " + y;
            cu.innerHTML = "(Decimal Degrees)";
        }else{
            cx.innerHTML = "Easting: " + x;
            cy.innerHTML = "Northing: " + y;
            cu.innerHTML = "Colorado State Plane (Feet) - Central Zone";
        }
    }
}

// Code to convert from map units to decimal degrees.
// Code based on asp code from Gerry Daumiller, Montana State Library 8-23-02 email. 
// ASP code on web at http://nris.state.mt.us/gis/projection/projection.html.  
// Translated to javascript by Jeff Miller, Jefferson County, WA.

// The formulae this program is based on are from "Map Projections,
// A Working Manual" by John P. Snyder, U.S. GeoLogical Survey
// Professional Paper 1395, 1987, pages 295-298

// Set up the coordinate system parameters.  Need to edit these based on state plane zone.  
// Modified for Colorado State Plane, Central Zone by Denver-RTD, DJones 1/2007

function convertSP(uX,uY) {
a = 20925604.48;   		//major radius of ellipsoid, map units (NAD 83)
ec = 0.08181905782;  		//eccentricity of ellipsoid (NAD 83)
angRad = 0.01745329252;  	//number of radians in a degree
pi4 = Math.PI / 4;  		//Pi / 4
p0 = 37.83333333 * angRad; 	 	//latitude of origin
p1 = 38.45000000 * angRad;  		//latitude of first standard parallel
p2 = 39.75000000 * angRad;  	//latitude of second standard parallel
m0 = -105.50000000 * angRad;  	//central meridian
x0 =  3000000.00031608; 		//False easting of central meridian, map units
y0 = 999999.99999600;           //False northing, map units

// Calculate the coordinate system constants.
with (Math) {
m1 = cos(p1) / sqrt(1 - (pow(ec,2)) * pow(sin(p1),2));  
m2 = cos(p2) / sqrt(1 - (pow(ec,2)) * pow(sin(p2),2));
t0 = tan(pi4 - (p0 / 2));
t1 = tan(pi4 - (p1 / 2));
t2 = tan(pi4 - (p2 / 2));
t0 = t0 / pow(((1 - (ec * (sin(p0)))) / (1 + (ec * (sin(p0))))),ec/2);  
t1 = t1 / pow(((1 - (ec * (sin(p1)))) / (1 + (ec * (sin(p1))))),ec/2);
t2 = t2 / pow(((1 - (ec * (sin(p2)))) / (1 + (ec * (sin(p2))))),ec/2);
n = log(m1 / m2) / log(t1 / t2);
f = m1 / (n * pow(t1,n)); 
rho0 = a * f * pow(t0,n);

// Convert the coordinate to Latitude/Longitude.

//remove false easting, northing
uX = uX - x0;
uY = uY - y0;

// Calculate the Longitude.
pi2 = pi4 * 2;

rho = sqrt(pow(uX,2) + pow((rho0 - uY),2));  
theta = atan(uX / (rho0 - uY));
txy = pow((rho / (a * f)),(1 / n));
lon = (theta / n) + m0;
uX = uX + x0;

// Estimate the Latitude
lat0 = pi2 - (2 * atan(txy));

// Substitute the estimate into the iterative calculation that
// converges on the correct Latitude value.
part1 = (1 - (ec * sin(lat0))) / (1 + (ec * sin(lat0)));
lat1 = pi2 - (2 * atan(txy * pow(part1,(ec/2))));

while ((abs(lat1 - lat0)) > 0.000000002) {
  lat0 = lat1;
  part1 = (1 - (ec * sin(lat0))) / (1 + (ec * sin(lat0)));
  lat1 = pi2 - (2 * atan(txy * pow(part1,(ec/2))));
  }

// Convert from radians to degrees.
Lat = lat1 / angRad;
Lon = lon / angRad;

return Lon + "|" + Lat;
}
}
//End of Code for converting map units to decimal degrees.

function cancelCoords()
{
window.status = "now";
}

function SetBufferBusy()
{
    BufferImageSpan = document.getElementById('BufferWorkingSpan');
    BufferImageSpan.innerHTML = "&nbsp;<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Creating Buffer...";
}
function SetFindBusy()
{
    AutoBusy = true; //cancels auto updating of data
    FindDiv = document.getElementById('FindWorking');
    FindDiv.innerHTML = "&nbsp;<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Searching...";
}

function SetSelectResultsBusy()
{
    alert("yo now we done");
    //var fpBody = document.getElementById('Results_TaskResults1');
	//var html = fpBody.innerHTML;
	//fpBody.innerHTML = "<div><img src='images/callbackActivityIndicator.gif' align='middle'/> Getting Information. . .</div>" + html;
	//showFloatingPanel('Results');
	//fpBody=document.getElementById('Results_BodyRow');
	//if (fpBody.style.display=="none")
	//    toggleFloatingPanelState('Results','images/collapse.gif','images/expand.gif');
}

//Causes a callback on the map to occur which will zoom to a box around x,y
function ZoomToBox(xmin,ymin,xmax,ymax,layer)
{
    document.getElementById('attributes_status_div').innerHTML = "&nbsp;<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Zooming to Selected Feature...";
	FireCallBack("ZoomToBox","AttributeResults","xmin=" + xmin + "&ymin=" + ymin + 
        "&xmax=" + xmax + "&ymax=" + ymax + "&layer=" + layer );
}

//Causes a callback on the map to occur which will zoom to a box around objectid in the graphics layer
function ZoomToBox2(layer,objectid)
{
    document.getElementById('attributes_status_div').innerHTML = "&nbsp;<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Zooming to Selected Feature...";
	FireCallBack("ZoomToBox","AttributeResults","layer=" + layer + "&objectid=" + objectid );
}

//causes a callback which will highlight the specified object from the layer in the Graphics resource.  In additon highlights the row on the 
//html attribute table
function HighlightFeature(id,Rowcount,ObjectID, Layer)
{
    var i;
    var tablerow = document.getElementById(id);
    var turnOff = false;
    //document.getElementById('attributes_status_div').innerHTML = "&nbsp;<img alt='Working Indicator' src='images/callbackActivityIndicator.gif' align='middle' />&nbsp;Highlighting Feature...";
    if (tablerow.className == "MapViewer_TableDataSelectedStyle")
    {
        turnOff = true;
    }
    for(i=0;i<Rowcount;i++)
    {
        var tablerow = document.getElementById("AttributeRow_" + i);
        tablerow.className = "MapViewer_TableDataStyle";
    }
    if(turnOff == false){
        var tablerow = document.getElementById(id);
        tablerow.className = "MapViewer_TableDataSelectedStyle";
    }
    Layer = Layer.replace("&","**");
	FireCallBack("HighlightFeature","AttributeResults","objectid=" + ObjectID + "&layer=" + Layer);
}

function SetMaxWidth(ObjectName)
{
    var Ob = document.getElementById(ObjectName);
    Ob.className = "MaxWidth";
    alert(Ob.style.width);
}

function ShowAttributes(Layer, ZoomToExtent)
{
     //alert("ShowAttributes: " + Layer + " " + ZoomToExtent);
     FireCallBack("ShowAttributes","AttributeResults","layer=" + Layer + "&zoomextent=" + ZoomToExtent);
}
function AttributeButtonOver(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "AttributeButtonSelected"; 
}
function AttributeButtonOut(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "AttributeButton"; 
}
function AttributeLinkOver(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "AttributeLinkSelected"; 
}
function AttributeLinkOut(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "AttributeLink"; 
}
function FPButtonOver(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "FPToolButtonSelected"; 
}
function FPButtonOut(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "FPToolButton"; 
}
function ShowMapBufferFP()
{
    toggleFloatingPanelVisibility("BufferPanel");
    UpdateZOrder("BufferPanel");
}
function ShowExportFP()
{
    toggleFloatingPanelVisibility("ExportPanel");
    UpdateZOrder("ExportPanel");
}
function ShowLegendFP()
{
    toggleFloatingPanelVisibility("LegendPanel");
    UpdateZOrder("LegendPanel");
}
function GeocodeOver(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "GeocodeValueHover"; 
}
function GeocodeOut(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "GeocodeValue"; 
}

//Causes a callback to reload a resource automatically, every MilliSeconds
function AutoRefreshResource(MilliSeconds,Resource)
{
    if(AutoBusy == false)
    {
        //refresh and restart timer
        ShowLoadingBanner("Updating Live Data...");
        FireCallBack("RefreshResource","RefreshResource","resource=" + Resource);
        setTimeout("AutoRefreshResource(" + MilliSeconds + ",'" + Resource +"')", MilliSeconds);
    }else
    {
        //don't refresh, just start timer again
        setTimeout("AutoRefreshResource(" + MilliSeconds + ",'" + Resource +"')", MilliSeconds);
    }
}
function TempRefreshData()
{
        ShowLoadingBanner("Updating Live Data...");
        alert("firing call back to refresh: " + "live busses"); 
        FireCallBack("RefreshResource","RefreshResource","resource=live busses");
        alert("fired callback");
}
function ShowLoadingBanner(Text)
{
    var LoadingBanner = document.getElementById("LoadingBanner");
    LoadingBanner.innerHTML = "<img src=\"images/loading.gif\" alt=\"Loading Map Indicator\" />&nbsp;" + Text;
    LoadingBanner.style.backgroundColor = "white";
}

function HideLoadingBanner()
{
     var LoadingBanner = document.getElementById("LoadingBanner");
     LoadingBanner.innerHTML = "";
     LoadingBanner.style.backgroundColor = "transparent";
}

function UpdateFloatingPanelSize(FloatingPanelID,NewWidth,NewHeight)
{
    floatingPanel=document.getElementById(FloatingPanelID);
    esriPanel = FloatingPanels[FloatingPanelID];
    floatingPanelBodyCell = document.getElementById(floatingPanel.id+'_BodyCell');
    floatingPanelSideResizeCell=document.getElementById(floatingPanel.id+'_SideResizeCell');
    resize(NewWidth, NewHeight);
}

function Test()
{
    window.status = "Test occured";
}

function FindTypeChange()
{
    document.getElementById("FindItemArea").innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
    var FindTypeObj = document.getElementById("Tasks_Menu_Panel_FindType");
    //var Icon = FindTypeObj.style.backgroundImage;
    //document.getElementById('FindIcon').innerHTML = "<img src='images/pnr.png' alt='icon' />";
    var FindTypeVal = FindTypeObj.options[FindTypeObj.selectedIndex].value;
    if (FindTypeVal != "ignore")
    {
        FireCallBack("Find_TypeChanged","FindType","value=" + FindTypeVal);
    }else{
        document.getElementById("FindItemArea").innerHTML = "";
    }
}
function FindItemChange()
{
    var FindTypeObj = document.getElementById("Tasks_Menu_Panel_FindType");
    var FindTypeVal = FindTypeObj.options[FindTypeObj.selectedIndex].value;
    var FindItemObj = document.getElementById("FindItem");
    var FindItemVal = FindItemObj.options[FindItemObj.selectedIndex].value;
    if (FindTypeVal != "ignore" && FindItemVal != "ignore")
    {
        FireCallBack("Find_ItemChanged","FindType","type=" + FindTypeVal + "&value=" + FindItemVal);
    }
}
function FindGeocode()
{
    var FindTypeObj = document.getElementById("Tasks_Menu_Panel_FindType");
    var FindTypeVal = FindTypeObj.options[FindTypeObj.selectedIndex].value;
    var FindItemVal = escape(document.getElementById("FindItem").value);
    
    if (FindTypeVal != "ignore")
    {
        var FindWorking =  document.getElementById("FindWorking");
        FindWorking.innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
        FireCallBack("Find_ItemChanged","FindType","type=" + FindTypeVal + "&value=" + FindItemVal);
    }
}
function FindText()
{
    var FindTypeObj = document.getElementById("Tasks_Menu_Panel_FindType");
    var FindTypeVal = FindTypeObj.options[FindTypeObj.selectedIndex].value;
    var FindItemVal = document.getElementById("FindItem").value;
    if (FindTypeVal != "ignore")
    {
         var FindWorking =  document.getElementById("FindWorking");
        FindWorking.innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
        FireCallBack("Find_ItemChanged","FindType","type=" + FindTypeVal + "&value=" + FindItemVal);
    }
}


function TurnOffMapTips()
{
    FireCallBack("maptips","maptips","show=false");
}
function TurnOnMapTips()
{
    FireCallBack("maptips","maptips","show=true");
}

function CreateBuffer()
{
    var BufObj = document.getElementById("BufferPanel_BufferDistance");
    var BufDistance = BufObj.value;
    if( parseFloat(BufDistance) != "NaN")
    {
        BufDistance = parseFloat(BufDistance);
        var BufUnitObj = document.getElementById("BufferPanel_BufferUnits");
        var BufUnit = BufUnitObj.options[BufUnitObj.selectedIndex].value;
        var BufLayObj = document.getElementById("BufferPanel_BufferLayer");
        var BufLayer = BufLayObj.options[BufLayObj.selectedIndex].value;
       
        FireCallBack("Buffer","Buffer","distance=" + BufDistance + "&unit=" + BufUnit + "&layer=" + BufLayer);
    }
}

function ClearSelection()
{
    FireCallBack("ClearSelection","Selection","remove=true");
}
function OpenTable()
{
    toggleFloatingPanelVisibility("AttributesPanel");
    UpdateZOrder("AttributesPanel");
}

function OpenGeocoderAttributes(X,Y,Name)
{
    showFloatingPanel('GeocoderDisplay');
    //toggleFloatingPanelVisibility("GeocoderDisplay");
    
    //clear out any old results
    document.getElementById("LocationAttributes").innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
    
    UpdateZOrder("GeocoderDisplay");
    FireCallBack("GeoCodeDataDisplay","Geocoder","Name=" + escape(Name) + "&X=" + X + "&Y=" + Y);
}

//*****

function showBusyIndicator(sender) {

            showLayer("BusyIndicator");

            if (sender!=null) {

                window.status = "Pending Tiles: " + sender.pendingTiles.length; 

            }  

        }

        

        function showPendingTiles(sender) {

            if (sender!=null) {

                window.status = "Pending Tiles: " + sender.pendingTiles.length; 

            }  

        }

        

        function hideBusyIndicator(sender) {

            hideLayer("BusyIndicator");

            if (sender!=null) {

                window.status = ""; 

            }  

        } 




function UpdateZOrder(control,Down)
{
    var TempControl = document.getElementById(control);
     FPZIndex = FPZIndex + 1;
    if(Down != null)
    {
        TempControl.style.zIndex = FPZIndex - 3;
        FPZIndex = FPZIndex - 3;
        
    }else{
        TempControl.style.zIndex = FPZIndex;
    }
    //alert(control + "-" + TempControl.style.zIndex);
}


function LoadInlineHelp(URL,Title)
{
    document.getElementById("InlineHelpIFrame").src = URL;
    showFloatingPanel('InlineHelp');
    UpdateZOrder("InlineHelp");
    document.getElementById("InlineHelp_TitleCell").innerHTML = Title;
}

function testtab()
{
    var tabbar=new dhtmlXTabBar("ExternalContentTabs","top");
        tabbar.setImagePath("jstabbarimages/");
        tabbar.setStyle("modern");
        tabbar.setHrefMode("iframes");

        var ExternalTabCount = 0;
        var ExternalTabCounter = 0;
}

var ExternalTabRowID;
var LastRemovedTabID;
function LoadExternalIFrame(URL,Title,FrameTitle, RowID)
{
    //ExternalTabCount++;
    if(ExternalTabCount > 4)
    {
        alert('There are already 5 tabs loaded in the multi-media window, please remove a tab to load new tab');
    }else{
        if(RowID == ExternalTabRowID || ExternalTabRowID == null)
        {
            //add tab to existing set of tabs, as its the same record from same layer.
            //alert("adding tab: " + ExternalTabCounter);
            tabbar.addTab('extab' + ExternalTabCounter,'Loading...','80px',ExternalTabCount);
            tabbar.setLabel('extab' + ExternalTabCounter,Title);
            //tabbar.setContentHref('extab' + ExternalTabCounter,URL);
            tabbar.setContentHref('extab' + ExternalTabCounter,URL);
            tabbar.setTabActive('extab' + ExternalTabCounter);
            ExternalTabCounter++;
            ExternalTabCount++;
            ExternalTabRowID = RowID;
        }else
        {
            //different set of data, clear out old multimedia tabs and start over.
            tabbar.clearAll();
            ExternalTabCounter = 0;
            ExternalTabCount = 0;
            tabbar.addTab('extab' + ExternalTabCounter,'Loading...','80px',ExternalTabCounter);
            tabbar.setLabel('extab' + ExternalTabCounter,Title);
            tabbar.setContentHref('extab' + ExternalTabCounter,URL);
            tabbar.setTabActive('extab' + ExternalTabCounter);
            ExternalTabCounter++;
            ExternalTabCount++;
            ExternalTabRowID = RowID;
        }
    }
    
    //document.getElementById("ExternalContentIFrame").src = URL;
    showFloatingPanel('ExternalContent');
    UpdateZOrder("ExternalContent");
    if(FrameTitle != null)
    {
        document.getElementById("ExternalContent_TitleCell").innerHTML = FrameTitle;
    }else
    {
        document.getElementById("ExternalContent_TitleCell").innerHTML = Title;
    }
    UpdateZOrder('AttributesPanel',1);
}
function ExternalContent_RemoveTab()
{
    var loctabid = tabbar.getActiveTab();
    tabbar.removeTab(loctabid,true);
    LastRemovedTabId = loctabid;
    ExternalTabCount--;
    if(ExternalTabCount == 0)
    {
    tabbar.clearAll();
    ExternalTabCounter = 0
    }
}
function ExternalContent_OpenBrowser()
{
    var loctabid = tabbar.getActiveTab();
    var tabwin = tabbar.tabWindow(loctabid);
    //alert(tabwin.location);
    var Win = window.open (tabwin.location,"","status=1,toolbar=1,width=800,height=600,scrollbars=1,resizable=1,menubar=1");
    //Win.location = tabwin.location;
}
function CreateMapLayout(typecontrol,textcontrol)
{
    ExportImageDiv = document.getElementById('ExportPanelWorking');
    ExportImageDiv.innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
 loctrl = document.getElementById(typecontrol);
 selIndex = loctrl.selectedIndex;
 locval = loctrl.options[selIndex].value;
 textval = document.getElementById(textcontrol).value;
 FireCallBack("ExportMap","ExportMap","format=" + locval + "&title=" + textval);
}


function GeocodeToPoint(X,Y,rowId)
{  
 var GCount = document.getElementById('GeocodeResCount').value;

 for(i=0;i<GCount;i++)
 {
    var Ob = document.getElementById('geocodeRow' + i);
    Ob.className = 'GeocodeRow';
 }

 var Ob = document.getElementById(rowId);
 Ob.className = 'GeocodeRowSel';
 
 //clear out any contents of the geoattributes window
 document.getElementById("LocationAttributes").innerHTML = "";
 hideFloatingPanel('GeocoderDisplay');
 
 FireCallBack("ZoomToPoint","ZoomToPoint","x=" + X + "&y=" + Y);
}

function ZoomOutLevel()
{
    FireCallBack("ZoomOutLevel","ZoomOutLevel","zoomout=true");
}

function ZoomFullExtent()
{
    //alert("zoomFullExtent");
    FireCallBack("ZoomFullExtent","ZoomFullExtent","fullextent=true");
}

function OpenBrowserWin(frameID)
{
    var frame = document.getElementById(frameID);
    //alert(frame);
    var Win = window.open (frame.src,"","status=1,toolbar=1,width=800,height=600,scrollbars=1,resizable=1,menubar=1");
    //Win.location = frame.src; 
}

//--Help functions --//

function OpenHelp()
{
    window.open ("Help/Default.htm","","status=1,toolbar=1,width=600,height=800,scrollbars=1"); 
}

function MapContextMenu_CenterAt(e)
{
   e=(window.event)? window.event:e;

   getXY(e);

   var box = calcElementPosition(map.containerDivId);
   locX = mouseX - box.left;
   locY = mouseY - box.top;
	    
   //alert(locX +" " + locY);
   FireCallBack("ContextMenu_CenterAt","ContextMenu","x=" + locX + "&y=" + locY);
	   
}

function disableEnterKey(e)
{

     var key;
     var e;
     e=(window.event)? window.event:e;
     if(window.event){
          key = e.keyCode;     //IE
     }else{
          key = e.which;     //firefox
     }
     if(key == 13){  
        return false;
     }else{
          return true;
     }
}
function findGeocodeonEnter(e)
{
    var key;
     var e;
     e=(window.event)? window.event:e;
     if(window.event){
          key = e.keyCode;     //IE
     }else{
          key = e.which;     //firefox
     }
     if(key == 13){  
        //alert('running geocode');
        var FindTypeObj = document.getElementById("Tasks_Menu_Panel_FindType");
        var FindTypeVal = FindTypeObj.options[FindTypeObj.selectedIndex].value;
        var FindItemVal = escape(document.getElementById("FindItem").value);
        
        if (FindTypeVal != "ignore")
        {
            var FindWorking =  document.getElementById("FindWorking");
            FindWorking.innerHTML = "<img alt='Working Indicator' src='images/loading.gif' align='middle' />&nbsp;Working...";
            FireCallBack("Find_ItemChanged","FindType","type=" + FindTypeVal + "&value=" + FindItemVal);
        }
     }
}
function MapTipLinkOver(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "RTD_MapTipScheduleLinkerOver"; 
}
function MapTipLinkOut(id)
{
    var Ob = document.getElementById(id);
    Ob.className = "RTD_MapTipScheduleLinker"; 
}
function MapTipLinkOver2(e)
{
   if (!e) var e = window.event; 
   //var linkID = e.srcElement? e.srcElement.id : this.id;
   var Elem = e.srcElement? e.srcElement: this;
  // var Ob = document.getElementById(linkID);
    Elem.className = "RTD_MapTipScheduleLinkerOver";    
}
function MapTipLinkOut2(e)
{
    if (!e) var e = window.event;
    var Elem = e.srcElement? e.srcElement: this;
    //var linkID = e.srcElement? e.srcElement.id : this.id; 
    //var Ob = document.getElementById(linkID);
    Elem.className = "RTD_MapTipScheduleLinker";    
}




//Help tips Functions

function HelpShowBox(e) {  
if (!e) var e = window.event;  
var linkID = e.srcElement? e.srcElement.id : this.id;  
var helpbox = document.getElementById('helpbox');  
for(i=0;i<HelpArray.length;i++)
    {
     if(HelpArray[i][0] == linkID)
         {
            helpbox.innerHTML = HelpArray[i][1]; //helptexts[linkID.substr(4) - 1];  
            helpbox.style.display = 'block'; 
            var posx = (typeof e.pageX!= 'undefined')? e.pageX  : e.clientX + (document.documentElement? document.documentElement.scrollLeft  : document.body.scrollLeft);  
            var posy = (typeof e.pageY!= 'undefined')? e.pageY  : e.clientY + (document.documentElement? document.documentElement.scrollTop  : document.body.scrollTop); 
            helpbox.style.top = posy - 20 + 'px'; 
            helpbox.style.left = posx + 10 + 'px';
         }
    }  
} 

function HelpHideBox() {  document.getElementById('helpbox').style.display = 'none'; } 

function HelpBoxInit() { 

    for(i =0; i< HelpArray.length; i++)
    {
     var helpRef = document.getElementById(HelpArray[i][0]);
     if (helpRef.attachEvent) {     
            helpRef.attachEvent('onmouseover', HelpShowBox);     
            helpRef.attachEvent('onmouseout', HelpHideBox);    
        } 
        else if(helpRef.addEventListener) 
        {     
            helpRef.addEventListener('mouseover', HelpShowBox, false);     
            helpRef.addEventListener('mouseout', HelpHideBox, false);
        }   
    }
}

//This replaces the ESRI hideFloatingPanel which doesn't work correctly when 
//fired from a callback sometimes as it creates another one causing app to halt.
function hideFloatingPanel2(fpID)
{   
    floatingPanel=document.getElementById(fpID);
    if (floatingPanel==null)return;                
    esriPanel = FloatingPanels[fpID];
    floatingPanel.style.display='none';
    var hfVisible = document.getElementById(fpID + '_hfVisible');
    if (hfVisible!=null) hfVisible.value='false';
    if (esriPanel.contentOnHideFunction!=null) eval(esriPanel.contentOnHideFunction);
    //show container if directly on page
    var fpContainer = document.getElementById(fpID + "_Container");
    if (fpContainer != null)
        fpContainer.style.display='none';

	ie6Workarounds(fpID);
    //no callbacks here unlike in esri original
}

function RefreshLegend()
{
    FireCallBack("RefreshLegend","RefreshLegend","refresh=true");
}