﻿/*
util.js handles the logic for sizing of the mapping application
*/


/// <summary>
/// Determines the height of the client window
/// </summary>
/// <returns>height of client window in pixels</returns>
function getWindowHeight() 
{
    if (window.self && self.innerHeight) 
    {
        return self.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) 
    {
        return document.documentElement.clientHeight;
    }
    return 0;
}

/// <summary>
/// Determines the width of the client window
/// </summary>
/// <returns>width of client window in pixels</returns>
function getWindowWidth() 
{
    if (window.self && self.innerWidth) 
    {
        return self.innerWidth;
    }
    if (document.documentElement && document.documentElement.clientWidth) 
    {
        return document.documentElement.clientWidth;
    }
    return 0;
}

/// <summary>
/// Checks zoom level in sq km, and feature count in current envelope.  If either are above threshold, user is alerted.
/// Disable Search Tools is either are above threshold
/// </summary>
/// <returns>null</returns>
function ExecuteZoomCheck()
{
    //first, check zoom level is OK
    if(IsAreaAppropriate(GetAreaOfBounds(gmap.getBounds())) == false)
    {
        //Report to user that zoom level is inappropriate - zoom in
        MapAlert(_zoomMessage);
        ExtentToolStatus(false); // Disable extent tool
    }
    else
    {
        //Zoom level is OK
        //Cancel any other message telling the user to zoom in (for when they zoom quickly)
        CancelMapAlert();
        ExtentToolStatus(true); // Enable extent tool
    }
}


/// <summary>
/// Accepts a polygon and returns the area in Square KM
/// </summary>
/// <returns>area in square km
function GetSquareKm(polygon)
{
    var area = polygon.getArea();
//    var sqkm = Math.floor(area / 1000000 + 0.999999);
    var sqkm = Math.floor(area / 1000000 + 0.5);
    return sqkm;
}

/// <summary>
/// Accepts a Polyline and returns the length in KM
/// </summary>
/// <returns>area in km
function GetKmLength(polyline)
{
    var length = polyline.getLength();
//    var km = Math.floor(length / 1000 + 0.999);
    var km = Math.floor(length / 1000 + 0.5);
    return km;
}

/// <summary>
/// Gets area (in square kilometers) of viewport region.
/// </summary>
/// <returns>area of viewport in square kilometers</returns>
function GetAreaOfBounds(bounds)
{
    var sw = bounds.getSouthWest();
    var ne = bounds.getNorthEast();
    var polyArray = new Array();
    polyArray.push(new GLatLng(ne.y, sw.x));
    polyArray.push(new GLatLng(ne.y, ne.x));
    polyArray.push(new GLatLng(sw.y, ne.x));
    polyArray.push(new GLatLng(sw.y, sw.x));
    polyArray.push(new GLatLng(ne.y, sw.x));
    var polygon = new GPolygon(polyArray);
    return GetSquareKm(polygon);
}

/// <summary>
/// Determines whether user's current extent is appropriate for executing a catalog search
/// Zoom Threshold
/// </summary>
/// <returns>true if current map viewport is less than 50000 sq km</returns>
function IsAreaAppropriate(area)
{
    if(area >= _zoomThreshold || area == 0) //When zoomed very far out, area = 0.
    {
        return false;   
    }
    else
    {
        return true;
    }
}

/// <summary>
/// Determines whether length of polyine is appropriate to search catalog
/// </summary>
/// <params value="length">The length given by GPolyline.getLength() (in meters)</params>
/// <returns>true if polyline is less than polyLength threshold</returns>
function IsLengthAppropriate(length)
{
    if(length >= _PolylineLengthThreshold)
    {
        return false;
    }
    else
    {
        return true;
    }
}

//Allows user to type in search, and hit 'enter' to search.
function doClick(buttonName,e)
    {
//the purpose of this function is to allow the enter key to 
//point to the correct button to click.
        var key;

         if(window.event)
         {
              key = window.event.keyCode;     //IE
         }
         else
         {
              key = e.which;     //firefox
         }
    
        if (key == 13)
        {
            //Get the button the user wants to have clicked
            var btn = $(buttonName);
            if (btn != null)
            { //If we find the button click it
                btn.click();
                event.keyCode = 0
            }
        }
   }


function FormatDate(dayNumber, monthNumber, yearNumber)
{
    return yearNumber + "/" + monthNumber + "/" + dayNumber;    
}

///Convert from DD-MMM-YYYY (15-DEC-2004) to mm/dd/yyyy (12/15/2004)
function ConvertDisplayDateToQueryFormat(dateString)
{
   var dateArr = dateString.split('-');
   return (_monthArray.indexOf(dateArr[1]) + 1) + "/" + dateArr[0] + "/" + dateArr[2];
}

function GetCloudDescriptionFromValue(cloudPercent)
{
    if(cloudPercent >=0 && cloudPercent <= 20)
    {
        return "Sunny";
    }
    else if(cloudPercent > 20 && cloudPercent <=50)
    {
        return "Partly Cloudy";
    }
    else if(cloudPercent > 50 && cloudPercent <=100)
    {
        return "Cloudy";
    }
    
    return "Unknown"; //Default
}

//Any map click comes through here.
function HandleMapClick(overlay, latlng)
{
   //Highlight footprint & corresponding result row if clicked.
   if(overlay)
     {
         //If color is = normal color, highlight footprint.
         if(overlay.color == _footprintFillColor) //If not selected
         {
            _searchResultsGrid.ClearHighlightedFootprints();
            overlay.setFillStyle(_searchResultsGrid.SelectedPolyFillStyle); 
            overlay.setStrokeStyle(_searchResultsGrid.SelectedPolyStrokeStyle);
            
            //Figure out which overlay in the resultsGrid collection equal to this overlay. 
            //Then highlight the row for this overlay.
            _searchResultsGrid.HighlightRowByOverlay(overlay);
         }
         
         var sr = _searchResultsGrid.GetSearchResultByOverlay(overlay); //Get reference to result object
         //Open window with correct text
         if(_searchResultsGrid.IsOverlayThumbVisible(overlay))
         {
              //thumb is on.  swap text
              if(sr != null)
              {
                _map.openInfoWindowHtml(sr.Overlay.getBounds().getCenter(), sr.InfoWindowContent.replace(_showHyperlinkText, _hideHyperlinkText)); //Hide thumb text
              }
              else {
                _map.openInfoWindowHtml(sr.Overlay.getBounds().getCenter(), sr.InfoWindowContent.replace(_hideHyperlinkText, _showHyperlinkText)); //Show thumb text
              }
         }
         //Since the window will always open for the clicked on footprint, set the result items' status appropriately
         if(sr != null)
         {
            _searchResultsGrid.ClearOpenInfoWindowStatus(); //set all other info window bools to false
            sr.IsInfoWindowOpen = true; //set this status to true, so we know this result's info window is open
         }
     
     //Set flag for placename search window.  Don't want to reopen it
     _placeNameSearchWindowVisible = false;
   }
}


// Download Modal
function DownloadPrefs() {
    document.getElementById('wrapper-downloadPrefs').style.display = "inline";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "inline";
}

function CloseDownloadPrefs() {
    document.getElementById('wrapper-downloadPrefs').style.display = "none";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "none";
}

// Help Modal
function OpenHelp() {
    document.getElementById('wrapper-help').style.display = "inline";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "inline";
}

function CloseHelp() {
    document.getElementById('wrapper-help').style.display = "none";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "none";
}

// Error
function OpenError() {
    document.getElementById('wrapper-error').style.display = "inline";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "inline";
}

function CloseError() {
    document.getElementById('wrapper-error').style.display = "none";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "none";
}
// PermaLink
function OpenPermaLink() {
    document.getElementById('wrapper-permaLink').style.display = "inline";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "inline";
}

function ClosePermaLink() {
    document.getElementById('wrapper-permaLink').style.display = "none";
    document.getElementById('wrapper-searchPrefs-bg').style.display = "none";
}


//Clear Map Overlays, Search Results, AOI geometry.
function ClearEverything()
{
  //gmap.clearOverlays();
// _searchResultsGrid.Clear();
 //Clear out the search geometry object.
// _searchGeometryObject.Clear();
// _foot.ClearFeatureTable(); 
 //Disable 'Clear' Button.
 
 // Clear Permalink 
 // document.getElementById('uxPermaLink').value = "Please execute a search on the Image Catalog.";
}

//Clear Map Overlays and Search Grid.
function ClearMapAndResults()
{
  //gmap.clearOverlays();
 _searchResultsGrid.Clear();
}


function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

