﻿/*
utilites.js handles the logic for sizing of the mapping application
*/

/// <summary>
/// Add's the GeoFUSE Logo to the map
/// </summary>
/// <returns></returns>
function addGeoFUSELogo() {
    try {
        if (_map == null) {
            return;
        }
        else if (_map.isLoaded()) {
        /* Add GeoFUSE Logo to the Map */

            var offsetTop = 0;
            var findElem = $("wrapper-find");
            var searchElem = $("wrapper-search");
            var mapElem = $("wrapper-map");
            var topElem = $("wrapper-top");
            var leftElem = $("wrapper-left");
            var bottomElem = $("wrapper-footer");
            var findElem = $("wrapper-find");
            var width = null;
            for (var elem = mapElem; elem; elem = elem.offsetParent) {
                offsetTop += elem.offsetTop;
            }
            var height = getWindowHeight() - offsetTop - 35;
            if (mapElem.style.left == "6px") {
                width = getWindowWidth() - 6;
            }
            else {
                width = getWindowWidth() - 317;
            }
            var map_height = height;
            
            // remove logo from map if exists already
            if (_geofuseLogoScreenOverlay != null)
                _geofuseLogoScreenOverlay.hide();

            // add logo to map by creating a screen overlay
            _geofuseLogoScreenOverlay = new GScreenOverlay("http://geofuse.geoeye.com/maps/images/geofuse_logo_maps.png",
                                                          new GScreenPoint(0, 15),
                                                          new GScreenPoint((width * -1) + 5, 0),
                                                          new GScreenSize(0, 0));
            _map.addOverlay(_geofuseLogoScreenOverlay);
            
            return 1;
        }
    }
    catch (e) {
        return;
    }

    return 0;
}


/// <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;
}

function ChangePreferenceResolutionTabe(tabObject) {
    // set all tabs to hidden
    $("uxPreferencesResolutionChoice_All").style.visibility = "hidden";
    $("uxPreferencesResolutionChoice_All").style.display = "none";
    $("uxPreferencesResolutionChoice_Half").style.visibility = "hidden";
    $("uxPreferencesResolutionChoice_Half").style.display = "none";
    $("uxPreferencesResolutionChoice_One").style.visibility = "hidden";
    $("uxPreferencesResolutionChoice_One").style.display = "none";

    $("uxdivSourceAll").style.color = "";
    $("uxdivSourceGE1").style.color = "";
    $("uxdivSourceIK2").style.color = "";
    $("uxdivSourceOV3").style.color = "";

    $("uxSourceAll").disabled = "";
    $("uxSourceGE1").disabled = "disabled";
    $("uxSourceIK2").disabled = "disabled";
    $("uxSourceOV3").disabled = "disabled";

    if (tabObject == "uxPreferencesResolutionChoice_One") {
        $("uxPreferencesResolutionChoice_One").style.visibility = "";
        $("uxPreferencesResolutionChoice_One").style.display = "";
        $("uxSourceAll").disabled = "";
        $("uxSourceAll").checked = "checked";
        $("uxSourceGE1").disabled = "";
        $("uxSourceIK2").disabled = "";
        $("uxSourceOV3").disabled = "";
        $("uxdivSourceAll").style.color = "";
        $("uxdivSourceGE1").style.color = "";
        $("uxdivSourceIK2").style.color = "";
        $("uxdivSourceOV3").style.color = "";
    }
    else if (tabObject == "uxPreferencesResolutionChoice_Half") {
        $("uxPreferencesResolutionChoice_Half").style.visibility = "";
        $("uxPreferencesResolutionChoice_Half").style.display = "";
        $("uxSourceAll").disabled = "disabled";
        $("uxSourceGE1").disabled = "";
        $("uxSourceGE1").checked = "checked";
        $("uxSourceIK2").disabled = "disabled";
        $("uxSourceOV3").disabled = "disabled";
        $("uxdivSourceAll").style.color = "#e8e8e8";
        $("uxdivSourceGE1").style.color = "";
        $("uxdivSourceIK2").style.color = "#e8e8e8";
        $("uxdivSourceOV3").style.color = "#e8e8e8";
    }
    else {
        $("uxPreferencesResolutionChoice_All").style.visibility = "";
        $("uxPreferencesResolutionChoice_All").style.display = "";
        $("uxSourceAll").disabled = "";
        $("uxSourceAll").checked = "checked";
        $("uxSourceGE1").disabled = "disabled";
        $("uxSourceIK2").disabled = "disabled";
        $("uxSourceOV3").disabled = "disabled";
        $("uxdivSourceAll").style.color = "";
        $("uxdivSourceGE1").style.color = "#e8e8e8";
        $("uxdivSourceIK2").style.color = "#e8e8e8";
        $("uxdivSourceOV3").style.color = "#e8e8e8";
    }
}


/// <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>
/// Automatically resizes the application when client browser is resized
/// </summary>
/// <returns>null</returns>
function ResizeApp() {
    try {
        if (_map == null) {
            return;
        }
        
        var offsetTop = 0;
        var findElem = $("wrapper-find");
        var searchElem = $("wrapper-search");
        var mapElem = $("wrapper-map");
        var topElem = $("wrapper-top");
        var leftElem = $("wrapper-left");
        var bottomElem = $("wrapper-footer");
        var findElem = $("wrapper-find");
        var width = null;
        for (var elem = mapElem; elem; elem = elem.offsetParent) {
            offsetTop += elem.offsetTop;
        }
        var height = getWindowHeight() - offsetTop - 35;
        if (mapElem.style.left == "6px") {
            width = getWindowWidth() - 6;
        }
        else {
            width = getWindowWidth() - 317;
        }
        var map_height = height;
        if (height >= 0) {
            //make sure width is >= 0
            if (width < 0) {
                width = 0;
            }
            mapElem.style.height = map_height + "px";
            mapElem.style.width = width + "px";
            topElem.style.width = getWindowWidth() - 0 + "px";
            bottomElem.style.width = getWindowWidth() - 30 + "px";
            leftElem.style.height = map_height + "px";
            findElem.style.height = map_height - 56 + "px";
            searchElem.style.height = map_height - 56 + "px";
            $("wrapper-gridResults").style.height = height - 175 + "px";    // set height of results grid div for scrolling.

            //findElem.style.height = map_height - 70 + "px";
            //e("wpanel").style.height =e("panel").style.height = (height + 4) + "px";
            //e("paneltoggle").style.paddingTop = (height/2) + "px";
            //e("paneltoggle").style.paddingBottom = (height/2) + "px";
            //var sp = e("spsizer");
            //sp.style.height = Math.max(0, height - sp.offsetTop) + "px";
        }
        _map.checkResize();

        /* Add GeoFUSE Logo to the Map */
        addGeoFUSELogo();
        
        // remove logo from map if exists already
//        if (_geofuseLogoScreenOverlay != null)
//            _geofuseLogoScreenOverlay.hide();

//        // add logo to map by creating a screen overlay
//        _geofuseLogoScreenOverlay = new GScreenOverlay("http://geofuse.geoeye.com/maps/images/geofuse_logo_maps.png",
//                                                      new GScreenPoint(0, 15),
//                                                      new GScreenPoint((width * -1) + 5, 0),
//                                                      new GScreenSize(0, 0));
//        _map.addOverlay(_geofuseLogoScreenOverlay);    
    }
    catch (e) {
    }
}


/// <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(_map.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.round(area / 1000000) / 1;
    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.round(length / 1000);
    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;
    }
}

function UpdateMousePosition(point) {   //Pass to footer object.
    _foot.SetMousePosition(point);
}

//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 dayNumber + "-" + _monthArray[monthNumber] + "-" + yearNumber;
}

///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() {
    _map.clearOverlays();

    // add GeoFUSE Logo to Map
    addGeoFUSELogo();
    
    _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() {
    _map.clearOverlays();
    
    // add GeoFUSE Logo to Map
    addGeoFUSELogo();
    
    _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;
}
