﻿/*
searchresults.js controls the display and events of the catalog search results grid.
*/

var _overlayArray = new Array();
var _searchResultsRowSelectedColor = "#B1D766";
var _searchResultsDefaultColor = "#ffffff";
var _resultClearedMessage, _noFeaturesMessage = null;

function SearchResultsGrid(featureCount)
{
     //Apply names and titles to the find panel buttons
    $("uxHelpBtn").alt = _searchHelpToolTip;
    $("uxHelpBtn").title = _searchHelpToolTip;
    $("uxHelpBtn").style.cursor = "pointer";
    $("uxClearBtn").alt = _searchClearToolTip;
    $("uxClearBtn").title = _searchClearToolTip;
    $("uxClearBtn").style.cursor = "not-allowed";
    $("uxDownload1").alt = _searchDataDownloadToolTip;
    $("uxDownload1").title = _searchDataDownloadToolTip;
    $("uxDownload1").style.cursor = "not-allowed";
    $("uxSearchPreferencesBtn").alt = _searchPreferencesToolTip;
    $("uxSearchPreferencesBtn").title = _searchPreferencesToolTip;
    $("uxSearchPreferencesBtn").style.cursor = "pointer";
    $("uxPermalinkBtn").alt = _searchPermalinkToolTip
    $("uxPermalinkBtn").title = _searchPermalinkToolTip
    $("uxPermalinkBtn").style.cursor = "pointer";
    
    //Apply names and titles to the results panel buttons
    /*$("uxHelpBtn2").alt = _searchHelpToolTip;
    $("uxHelpBtn2").title = _searchHelpToolTip;
    $("uxHelpBtn2").style.cursor = "pointer";
    $("uxClearBtn2").alt = _searchClearToolTip;
    $("uxClearBtn2").title = _searchClearToolTip;
    $("uxClearBtn2").style.cursor = "not-allowed";
    $("uxDownload2").alt = _searchDataDownloadToolTip;
    $("uxDownload2").title = _searchDataDownloadToolTip;
    $("uxDownload2").style.cursor = "not-allowed";*/
    $("uxSearchPreferencesBtn2").alt = _searchPreferencesToolTip;
    $("uxSearchPreferencesBtn2").title = _searchPreferencesToolTip;
    $("uxSearchPreferencesBtn2").style.cursor = "pointer";
    $("uxPermalinkBtn2").alt = _searchPermalinkToolTip
    $("uxPermalinkBtn2").title = _searchPermalinkToolTip
    $("uxPermalinkBtn2").style.cursor = "pointer";
     
     //Take the JSON feature set and pull out the attributes for display in the grid.
     this.resTable = GetTable(); //Get Table reference.
     this.featureCount = featureCount; //feature count
     this.pageStart = geoeye.webmaps.PageInfo.start;
     this.pageSize = geoeye.webmaps.PageInfo.size;
     this.pageEnd = Math.min(featureCount, this.pageStart + this.pageSize - 1); 
     this.currentPage = 1; //Keep track of what page we're on.
     this.rowCounter = 0; //keeps tabs on how many rows there are.
     this.Rows = new Array(); //A collection of row objects.
     this.SearchResultItem = new Array();
     this.DownloadButton = $("uxDownload");
     this.SelectedPolyStrokeStyle = {
        color:_footprintSelectedOutlineColor,
        weight:_footprintSelectedOutlineWeight,
        opacity:_footprintSelectedOutlineOpacity
        };
     this.SelectedPolyFillStyle = {
        color:_footprintSelectedFillColor,
        opacity:_footprintSelectedFillOpacity
        };
        
     this.NormalPolyStrokeStyle = {
        color:_footprintOutlineColor,
        weight:_footprintOutlineWeight,
        opacity:_footprintOutlineOpacity
        };
    
    this.NormalPolyFillStyle = {
        color:_footprintFillColor,
        opacity:_footprintFillOpacity
        };
  
     
     this.InsertHeaderRow = function()
     {
        var toggleControlsDiv = document.getElementById("toggleControls");
        toggleControlsDiv.innerHTML = "<input id=\"uxFootprintToggle_all\" type=\"image\" onclick=\"ToggleFootprints()\" alt=\"Toggle Footprint\" src=\"images/icon-footprint-on.png\"/>";
        toggleControlsDiv.innerHTML += "&nbsp;<label id=\"lblFootprintToggle_all\" style=\"cursor:pointer; position: relative; bottom: 0.2em\" onclick=\"ToggleFootprints()\" valign=\"middle\">" + _hideFootprintsLabel + "</label>";
        toggleControlsDiv.innerHTML += "&nbsp;&nbsp;<input id=\"uxThumbnailToggle_all\" type=\"image\" onclick=\"ToggleThumbnails()\" alt=\"Toggle Thumbnails\" src=\"images/icon-image-off.png\"/>";
        toggleControlsDiv.innerHTML += "&nbsp;<label id=\"lblThumbnailToggle_all\" style=\"cursor:pointer; position: relative; bottom: 0.2em\" onclick=\"ToggleThumbnails()\" valign=\"middle\">" + _showThumbnailsLabel + "</label>";
        //Write Header
        var resHead = this.resTable.insertRow(-1);
        var cellOne = resHead.insertCell(0);
        cellOne.innerHTML="<span class=\"searchResultHeader\">" + _viewSRColumn + "</span>";
        var cellTwo = resHead.insertCell(1);
        cellTwo.innerHTML="<span class=\"searchResultHeader\">" + _autoNumberSRColumn + "</span>";
        var cellThree = resHead.insertCell(2);
        cellThree.innerHTML="<span class=\"searchResultHeader\">" + _vehicleAbbrevSRColumn + "</span>";
        var cellFour = resHead.insertCell(3);
        cellFour.innerHTML="<span class=\"searchResultHeader\">" + _cloudCoverSRColumn + "</span>";
        var cellFive = resHead.insertCell(4);
        cellFive.innerHTML="<span class=\"searchResultHeader\">" + _collectedSRColumn + "</span>";
        var cellSix = resHead.insertCell(5);
        cellSix.innerHTML="<span class=\"searchResultHeader\">Details&nbsp&nbsp</span>";
     }
     
    this.Clear = function()
    {
        //Clear Toggle Buttons
        var toggleControlsDiv = document.getElementById("toggleControls");
        toggleControlsDiv.innerHTML = "";
        $('uxPermaLink').value = "Please execute a search on the Image Catalog.";
        //Clear grid
        try
        {
            while(this.resTable.rows.length>0)
            {
                this.resTable.deleteRow(0);
            }
            
            this.DisplaySearchResultsHeader(_resultClearedMessage);
            this.SearchResultItem.length = 0;
            this.DisableDownloadButton();
            this.DisableClearButton();
            this.HidePagingControls();
        }
        catch(e)
        {
            ErrorAlert(SearchResultsGridError);
        }
    } 
    
    this.ClearSearchResultRows = function()
    {
        try
        {
            //clear row objects, but keep headers
            while(this.resTable.rows.length>0)
            {
                   this.resTable.deleteRow(0);
            }
            this.SearchResultItem.length = 0;
            this.Rows.length = 0;
        }
        catch (e)
        {
            ErrorAlert(SearchResultsGridError);
        } 
    }
    
    this.InsertSearchResultRow = function (searchResultObject)
    {
       try
       {
            var resRow = this.resTable.insertRow(-1);
            var displayCell = resRow.insertCell(0);
            displayCell.innerHTML=GetDisplayButtons(searchResultObject.CurrentPageCount);
            var countCell = resRow.insertCell(1);
            countCell.innerHTML = searchResultObject.DisplayCount + 1; //0 based index is not user-friendly
            var satCell = resRow.insertCell(2);
            satCell.innerHTML = searchResultObject.Spacecraft;
            var cloudCell = resRow.insertCell(3);
            cloudCell.innerHTML = searchResultObject.CloudCoverPercent + "%";
            var acqCell = resRow.insertCell(4);
            acqCell.innerHTML = searchResultObject.CollectionDate();
            var detailsCell = resRow.insertCell(5);
            detailsCell.innerHTML = searchResultObject.ViewHyperlink;
            this.Rows.push(resRow); //Add Html Row to array.
            this.SearchResultItem.push(searchResultObject); //Add result object to array
        }
        catch(e)
        {
            ErrorAlert(SearchResultsGridError);
        }
    }
    
    this.ClearHighlightRows = function()
    {
        for(var hrc=0; hrc<this.Rows.length;hrc++)
        {
            this.Rows[hrc].bgColor = _searchResultsDefaultColor; 
        } 
    }
    
    this.HighlightRow = function(rowNumber)
    {
       this.ClearHighlightRows();
       this.Rows[rowNumber].bgColor = _searchResultsRowSelectedColor;
    }
    
    //Sets all result rows' info window status to false
    this.ClearOpenInfoWindowStatus = function()
    {
       for(var hrc=0; hrc<this.SearchResultItem.length;hrc++)
       {
            this.SearchResultItem[hrc].IsInfoWindowOpen = false;  
       }
    }
    
    this.ClearHighlightedFootprints = function()
    {
       for(var hrc=0; hrc<this.SearchResultItem.length;hrc++)
       {
            this.SearchResultItem[hrc].Overlay.setFillStyle(this.NormalPolyFillStyle); 
            this.SearchResultItem[hrc].Overlay.setStrokeStyle(this.NormalPolyStrokeStyle); 
       }
    }
    
    this.HighlightFootprint = function(rowNumber)
    {
        try {
           this.ClearHighlightedFootprints();
           this.SearchResultItem[rowNumber].Overlay.setFillStyle(this.SelectedPolyFillStyle); 
           this.SearchResultItem[rowNumber].Overlay.setStrokeStyle(this.SelectedPolyStrokeStyle);
        } catch(e)
        {
            ErrorAlert(SearchResultsGridError);
        }
    }
    
    //Pass in clicked-on feature.  Use unique ID to match to one of the search results.
    this.HighlightRowByOverlay = function(overlay)
    {
       try
       { 
           for(var hrc=0; hrc<this.SearchResultItem.length;hrc++)
           {
                if(this.SearchResultItem[hrc].Overlay == overlay)
                {
                    this.HighlightRow(hrc);
                }
           }
       }
       catch (e)
       {
           ErrorAlert(SearchResultsGridError);
       }
    }
    
    //Pass in clicked-on feature.  Use unique ID to match to one of the search results.
    this.GetSearchResultByOverlay = function(overlay)
    {
       try
       {
           for(var hrc=0; hrc<this.SearchResultItem.length;hrc++)
           {
                if(this.SearchResultItem[hrc].Overlay == overlay)
                {
                    return this.SearchResultItem[hrc];
                }
           }
       }
       catch (e)
       {
           ErrorAlert(SearchResultsGridError);
       }
       //default return null
       return null;
    }
    
    //Pass in clicked-on feature.  Determine if the thumbnail is visible for the given geometry.
    this.IsOverlayThumbVisible = function(overlay)
    {
       for(var hrc=0; hrc<this.SearchResultItem.length;hrc++)
       {
            if(this.SearchResultItem[hrc].Overlay == overlay)
            {
                if(this.SearchResultItem[hrc].ThumbnailVisible == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
       }
       //default return false;
       return false;
    }
    
    
    this.DisplaySearchResultsHeader = function (content)
    {
        //Default - show search result counts.
        if(content == null || content == undefined)
        {
            if (this.featureCount < _maxReturnedFootprintCount) {
                content = "There are <b>" + this.featureCount + "</b> image matches on the map.<br />" +
                    "Showing matches " + this.pageStart + " through " + this.pageEnd + ".";                    
            }
            else {
                content = "There are <b>" + this.featureCount + " (or more) </b> image matches<br/>on the map. " +
                    "Showing matches " + this.pageStart + " through " + this.pageEnd + ".";
                MapAlert("Your results set may have been truncated. " +
                    "The map will display matches " +
                    this.pageStart +
                    " through " +
                    this.pageEnd +
                    " out of a max " +
                    this.featureCount +
                    " footprints.");
            }
        // Code to toggle all footprints on/off
//        "<a href=\"#\" onclick=\"TurnOffAllFootprints();\">HIDE ALL</a> &bull; <a href=\"#\" onclick=\"TurnOnAllFootprints();\">SHOW ALL</a>";
        }
        
        $("uxResultsDisplay").innerHTML = content;
    }
    
    this.ShowPagingControls = function()
    {
        $("uxPaging").style.display='inline';
    }
    
    this.HidePagingControls = function()
    {
        $("uxPaging").style.display='none';
    }
    
    this.EnableNextPage = function()
    {
            $("uxNext").src = "images/button-results-next.gif";
            $("uxNext").style.cursor = "pointer";
            $("uxNext").alt = "Next Page";
    }
    
    this.DisableNextPage = function()
    {
            $("uxNext").src = "images/button-results-next-disabled.gif";
            $("uxNext").style.cursor = "arrow";
            $("uxNext").alt = ""; 
    }
    
    this.EnablePreviousPage = function()
    {
            $("uxPrevious").src = "images/button-results-prev.gif";
            $("uxPrevious").style.cursor = "pointer";
            $("uxPrevious").alt = "Previous Page";
    }
    
    this.DisablePreviousPage = function()
    {
            $("uxPrevious").src = "images/button-results-prev-disabled.gif";
            $("uxPrevious").style.cursor = "arrow";
            $("uxPrevious").alt = "";
    }
    
    this.EnableDownloadButton = function()
    {
        $("uxDownloadCell1").innerHTML = '<img id="uxDownload1" style="cursor:pointer" alt="'+_searchDataDownloadToolTip+'" title="'+_searchDataDownloadToolTip+'" src="images/button-global-download.png" onclick="DownloadPrefs();" />';
        $("uxDownloadCell2").innerHTML = '<img id="uxDownload2" style="cursor:pointer" alt="'+_searchDataDownloadToolTip+'" title="'+_searchDataDownloadToolTip+'" src="images/button-global-download.png" onclick="DownloadPrefs();" />';
    }
    
    this.DisableDownloadButton = function()
    {
        $("uxDownloadCell1").innerHTML = '<img id="uxDownload1" style="cursor:not-allowed" alt="'+_searchDataDownloadToolTip+'" title="'+_searchDataDownloadToolTip+'" src="images/button-global-download-disabled.png"/>';
        $("uxDownloadCell2").innerHTML = '<img id="uxDownload2" style="cursor:not-allowed" alt="'+_searchDataDownloadToolTip+'"  title="'+_searchDataDownloadToolTip+'" src="images/button-global-download-disabled.png"/>';
    }
    
    this.EnableClearButton = function()
    {
        $("uxClearCell2").innerHTML = '<img alt="'+_searchClearToolTip+'"  title="'+_searchClearToolTip+'"  style="cursor:pointer" src="images/button-global-clear.png" onclick="ClearEverything()"/>';
    }
    
    this.DisableClearButton = function()
    {
        $("uxClearCell2").innerHTML = '<img alt="'+_searchClearToolTip+'" title="'+_searchClearToolTip+'" style="cursor:not-allowed" src="images/button-global-clear-disabled.png" onclick=""/>';
    }
    
    this.HandleNextPageClick = function()
    {
        try
        {
            //Don't search if we're on last page.  We've handled the styling in the 'process search results' method, now we handle functionality 
            if(this.pageEnd != this.featureCount)
            {
                geoeye.webmaps.PageInfo.start = geoeye.webmaps.PageInfo.start + geoeye.webmaps.PageInfo.size;
                _qtask.execute(_query, false, ProcessSearchResults);
                _searchResultsGrid.currentPage++;
            }
        }
        catch (e)
        {
           ErrorAlert(SearchResultsGridError);
        }
    }
    
    this.HandlePreviousPageClick = function()
    {
        try
        {
            //Don't search if we're on page 1.  We've handled the styling in the 'process search results' method, now we handle functionality 
            if(_searchResultsGrid.currentPage != 1)
            {
                _searchResultsGrid.ClearSearchResultRows(); // Fixed the multiple records come back problem.  Not quite sure if this is messing things up though.
                geoeye.webmaps.PageInfo.start = geoeye.webmaps.PageInfo.start - geoeye.webmaps.PageInfo.size;
                _qtask.execute(_query, false, ProcessSearchResults);
                _searchResultsGrid.currentPage--;
                
            }
        }
        catch (e)
        {
           ErrorAlert(SearchResultsGridError);
        }
    }
     


     //Clear, then repopulate  *****UNCOMMENT THE LINE BELOW TO GET BACK TO ORIGINAL
     //this.Clear();
     
     //Handle 0 features
     if(this.featureCount > 0)
     {
         this.InsertHeaderRow();
         this.DisplaySearchResultsHeader();
         this.EnableDownloadButton();
         this.EnableClearButton();
         if(this.featureCount > this.pageSize)
         {
            //There are more features, enable paging
            this.ShowPagingControls();
            this.EnableNextPage();
            this.DisablePreviousPage(); //Default state is disabled
         }
         else
         {
            //There are less features than page size, disable paging.
            this.DisableNextPage();
            this.DisablePreviousPage();
         }
     }
     else
     {
         this.DisplaySearchResultsHeader(_noFeaturesMessage);
         this.DisableDownloadButton();
     }
}





//An object to hold one search result
function SearchResultItem(id,overlay,infoWindowContent,thumbURL, displayCount, currentPageCount, spacecraft, collectionDate, cloudDescription, cloudCoverPercent, viewHyperlink)
{
    this.ID = id; //Image ID
    this.Overlay = overlay; //The overlay object.
    this.InfoWindowContent = infoWindowContent; //what goes in the info window?
    this.IsInfoWindowOpen = false; //Bool - is the info window open for this feature?
    this.ThumbnailOverlay = null; //Load with thumbnail once loaded.
    this.ThumbURL = thumbURL; //Path to the URL
    this.DisplayCount = displayCount; //The number of the record 1 - n
    this.CurrentPageCount = currentPageCount; //The auto-number of the record, 1 - 20
    this.Spacecraft = spacecraft; //name of vehicle
    this.FootprintVisible = true; //Bool - is Footprint Visible?
    this.ThumbnailVisible = false; //Bool - is thumbnail visible?
    this.CollectionDate = function () //Get the correctly formatted date
    {
            var aDate = new Date(collectionDate);
            return FormatDate(aDate.getDate(), aDate.getMonth(), aDate.getFullYear());    
    }
    this.CloudDescription = cloudDescription; //Wording of cloudiness
    this.CloudCoverPercent = cloudCoverPercent; //Percent cloudy
    this.ViewHyperlink = viewHyperlink; //View Details hyperlink string
    
    this.LL_LAT = this.Overlay.getBounds().getSouthWest().lat(); //Coords
    this.LL_LON = this.Overlay.getBounds().getSouthWest().lng();
    this.UR_LAT = this.Overlay.getBounds().getNorthEast().lat();
    this.UR_LON = this.Overlay.getBounds().getNorthEast().lng();
}



///Helper Functions
function GetTable()
{
    return $("uxSearchResults");
}


function GetDisplayButtons(id)
{
    var rString = "<input id=\"uxFootprintToggle_" + id + "\" type='image' src='images/icon-footprint-on.png' alt='Toggle Footprint' onclick='ToggleFootprint(" + id + ")' />";
    rString += "&nbsp;<input id=\"uxThumbnailToggle_" + id + "\" type='image' src='images/icon-image-off.png' alt='Toggle Image' onclick='ToggleThumbnail(" + id + ")' />";
    return rString;
}



/// <summary>
/// Handles ESRI GMaps REST Query Result.  Adds features to map.  Controls styling and 'bubble' content.
/// <param name="featureSet">A JSON object returned from ArcGIS REST query</param>
/// </summary>
/// <returns>null</returns>
function ProcessSearchResults(fset, error) 
{
    //Hack to avoid multiple searches when polygons vertices are updated.
    _polygonUpdateCount = 0;
    select("mapPan"); //now that we've completed the search, re-enable the mapPan tool.
    
    if (error != null) {
        alert(error.code);
    }
    
    try 
    {
        if(fset)
        {
        
            //JS literal class esri.arcgis.gmaps.OverlayOptions
            var overlayOptions = 
            {
              strokeColor:_footprintOutlineColor,
              strokeWeight:_footprintOutlineWeight,
              strokeOpacity:_footprintOutlineOpacity,
              fillColor:_footprintFillColor,
              fillOpacity:_footprintFillOpacity
            };  
           
            
            //Handle Search Results Grid
            if(geoeye.webmaps.PageInfo.start > geoeye.webmaps.PageInfo.size)
            {
                //we are paging ahead
                //update the SearchResultGrid object with page info
                _searchResultsGrid.pageStart = geoeye.webmaps.PageInfo.start;
                _searchResultsGrid.pageSize = geoeye.webmaps.PageInfo.size;
                _searchResultsGrid.pageEnd = Math.min(geoeye.webmaps.PageInfo.totalSize, _searchResultsGrid.pageStart + _searchResultsGrid.pageSize - 1); 
                //Clear old rows out of result grid.
                _searchResultsGrid.ClearSearchResultRows();
                _searchResultsGrid.DisplaySearchResultsHeader(); //refresh display count
                _searchResultsGrid.InsertHeaderRow(); //Insert Column Header
                _map.clearOverlays();
                if(_searchResultsGrid.pageEnd == _searchResultsGrid.featureCount)
                {
                    //We're on the last page.  Disable the 'next' button
                    _searchResultsGrid.DisableNextPage();
                }
                else
                {
                    //Enable Next Button
                    _searchResultsGrid.EnableNextPage();
                }
                //Enable Previous Button
                
                _searchResultsGrid.EnablePreviousPage();
            }
            else
            {
                //otherwise, this is page 1
                _searchResultsGrid = new SearchResultsGrid(geoeye.webmaps.PageInfo.totalSize);
                _searchResultsGrid.currentPage = 1;
                _map.clearOverlays();
            }
            

            //Need to break apart featureset and add features one at a time.  This will allow us to remove them one by one later.
            var sr; //Holds the Search Result Object inside the loop.
            for(var rCnt=0; rCnt<fset.features.length; rCnt++)
            {
                var displayCount = (_searchResultsGrid.pageStart + rCnt - 1); //Overall count of footprints
                var bubbleContent = BuildFootprintContent(rCnt, displayCount, fset.features[rCnt]); //Get the info window content HTML
                var infoWindowOptions = infoWindowOptions = {content:bubbleContent};
                var ol = _mapExtension.addToMap(fset.features[rCnt], overlayOptions, infoWindowOptions);
                
                //Add each feature to the overall Feature Array, and to map.
                sr = new SearchResultItem(fset.features[rCnt].attributes[_imageNameColumn],
                                                                  ol[0][0],
                                                                  bubbleContent,
                                                                  fset.features[rCnt].attributes[_imageURL],
                                                                  displayCount,
                                                                  rCnt,
                                                                  fset.features[rCnt].attributes[_spacecraftColumn],
                                                                  fset.features[rCnt].attributes[_dateColumn],
                                                                  GetCloudDescriptionFromValue(fset.features[rCnt].attributes[_cloudCoverColumn]),
                                                                  fset.features[rCnt].attributes[_cloudCoverColumn],
                                                                  BuildViewHyperlink(rCnt)
                                                                  );
                                                                  
                //Add the new searchResultItem to the Result Grid.
                _searchResultsGrid.InsertSearchResultRow(sr); 
            }
            
            //Remove the search AOI, then add it back in
            if(_searchGeometryObject.MapObject != null)
            {
                _map.removeOverlay(_searchGeometryObject.MapObject);
                //Re add the search marker so it'll be on top of the footprints.
                if(_searchGeometryObject.GeometryType == "envelope") // || _searchGeometryObject.GeometryType == "polygon"
                {
                    //Make the envelope fill transparent.
                    _searchGeometryObject.MapObject.setFillStyle({opacity:0});
                }
                _map.addOverlay(_searchGeometryObject.MapObject);
            }
            
        }
        else
        {
            //Inform the user, no results.
            _searchResultsGrid.DisplaySearchResultsHeader(_noFeaturesMessage);
        }
        //Turn OFF Freeze Div that disabled application interaction while searching
        var timer;
        var timing=60 //5 minutes in milliseconds...
        timer=setTimeout("$('wrapper-searchingCover').style.display = 'none'", timing);
    }
    catch (e)
    {
        ErrorAlert(ProcessingSearchResultsError);
    }
}


//Create the HTML hyperlink to view a row's info window.
function BuildViewHyperlink(id)
{
    return "<a href='javascript:ViewDetails(" + id + "), _searchResultsGrid.HighlightRow(" + id + ")'>" + _moreDetails + "</a>";
}

///////////////////GARY//////////////////////////
/// <summary>
/// Turns Off all Images.
/// </summary>
/// <returns>null</returns>
function TurnOffAllThumbnails() {

       var pageResults = _searchResultsGrid.pageEnd - _searchResultsGrid.pageStart;
       var i = 0;
       
//       for (i=0; i<=pageResults; i++) {
//           if(_searchResultsGrid.SearchResultItem[i].ThumbnailOverlay != null){
//                _map.removeOverlay(_searchResultsGrid.SearchResultItem[i].ThumbnailOverlay)
//           }
//       }
       
       for (i=0; i<=pageResults; i++) {
           var mkr = _searchResultsGrid.SearchResultItem[i].ThumbnailOverlay;
           $("uxThumbnailToggle_" + i).src = "images/icon-image-off.png";
           mkr.hide();
           _searchResultsGrid.SearchResultItem[i].ThumbnailVisible = false;
       }
}

/// <summary>
/// Turns On all Images.
/// </summary>
/// <returns>null</returns>
function TurnOnAllThumbnails() {

       var pageResults = _searchResultsGrid.pageEnd - _searchResultsGrid.pageStart;
       //add/remove footprints from the bottom up so the top thumbnail is the best(top) in the results list
       var i = pageResults;
       
       for (i=pageResults; i>=0; i--) {
           if(_searchResultsGrid.SearchResultItem[i].ThumbnailOverlay != null){
                var mkr = _searchResultsGrid.SearchResultItem[i].ThumbnailOverlay;
                mkr.hide();
                _searchResultsGrid.SearchResultItem[i].ThumbnailVisible = false;
                _map.removeOverlay(_searchResultsGrid.SearchResultItem[i].ThumbnailOverlay)
                _searchResultsGrid.SearchResultItem[i].ThumbnailOverlay = null;
           }
       }
       
       
       for (i=pageResults; i>=0; i--) {
           LoadThumbnail(i)
           var mkr = _searchResultsGrid.SearchResultItem[i].ThumbnailOverlay;
           $("uxThumbnailToggle_" + i).src = "images/icon-image-on.png";
           mkr.show();
           _searchResultsGrid.SearchResultItem[i].ThumbnailVisible = true;
       }
}

function ToggleFootprints() {
    var toggleControl = document.getElementById("uxFootprintToggle_all");
    var toggleLabel = document.getElementById("lblFootprintToggle_all");
    if(toggleControl.src.slice(-7) == "off.png"){
        TurnOnAllFootprints();
        toggleControl.src = "images/icon-footprint-on.png";
        toggleLabel.innerHTML = _hideFootprintsLabel;
    }else{
        TurnOffAllFootprints();
        toggleControl.src = "images/icon-footprint-off.png";
        toggleLabel.innerHTML = _showFootprintsLabel;
    }
}

function ToggleThumbnails() {
    var toggleControl = document.getElementById("uxThumbnailToggle_all");
    var toggleLabel = document.getElementById("lblThumbnailToggle_all");
    if(toggleControl.src.slice(-7) == "off.png"){
        TurnOnAllThumbnails();
        toggleControl.src = "images/icon-image-on.png";
        toggleLabel.innerHTML = _hideThumbnailsLabel;
    }else{
        TurnOffAllThumbnails();
        toggleControl.src = "images/icon-image-off.png";
        toggleLabel.innerHTML = _showThumbnailsLabel;
    }
}
///////////////////GARY//////////////////////////


/// <summary>
/// Turns Off all Footprints.
/// </summary>
/// <returns>null</returns>
function TurnOffAllFootprints() {

       var pageResults = _searchResultsGrid.pageEnd - _searchResultsGrid.pageStart;
       var i = 0;
       for (i=0; i<=pageResults; i++) {
           var mkr = _searchResultsGrid.SearchResultItem[i].Overlay;
           $("uxFootprintToggle_" + i).src = "images/icon-footprint-off.png";
           mkr.hide();
           _searchResultsGrid.SearchResultItem[i].FootprintVisible = false;
       }
}

/// <summary>
/// Turns Off all Footprints.
/// </summary>
/// <returns>null</returns>
function TurnOnAllFootprints() {

       var pageResults = _searchResultsGrid.pageEnd - _searchResultsGrid.pageStart;
       var i = 0;
       for (i=0; i<=pageResults; i++) {
           var mkr = _searchResultsGrid.SearchResultItem[i].Overlay;
           $("uxFootprintToggle_" + i).src = "images/icon-footprint-on.png";
           mkr.show();
           _searchResultsGrid.SearchResultItem[i].FootprintVisible = true;
       }
}

/// <summary>
/// Toggles the visibility of a given footprint.
/// </summary>
/// <params name="id">auto number of row</params>
/// <returns>null</returns>
function ToggleFootprint(id)
{
    try {
        var mkr = _searchResultsGrid.SearchResultItem[id].Overlay;
        if(mkr.isHidden())
        {
            $("uxFootprintToggle_" + id).src = "images/icon-footprint-on.png";
            mkr.show();
            _searchResultsGrid.SearchResultItem[id].FootprintVisible = true;
        }
        else
        {
           $("uxFootprintToggle_" + id).src = "images/icon-footprint-off.png";
           mkr.hide();
           _searchResultsGrid.SearchResultItem[id].FootprintVisible = false; 
        }
    } 
    catch(e)
    {
        ErrorAlert(SearchResultsGridError);
    }
}

/// <summary>
/// Loads a thumbnail for a given footprint, and adds it to the collection of thumbs for quick toggling.
/// </summary>
/// <params name="id">auto number of row</params>
/// <returns>null</returns>
function LoadThumbnail(id)
{
    if(_searchResultsGrid.SearchResultItem[id].ThumbnailOverlay == null)
    {
        //load thumbnail if not yet loaded.
        _searchResultsGrid.SearchResultItem[id].ThumbnailOverlay = new GGroundOverlay(_searchResultsGrid.SearchResultItem[id].ThumbURL.toString(),new GLatLngBounds(new GLatLng(_searchResultsGrid.SearchResultItem[id].LL_LAT,_searchResultsGrid.SearchResultItem[id].LL_LON),new GLatLng(_searchResultsGrid.SearchResultItem[id].UR_LAT,_searchResultsGrid.SearchResultItem[id].UR_LON)));
        _map.addOverlay(_searchResultsGrid.SearchResultItem[id].ThumbnailOverlay);
    }
}


/// <summary>
/// Toggles the visibility of a given Thumbnail.  If a thumb hasn't yet been loaded, then this loads it.
/// </summary>
/// <params name="id">auto number of row</params>
/// <returns>null</returns>
function ToggleThumbnail(id)//
{
    try {
        //See if it has been loaded yet.
        if(_searchResultsGrid.SearchResultItem[id].ThumbnailOverlay != null)
        {
            //Toggle it
            if(_searchResultsGrid.SearchResultItem[id].ThumbnailOverlay.isHidden())
            {
                 $("uxThumbnailToggle_" + id).src = "images/icon-image-on.png";
                 //Update the bubble hyperlink to 'hide thumbnail', only if this item's bubble was open
                 if(_searchResultsGrid.SearchResultItem[id].IsInfoWindowOpen)
                 {
                     if($("divThumbToggleHL") != null)
                     {
                        var updateTxt = $("divThumbToggleHL").innerHTML;
                        $("divThumbToggleHL").innerHTML = updateTxt.replace(_showHyperlinkText, _hideHyperlinkText);
                     }
                 }
                _searchResultsGrid.SearchResultItem[id].ThumbnailOverlay.show();
                _searchResultsGrid.SearchResultItem[id].ThumbnailVisible = true;
            }
            else
            {
                $("uxThumbnailToggle_" + id).src = "images/icon-image-off.png";
                //Update the bubble hyperlink to 'show thumbnail', only if already open
                if(_searchResultsGrid.SearchResultItem[id].IsInfoWindowOpen)
                {
                    if($("divThumbToggleHL") != null)
                    {
                        var updateTxt = $("divThumbToggleHL").innerHTML;
                        $("divThumbToggleHL").innerHTML = updateTxt.replace(_hideHyperlinkText,_showHyperlinkText);
                    }
                }
                _searchResultsGrid.SearchResultItem[id].ThumbnailOverlay.hide();
                _searchResultsGrid.SearchResultItem[id].ThumbnailVisible = false;
            }
        }
        else
        {
            //Load It
            $("uxThumbnailToggle_" + id).src = "images/icon-image-on.png";
            //Update the bubble hyperlink to 'hide thumbnail', only if already open
            if(_searchResultsGrid.SearchResultItem[id].IsInfoWindowOpen)
            {
                if($("divThumbToggleHL") != null)
                {
                    var updateTxt = $("divThumbToggleHL").innerHTML;
                    $("divThumbToggleHL").innerHTML = updateTxt.replace(_showHyperlinkText, _hideHyperlinkText);
                }
            }
            LoadThumbnail(id);
            _searchResultsGrid.SearchResultItem[id].ThumbnailVisible = true;
        }
    } catch(e)
    {
        ErrorAlert(SearchResultsGridError);
    }
}

/// <summary>
/// Fires in response to a search result row's 'view' hyperlink being clicked.
/// </summary>
/// <params name="id">auto number of row</params>
/// <returns>null</returns>
function ViewDetails(id)
{
    try {
        //Open the info Window for the Selected Footprint.
        //Make sure the footprint is on, and then highlight it.
        //Zoom to it, even
        _map.setCenter(_searchResultsGrid.SearchResultItem[id].Overlay.getBounds().getCenter());
        //_map.setZoom(_map.getBoundsZoomLevel(_searchResultsGrid.SearchResultItem[id].Overlay.getBounds()));
        //_map.panTo(_searchResultsGrid.SearchResultItem[id].Overlay.getBounds().getCenter());
        //Set up an onEndPan listener.  When done, open the window.
        _searchResultsGrid.HighlightFootprint(id);
        _map.enableInfoWindow();
        var infoMsg = null;
        if(_searchResultsGrid.SearchResultItem[id].ThumbnailVisible == true) //If thumb is already on, then swap the info hyperlink to say 'hide thumb'
        {
            _searchResultsGrid.SearchResultItem[id].InfoWindowContent = _searchResultsGrid.SearchResultItem[id].InfoWindowContent.replace(_showHyperlinkText, _hideHyperlinkText);
        }
        // Allows for situtation where user turns on image, closes bubble, turns off image, clicks details to open bubble again.
        else 
        {
            _searchResultsGrid.SearchResultItem[id].InfoWindowContent = _searchResultsGrid.SearchResultItem[id].InfoWindowContent.replace(_hideHyperlinkText, _showHyperlinkText);
        }

        _map.openInfoWindowHtml(_searchResultsGrid.SearchResultItem[id].Overlay.getBounds().getCenter(), _searchResultsGrid.SearchResultItem[id].InfoWindowContent);
        _searchResultsGrid.ClearOpenInfoWindowStatus(); //set all other info window bools to false
        _searchResultsGrid.SearchResultItem[id].IsInfoWindowOpen = true; //set this status to true, so we know this result's info window is open
        //Force Showing of this footprint, shince it is highlighted.
        //_searchResultsGrid.HighlightFootprint(id); 
    } catch(e)
    {
        ErrorAlert(SearchResultsGridError);
    } 
}


/// <summary>
/// Builds an HTML string of a search result's info window content
/// </summary>
/// <params name="count">auto number of row 1-20</params>
/// <params name="displayID">display</params>
/// <params name="jsonFeature">a JSON feature</params>
/// <returns>null</returns>
function BuildFootprintContent(count, displayID, jsonFeature)
{
    try {
        var returnContent  = _unableToGenerateContent;
        if(jsonFeature)
        {
            var aDate = (jsonFeature.attributes[_dateColumn] == undefined) ? (new Date(_defaultDateOnRESTError)) : (new Date(jsonFeature.attributes[_dateColumn]));
            var collectionDate = (jsonFeature.attributes[_dateColumn] == undefined) ? (_unknownValue): (FormatDate(aDate.getDate(), aDate.getMonth(), aDate.getFullYear()));
            var cloudCoverDescription = (jsonFeature.attributes[_cloudCoverColumn] == undefined) ? (_unknownValue) : (GetCloudDescriptionFromValue(jsonFeature.attributes[_cloudCoverColumn]));
            var cloudCoverPercent = (jsonFeature.attributes[_cloudCoverColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_cloudCoverColumn]);
            var spacecraft = (jsonFeature.attributes[_spacecraftColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_spacecraftColumn]);
            var tiltAngle = (jsonFeature.attributes[_tiltAngleColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_tiltAngleColumn]); 
            var groundSampleDistance = (jsonFeature.attributes[_resolutionColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_resolutionColumn]);
            var dataOwner = (jsonFeature.attributes[_dataOwnerColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_dataOwnerColumn]);
    //        var imageID = (jsonFeature.attributes[_imageNameColumn] == undefined) ? (_unknownValue) : ((jsonFeature.attributes[_imageNameColumn].length < _imageIDLength) ? (jsonFeature.attributes[_imageNameColumn]): (jsonFeature.attributes[_imageNameColumn].substr(jsonFeature.attributes[_imageNameColumn].length - _imageIDLength, _imageIDLength))); //Checks that the column is not null, and then checks to see if the string is the correct length
            var imageID = (jsonFeature.attributes[_imageNameColumn] == undefined) ? (_unknownValue) : (jsonFeature.attributes[_imageNameColumn]);
            var fullProductURL = (jsonFeature.attributes[_fullProductURL] == undefined) ? ('#') : (jsonFeature.attributes[_fullProductURL]);
            var fullMetadataURL = (jsonFeature.attributes[_fullMetadataURL] == undefined) ? ('#') : (jsonFeature.attributes[_fullMetadataURL]);


           returnContent = "<div>" +
           "<span class='GreenBold'>Search Result " + (displayID + 1) + "</span>" + //User friendly non-zero based index
           "<table><tr><td>" +
           _collectionDateText +
           "</td><td>" +
           collectionDate + 
           "</td></tr><tr><td>" +
           _cloudCoverText +
           "</td><td>" +
           cloudCoverDescription + " (" + cloudCoverPercent + "%)" +
           "</td></tr><tr><td>" +
           _vehicleText +
           "</td><td>" +
           spacecraft +
           "</td></tr><tr><td>" +
           _tileAngleText +
           "</td><td>" +
           tiltAngle +
           "</td></tr><tr><td>" +
           _groundSampleDistanceText +
           "</td><td>" +
           groundSampleDistance +
           "</td></tr><tr><td>" +
           _dataOwnerText +
           "</td><td>" +
           dataOwner +
           "</td></tr><tr><td>" +
           _orderingIDText +
           "</td><td>" +
           imageID +
           "</td></tr></table><br />" +
           _fullDataText +
           "<br />" +
           "<div style='margin:0px 0px 0px 0px' id='divThumbToggleHL'>› <a id='uxHLThumbToggle' href=\"javascript:ToggleThumbnail(" + count + ")\">" + _showHyperlinkText + "</a></div>" +
           "› <a target='_blank' href=\"" + fullMetadataURL + "\">" + _viewDataText + "</a><br/>" +
           "› <a target='_blank' href=\"" + fullProductURL  + "\">" + _productInfoText + "</a>" +
           "</div>";
       }
   
       return returnContent;
    } catch(e)
    {
        ErrorAlert(SearchResultsGridError);
    }
}




