﻿/*
placenamesearch.js handles the logic for executing placename searches and processing the results
*/

var _tabAccuracy = new Array(2,4,6,10,12,13,16,16,17); //Helps convert JSON returned 'accuracy' to GMaps 'zoomLevel'
var _placeArray = null; // Array of placenames
var _marker = null; // The marker placed on the map as a result of the AddMarker function (either placename search of featured location).
var _markerContent = null; //The content of the marker.  Used for removing then re-adding the marker if zoom level has changed.

/// <summary>
/// Starts the process of executing a placename search.  Does some client validation before continuing.
/// Results are returned to the function specified as 2nd parameter of getLocations() 
/// </summary>
/// <returns>null</returns>
function InitiatePlacenameSearch()
{
    var searchText = $("uxNameSearch").value;
    searchText = searchText.replace(/#/, ""); // remove hash symbol from search params
    if(searchText.length > 0)
    {
      executeSearchRequest(searchText);
      if($("wrapper-featuredLocations").style.display != 'none')
      {
        // Minimize the featured locations
        Effect.toggle('wrapper-featuredLocations','slide');
        
        // Remove the New To GeoEye Div
        Effect.Fade('wrapper-newToGeoeye');
      }
      document.getElementById('aFeaturedLocations').innerHTML = "<img src=\"images/mini-button-expand-arrow.png\" border=\"0\" title=\"Show Featured Locations\" alt=\"Show Featured Locations\" />";

    }
    else
    {
        ErrorAlert(NoPlaceNameError);
    }
}

/// <summary>
/// Executes Geocoding operation
/// Results are returned to the function specified as 2nd parameter of getLocations() 
/// </summary>
/// <param name="address">string address or name</param>
/// <returns>null</returns>
//function ExecuteGeocode(address) 
//{
//   if (_geocoder) 
//      {
//        _geocoder.setBaseCountryCode("EN");
//        _geocoder.getLocations(address,ProcessPlacenameSearchResults);
//      }
//}

/******************************************************************************
*   Begin HTTP Google Geocoding Section                                       *
*******************************************************************************/

function executeSearchRequest(searchrequesttext)
{
    // Create a new script object
    // (implementation of this class is in /export/jsr_class.js)
    aObj = new JSONscriptRequest('http://maps.google.com/maps/geo?output=json&oe=utf-8&hl=en&key=' + _APIKey + '&q=' +  searchrequesttext  + '&callback=ProcessPlacenameSearchResults');
    //aObj = new JSONscriptRequest('http://ws.geonames.org/searchJSON?q=' +  searchrequesttext  + '&maxRows=10&callback=executeSearchResults');
    // Build the script tag
    aObj.buildScriptTag();
    // Execute (add) the script tag
    aObj.addScriptTag();
}


/// <summary>
/// Processes Google Geocoder JSON results. If multiple results exist, create a list.
/// If just one result is returned, map is automatically zoomed.
/// </summary>
/// <param name="response">Google Geocoder getLocations() JSON response</param>
/// <returns>null</returns>
function ProcessPlacenameSearchResults(response) 
{
      //Clear overlays
      // _map.clearOverlays(); // Clear everything from map
      ClearEverything(); // Clear everything from results grid
      _placeArray = response.Placemark;
      
      if(response.Status.code!=200)
      {
        // alert('No results found');
        ShowPlacenameMatchesPanel("No matches found.  Please search again.", "");
      } 
      else 
      {
        var responseCounter;
        //Loop thru each placename match and write out the results.
        //If only one exists, then automatically zoom to region.
        if(response.Placemark.length == 0)
        {
        //No results found - let the user know
        ShowPlacenameMatchesPanel("No matches found.  Please search again.", "");
        }
        else if(response.Placemark.length == 1)
        {
            //Add placename match to map, zoom to extent
            AddPlacemarkToMap(0, true);
            var html = "<span class='GreenBold'>Displaying</span><br/> " + CreatePlacenameMatchResult(0);
            ShowPlacenameMatchesPanel(html, "");
        }
        else if(response.Placemark.length > 1)
        {
            //Begin to build HTML list of matches.
            var html = '<p><b>Did you mean...</b></p>';
            //Zoom to first result
            //AddPlacemarkToMap(0, true);
            var matches = CreatePlacenameMatchResult(0);
            //Loop thru the placemarks and display a list in the placename matches pane
            for(responseCounter=1;responseCounter<response.Placemark.length;responseCounter++)
            {
                //Add possible matches to map
                // AddPlacemarkToMap(response.Placemark[responseCounter], false);
                //Add to HTML list
                matches += CreatePlacenameMatchResult(responseCounter);
            }
            //matches+= "</div>";
            //Turn on results panel.
            ShowPlacenameMatchesPanel(html, matches);
        }
      }
}
 
/// <summary>
/// Adds a placename match result to the map.  If zoomToPoint is set to true, the map will recenter and zoom to the result.
/// </summary>
/// <param name="Placemark">Google Geocoder getLocations() result Placemark</param>
/// <param name="zoomToPoint">boolean</param>
/// <returns></returns>
function AddPlacemarkToMap(index, zoomToPoint, feature)
{
    var zoomlevel = null;
    var point = null;
    var name = null;
    var nowShowing = null;
    
    
    
    // If the feature var exists, it is a Featured Location.  Pull from array accordingly
    if (feature) {
        _placeNameSearchWindowVisible = false; //This is not a place name match, so don't close then reopen the window when zooming.
        zoomlevel = _featureArray[index][2];
        point = new GLatLng(_featureArray[index][0], _featureArray[index][1]);
        name = _featureArray[index][3];
        //Update 'Now Showing' text.
        //index, name, description
        nowShowing = "<span class='GreenBold'>Displaying</span><br/> " + BuildFeaturedLocationLink(index, _featureArray[index][3], _featureArray[index][4]);
        
    }
    // Otherwise, it is a result from the PlaceName search, pull from object accordingly.
    else 
    {
        _placeNameSearchWindowVisible = true; //Lets the app know we've reinitialized the place info window.
        feature = null;
        //Take in a placemark search result, add placemark to map.  Optionally zoom to Point
        accuracy = _placeArray[index].AddressDetails.Accuracy;
        point = new GLatLng(_placeArray[index].Point.coordinates[1], _placeArray[index].Point.coordinates[0]);
        zoomlevel = _tabAccuracy[accuracy];
        name = _placeArray[index].address;
        //Update 'Now Showing' text.
        nowShowing = "<span class='GreenBold'>Displaying</span><br/> " + BuildNowShowingLink(index, _placeArray[index].address, _placeArray[index].address);
    }
    if(zoomToPoint)
    {   //Zoom if option is set to true
        _map.setCenter(point, zoomlevel);
    }

    ShowPlacenameMatchesPanel(nowShowing, "");

    // Create a marker
    var tinyIcon = new GIcon();
    tinyIcon.image = "/maps/images/location.png";
    tinyIcon.iconSize = new GSize(2, 2);
    tinyIcon.iconAnchor = new GPoint(6, 20);
    tinyIcon.infoWindowAnchor = new GPoint(5, 1);

    // Set up the GMarkerOptions object literal
    markerOptions = { icon:tinyIcon };
    _marker = new GMarker(point,markerOptions);
    
    // Add the marker to map
    _map.addOverlay(_marker);
    //Enable info window when new marker is open.
    //_map.enableInfoWindow();
    //Add a listener to seen when the info window is closed.
    GEvent.addListener(_map.getInfoWindow(), "closeclick", function(){_placeNameSearchWindowVisible = false;});//
    
    // Add address information and map tools to marker
    _markerContent = BubbleContent(name);
    _marker.bindInfoWindowHtml(_markerContent);
    _marker.openInfoWindowHtml(_markerContent);
}

/// <summary>
/// generates a hyperlinked result that, when clicked, zooms the map to the placename
/// Accepts an index of the _placeArray
/// </summary>
/// <param name="Placemark"></param>
/// <returns>HTML formatted result string</returns>
function CreatePlacenameMatchResult(index)
{
    // return '<a href="javascript:InitiateCatalogSearchByPlacenameCoordinates(' + Placemark.Point.coordinates[1] +',' + Placemark.Point.coordinates[0] + ',' + _tabAccuracy[Placemark.AddressDetails.Accuracy] + ');" title=\"(Country Code: '+Placemark.AddressDetails.Country.CountryNameCode +')\">' + Placemark.address + '</a><br>';
    if(_placeArray[index].AddressDetails.Country != undefined)
    {
     return '<a href="javascript:AddPlacemarkToMap(' + index + ',' + _tabAccuracy[_placeArray[index].AddressDetails.Accuracy] + ');" title=\"(Country Code: '+_placeArray[index].AddressDetails.Country.CountryNameCode +')\">' + _placeArray[index].address + '</a><br/>';
    }
    else
    {
        return '<a href="javascript:AddPlacemarkToMap(' + index + ',' + _tabAccuracy[_placeArray[index].AddressDetails.Accuracy] + ');\">' + _placeArray[index].address + '</a><br/>';
    }
    
}

function BuildNowShowingLink(featureIndex, featureName, featureDescription)
{
   return "<a href=\"javascript:AddPlacemarkToMap("+ featureIndex + "," + true +","+false+");\" title=\"" + featureDescription + "\">" + featureName + "</a><br>";
}

/// <summary>
/// Clears the placename match panel and hides it
/// </summary>
/// <returns>null</returns>
function HidePlacenameMatchPanel()
{  
    //$('wrapper-placeNameMatches').style.display = 'none';
    $('wrapper-placeNameMatches').innerHTML = "";
}

/// <summary>
/// Turns on the placenameMatchesPanel, and fills it with a result list.
/// </summary>
/// <returns>null</returns>
function ShowPlacenameMatchesPanel(headerText, matchesHTML)
{

    $('wrapper-placeNameMatches').style.display = 'inline';
    $('wrapper-matchesHeader').innerHTML = headerText;
    if(matchesHTML.length == 0)
    {
        $('wrapper-matches').style.display = "none";
    }
    else
    {
        $('wrapper-matches').style.overflowX = "auto";
        $('wrapper-matches').style.overflowY = "hidden";
        $('wrapper-matches').style.display = "inline";
        $('wrapper-matches').innerHTML = matchesHTML;
    }
}

///Clears search textbox, placename matches, resets map.
function FindPlaceClear()
{
    $("uxNameSearch").value = "";
    //HidePlacenameMatchPanel();
    ShowPlacenameMatchesPanel("","");
    _map.clearOverlays();
    //Set Original Zoom.
    //_map.setCenter(_defaultMapCenter, _defaultMapZoom);
    //Force Close Info Window
    _map.closeInfoWindow();
}


