﻿// JScript File
var wmsCoordSystem = 4326;
var reloadTimer;
var heightOffset = 70;
var widthOffset = 0;
var footerOffset = 55;
var newLoad = false;
var m_CurTool = null;
var map;
function initialize() 
{
	    map = $find('Map1');
	    
	    map.add_mouseMove(mouseMove);
        
        //custom busy indicator
        map.add_onProgress(customProgress);
        

        
}
    
function mouseMove(sender,eventArgs) 
{
    window.status = 'Coordinates: ' +
      eventArgs.coordinate.get_x().toFixed(3) + ', ' +
      eventArgs.coordinate.get_y().toFixed(3);
}
function customProgress(sender, pendingTiles)
	{
		if (sender != null)
		{
			window.status = "Pending tiles: " + pendingTiles;
			if (pendingTiles > 0)
			{
				// showLayer and hideLayer are part of the Web ADF JS library
				// in the display_common.js
				showLayer("BusyIndicator");
			} 
			else 
			{
				hideLayer("BusyIndicator");
			}
		}
	}
// function run at startup
function startUp(bIsMapPage) 
{     
       if (!bIsMapPage)  
       {
         // set window resize event handler
            window.onresize = AdjustFooterHandler;
            //move footer
            adjustFooter();      

        }
        else
        {
                //adjust location of div coords on move
          // set window resize event handler
            window.onresize = AdjustCoordsHandler;
            adjustCoordinates();
//              // set window resize event handler
//            window.onresize = AdjustMapSizeHandler;
//            //move elements
//            AdjustMapSize(false);        
        }
} 

function AdjustCoordsHandler(e)
{
    window.clearTimeout(reloadTimer);
	reloadTimer = window.setTimeout("adjustCoordinates();",1000);
} 
//handler for window resize on page without map
function AdjustFooterHandler(e)
{
    window.clearTimeout(reloadTimer);
	reloadTimer = window.setTimeout("adjustFooter();",1000);
}
// handler for window resize on page with MAP
function AdjustMapSizeHandler(e) 
{
    window.clearTimeout(reloadTimer);
	reloadTimer = window.setTimeout("AdjustMapSize('true');",1000);
}

// function for adjusting element sizes when brower is resized
function AdjustMapSize(bResizeMap) {
 
   // get browser window dimensions 
    var sWidth = getWinWidth();
    var sHeight = getWinHeight();
    // calc dimensions needed for map
    var mWidth = sWidth - widthOffset;
    var mHeight = sHeight - heightOffset;
    if (mWidth<5) mWidth = 5;
    if (mHeight<5) mHeight = 5;  
    var mapDisplay = document.getElementById("Map_Panel");
    if (mapDisplay != null)
    {
        mapDisplay.style.width =  mWidth + "px";
        // set heights on elements 
         mapDisplay.style.height = mHeight  + "px";
    }

   //resize the map  - not on first load
   if (bResizeMap)
   {   
        window.setTimeout("resizeTheMap(" + mWidth + ", " + mHeight + ", true);", 500);
        
    }      
    map = $find('Map1');
    if (map == null)
        return;
    var box = calcElementPosition("Map_Panel"); 
    map.containerLeft = box.left;
	map.containerTop = box.top;
	//move the coordinates to the bottom
	var coords = document.getElementById("divCoordinates");
	if (coords != null)
	{
	    coords.style.left = box.left;
	    coords.style.top = box.top + mHeight - 11;
	}
    adjustFooter();
    return false;
}
function adjustCoordinates()
{
    	var sHeight = window.innerHeight;
	if (sHeight == null) {
		if (document.documentElement && document.documentElement.clientHeight)
			sHeight = document.documentElement.clientHeight;
		else
			sHeight = document.body.clientHeight;
	}
	//move the coordinates to the bottom
	var coords = document.getElementById("divCoordinates");
	if (coords != null)
	{
	    
	    coords.style.top = sHeight - 18;
	}
}
function adjustFooter()
{
	//move footer
	var sHeight = window.innerHeight;
	if (sHeight == null) {
		if (document.documentElement && document.documentElement.clientHeight)
			sHeight = document.documentElement.clientHeight;
		else
			sHeight = document.body.clientHeight;
	}
	var footer = document.getElementById("divHomeFooter");
    if (footer != null)
	{
	    footer.style.top = sHeight - footerOffset;
	}
	return true;
}
// function for resizing map in Web Map App
function resizeTheMap(width, height, resizeExtent) 
{
    if (resizeExtent==null) resizeExtent = true;
        map = $find('Map1');
    if (map == null)
        return;
    map.resize(width, height, resizeExtent); 

    return false; 
}
//map identify
function StartIdentify(id) 
{
    
    m_CurTool = "MapIdentify";
	GetPoint(map.controlName);
	openTask('Identify');
}
//map select
function StartSelect(id) 
{    
    m_CurTool = "MapSelect";
	openTask('Select');
}
function GetPoint() 
{
	map = $find('Map1');
	if (map!=null) 
	{
       //capture a point        
        map.getGeometry(ESRI.ADF.Graphics.ShapeType.Point,MapCoordsClick,null,'black',null,'pointer', true);
	}    
}
function MapCoordsClick(eventArgs) 
{    
        if (!isNaN(eventArgs.get_x()) && !isNaN(eventArgs.get_y())) 
        {
            coords = eventArgs.get_x().toFixed(3) + ":" + eventArgs.get_y().toFixed(3);
            var argument = 'coords='+coords; 
            var context = this; 
            //check current tool to see where to send callback
            switch(m_CurTool)
            {
                case "DFIRM":
                    showDFIRMWait();
                    openTask('DFIRM');          
                    eval(DFIRMCallbackString);
                    break;
                case "MapIdentify":  
                    var ddl = document.getElementById('Identify_ddlLayers');
                    var lyr = ddl[ddl.selectedIndex].value;
                    if (lyr != String.Empty)
                    {              
                        showIdentifyWait();
                        openTask('Identify');          
                        eval(IdentifyCallbackString);
                    }
                     else
                    {
                        alert('Please select a layer to identify');
                    }
                    break;
                default:
                    break;
            }
        }
}  
function showIdentifyWait()
{
    var theTask = document.getElementById('divIdentifyResults');
    if (theTask != null)
    {        
        theTask.innerHTML = "<div id=\"divIdentifyWait\" style=\"display:none;\"><img src='images/callbackActivityIndicator.gif' align='middle' alt=Please Wait/> Getting Information. . . </div>";
    }
        var waitImg = document.getElementById('divIdentifyWait');
    if (waitImg != null)
        waitImg.style.display="";
}

function changeDisplay(id)
{
    var elem = document.getElementById(id);
    if (elem != null)
    {
        if (elem.style.display=="")
            elem.style.display="none";
        else
        {
            elem.style.display=""; //show
        }
            
    }
}
//function to send selected address back on home page
function selectAddress(address)
{
    var inputaddress = document.getElementById("inputaddress");
    if (inputaddress != null) inputaddress.value = address;
    document.Form1.submit();
}
//function to update dfirm panel
function updateDropdown(id, newList)
{
    var div = document.getElementById(id);
    if (div != null)
    {
        div.innerHTML = newList;
    }
}

//function for display of coordinates as user moves coordinates over map
function showCoords(e)
{    
    var cx = document.getElementById("coordinate_x");
    var cy = document.getElementById("coordinate_y");
    var cu = document.getElementById("coordinate_units");
 
    //retrieves current coord unit.  If Map Properties floating panel id is changed, this must be updated.
    webMapCoordUnits = document.getElementById("SelectCoordUnit").value;
    
    getXY(e);        
    
    var box = calcElementPosition("Map_Panel");
  
	zleft = mouseX - box.left;
	ztop = mouseY - box.top;
	
    var mapextent = document.getElementById("MapExtent");
    //alert(mapextent.value);
    if (mapextent != null && mapextent.value != String.Empty)
    {
	    var ExtentStr = mapextent.value;
	    //alert(ExtentStr);
	    var ExtentAr = ExtentStr.split(",");
    	
	    //var x = Math.round((ExtentAr[0]*1 + (ExtentAr[1]*1 - ExtentAr[0]*1) * zleft / box.width)*100/100);  
        //var y =  Math.round((ExtentAr[3]*1 + (ExtentAr[2]*1 - ExtentAr[3]*1) * ztop / box.height)*100/100);
        var x = ExtentAr[0]*1 + (ExtentAr[1]*1 - ExtentAr[0]*1) * zleft / box.width;
        var y = ExtentAr[3]*1 + (ExtentAr[2]*1 - ExtentAr[3]*1) * ztop / box.height;
        if(webMapCoordUnits == "LatLon")
        {
            if (wmsCoordSystem != 4326) //not WGS84
            {
                var latLonDdStr = convertSP(x,y);
	            var ll = latLonDdStr.split("|");
	            var LonDD = ll[0];
	            var LatDD = ll[1];
	             x = (Math.round(LonDD * 1000000)) / 1000000;
	             y = (Math.round(LatDD * 1000000)) / 1000000;
	         }
            cx.innerHTML = "Latitude: " + y;
            cy.innerHTML = "Longitude: " + x;
            cu.innerHTML = "";
        }
        else
        {
            if (wmsCoordSystem == 4326) //WGS84
            {
                //convert to state plane coords
                var latLonDdStr = convertLatLon(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 = "Easting: " + x;
                cy.innerHTML = "Northing: " + y;
                cu.innerHTML = "";
        }
    }
    else
    {
	    cx.innerHTML = "";
        cy.innerHTML = "";
        cu.innerHTML = "";
    }
}


function convertLatLon(lon, lat)
{
    //convert lat/lon coords to state plane

    //http://nris.state.mt.us/gis/projection/geostate_asp.txt
    //geostate.asp    Gerry Daumiller  2/8/99 (Perl version) - 4/17/2002
    //Converts from latitude/Longitude to Montana State Plane Coordinates.
    //This program assumes that the coordinate is
    //in the Western Hemisphere.

    //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
    with (Math) 
    { 
    
        lon = lon - 1;
        // Calculate the coordinate system constants. 
var a = 20925604.48; //major radius of ellipsoid, map units (NAD 83) 
var ec = 0.08181905782; //eccentricity of ellipsoid (NAD 83) 
var angRad = 0.01745329252; //number of radians in a degree 
var pi4 = 3.141592653582 / 4; //Pi / 4 
var p0 = 33.750000 * angRad; //latitude of origin 
var p1 = 34.333333 * angRad; //latitude of first standard parallel 
var p2 = 36.166667 * angRad; //latitude of second standard parallel 
var m0 = -79.000000 * angRad; //central meridian 
var x0 = 2000000.002617; //False easting of central meridian, map units

        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 latitude/longitude to a coordinate.
        lat = lat * angRad;
        lon = lon * angRad;
        t = tan(pi4 - (lat / 2));

        //t = t / (((1 - (e * (sin(lat)))) / (1 + (e * (sin(lat))))) ^ (e / 2))
        
        t = t / (pow((1 - (ec * (sin(lat))))/1 + (ec * (sin(lat)))),ec/2);
        rho = a * f * pow(t,n);
        theta = n * (lon - m0);
        x = (rho * sin(theta)) + x0;
        y = rho0 - (rho * cos(theta));

        //lat = lat / angRad;
        //lon = lon / angRad;

        //Round the coordinates
        x = ((x * 100)) / 100;
        y = ((y * 100)) / 100;
        //lat = ((lat * 100000)) / 100000;
        //lon = ((lon * 100000)) / 100000;
        return x + "|" + y; 
    }
}
function convertSP(uX,uY) 
{ 
    //Projected Coordinate System: NAD_1983_StatePlane_North_Carolina_FIPS_3200_Feet
    //Projection: Lambert_Conformal_Conic
    //False_Easting: 2000000.00261667
    //False_Northing: 0.00000000
    //Central_Meridian: -79.00000000
    //Standard_Parallel_1: 34.33333333
    //Standard_Parallel_2: 36.16666667
    //Latitude_Of_Origin: 33.75000000
    //Linear Unit: Foot_US
 var a = 20925604.48; //major radius of ellipsoid, map units (NAD 83) 
var ec = 0.08181905782; //eccentricity of ellipsoid (NAD 83) 
var angRad = 0.01745329252; //number of radians in a degree 
var pi4 = 3.141592653582 / 4; //Pi / 4 
var p0 = 33.750000 * angRad; //latitude of origin 
var p1 = 34.333333 * angRad; //latitude of first standard parallel 
var p2 = 36.166667 * angRad; //latitude of second standard parallel 
var m0 = -79.000000 * angRad; //central meridian 
var x0 = 2000000.002617; //False easting of central meridian, 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. 

        // Calculate the Longitude. 
        uX = uX - x0; 
        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; 

        //alert(lat); 
        //alert(lon); 

        //Round the latitude and longitude 
        //lat = (CLng(lat * 100000)) / 100000; 
        //lon = (CLng(lon * 100000)) / 100000; 

        //Lat = lat.toPrecision(7); 
        //Lon = lon.toPrecision(8); 

        return Lon + "|" + Lat; 

    } 
} 


function getLayerList(layers)
{


    var txtWMSLayer = document.getElementById('AddData_txtWMSLayer');

    if (txtWMSLayer != null && layers != String.Empty)
    { 
        txtWMSLayer.value = layers;
        changeDisplay('divAddDataWait');
        return true;
    }
    else //could not get layers for display - ok though, can still add the service?
    {
        txtWMSLayer.value = "";
        return true;
    }

}



