﻿// Our global state
var gLocalSearch;
var gMap;
var gSelectedResults = [];
var gCurrentResults = [];
var gSearchForm;
var geocoder = null;
var searchType = null;

// Create our "tiny" marker icon
var gSmallIcon = new GIcon();
gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
gSmallIcon.iconSize = new GSize(12, 20);
gSmallIcon.shadowSize = new GSize(22, 20);
gSmallIcon.iconAnchor = new GPoint(6, 20);
gSmallIcon.infoWindowAnchor = new GPoint(5, 1);

// Set up the map and the local searcher.
function OnLoad() 
{
  geocoder = new GClientGeocoder();
       
  gSearchForm = new GSearchForm(false, document.getElementById("searchform"));
  gSearchForm.setOnSubmitCallback(null, CaptureForm);
  gSearchForm.input.focus();

  // Initialize the map
  gMap = new GMap(document.getElementById("map"));
  gMap.addControl(new GSmallMapControl());
  gMap.addControl(new GMapTypeControl());
  //gMap.setCenter(new GLatLng(37.4419, -122.1419), 13);
  
  var bHotelUseGeocode = document.getElementById("hotelUseGeocode").value;
  
  if(bHotelUseGeocode == "true")
  {
    var strLatitude = document.getElementById("hotelLatitude").value;
    var strLongitude = document.getElementById("hotelLongitude").value;
    showGeocode(new GLatLng(strLatitude, strLongitude));
  }
  else
  {
    var strHotelAddress = document.getElementById("hotelAddress").value;
    showAddress(strHotelAddress);
  }

  //Initialize the local searcher
  gLocalSearch = new GlocalSearch();
  gLocalSearch.setCenterPoint(gMap);
  gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
  
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() 
{
  if (!gLocalSearch.results) return;
  var searchWell = document.getElementById("searchwell");

  // Clear the map and the old search well
  searchWell.innerHTML = "";
  for (var i = 0; i < gCurrentResults.length; i++) {
    if (!gCurrentResults[i].selected()) {
      gMap.removeOverlay(gCurrentResults[i].marker());
    }
  }

  gCurrentResults = [];
  for (var i = 0; i < gLocalSearch.results.length; i++) {
    gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
  }

  var attribution = gLocalSearch.getAttribution();
  if (attribution) {
    document.getElementById("searchwell").appendChild(attribution);
  }

  // move the map to the first result if it exists
  if (gLocalSearch.results.length > 0) {
      var first = gLocalSearch.results[0];
      gMap.recenterOrPanToLatLng(new GPoint(parseFloat(first.lng), parseFloat(first.lat)));
  }
  
  if ((gLocalSearch.results.length == 0 && searchType == 0) || 
    (gLocalSearch.results.length > 1 && searchType == 0)) {
    recommendationSearchByAddress();
  }
}

// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) 
{
  gLocalSearch.execute(searchForm.input.value);
  return false;
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) 
{
  this.result_ = result;
  this.resultNode_ = this.unselectedHtml();
  
  if (result != null) {
      var titleLink = document.createElement('<a style="font-size: 10px; font-weight: bold;" target="_blank">');
      var addressBlock = document.createElement('<div style="font-size: 10px;">');
      var phoneBlock = document.createElement('<div style="font-size: 10px;">');
      var strHotelAddressLine1 = document.getElementById("hotelAddressLine1").value;
      var strHotelAddressLine2 = document.getElementById("hotelAddressLine2").value;
      var dirLink = document.createElement('<a style="font-size: 10px;" target="_blank">');
      var sep = document.createElement('<hr style="height: 1px;">');
      var selectedTextSplit = recommendDropDownList.value.split("\t");
      
      if (searchType == 1) {
          if (selectedTextSplit.length == 4) {
                if (selectedTextSplit[2].length <= 0) {
                    titleLink.href = "http://www.google.com/search?q=" + escape(selectedTextSplit[0]);
                } else {
                    titleLink.href = selectedTextSplit[2];
                }
                titleLink.innerHTML = selectedTextSplit[0];
          }
      } else {
          titleLink.href = result.url;
          titleLink.innerHTML = result.titleNoFormatting;
      }
      
      addressBlock.innerHTML = result.streetAddress + "<br />" + result.city + "&nbsp" + result.region;
      
      if (searchType == 1) {
        if (selectedTextSplit.length == 4) {
            phoneBlock.innerHTML += selectedTextSplit[1] + '<br />';
        }
      } else {
          if (result.phoneNumbers != null) {
              for (var i = 0; i < result.phoneNumbers.length; i++) {
                  if (result.phoneNumbers[i].type.length > 0) {
                        phoneBlock.innerHTML += result.phoneNumbers[i].type + ' - ';
                  }
                  phoneBlock.innerHTML += result.phoneNumbers[i].number + '<br />';
              }
          }
      }
      
      dirLink.href = result.ddUrlToHere + "&saddr=" + escape(strHotelAddressLine1 + ", " + strHotelAddressLine2);
      dirLink.innerHTML = "get directions";
      
      document.getElementById("searchwell").appendChild(titleLink);
      document.getElementById("searchwell").appendChild(addressBlock);
      document.getElementById("searchwell").appendChild(phoneBlock);
      document.getElementById("searchwell").appendChild(dirLink);
      document.getElementById("searchwell").appendChild(sep);
  }
  
  gMap.addOverlay(this.marker(gSmallIcon));
  searchType = null;
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) 
{
  if (this.marker_) return this.marker_;
  var marker = new GMarker(new GLatLng(parseFloat(this.result_.lat),
                                     parseFloat(this.result_.lng)),
                           opt_icon);
  GEvent.bind(marker, "click", this, function() {
    marker.openInfoWindow(this.selected() ? this.selectedHtml() :
                                            this.unselectedHtml());
  });
  this.marker_ = marker;
  return marker;
}

// "Saves" this result if it has not already been saved
LocalResult.prototype.select = function() 
{
//  if (!this.selected()) {
//    this.selected_ = true;

//    // Remove the old marker and add the new marker
//    gMap.removeOverlay(this.marker());
//    this.marker_ = null;
//    gMap.addOverlay(this.marker(G_DEFAULT_ICON));

//    // Add our result to the saved set
//    document.getElementById("selected").appendChild(this.selectedHtml());

//    // Remove the old search result from the search well
//    this.resultNode_.parentNode.removeChild(this.resultNode_);
//  }
}

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.unselectedHtml = function() 
{
    var container = document.createElement("div");
    container.className = "unselected";
    container.appendChild(this.result_.html.cloneNode(true));
    var saveDiv = document.createElement("div");
    saveDiv.className = "select";
    saveDiv.innerHTML = "";
    GEvent.bindDom(saveDiv, "click", this, function() {
        gMap.closeInfoWindow();
        this.select();
        gSelectedResults.push(this);
    });
    container.appendChild(saveDiv);
    return container;
}

// Returns the HTML we display for a result after it has been "saved"
LocalResult.prototype.selectedHtml = function() 
{
    return this.result_.html.cloneNode(true);
}

// Returns true if this result is currently "saved"
LocalResult.prototype.selected = function() 
{
    return this.selected_;
}

GSearch.setOnLoadCallback(OnLoad);

function showAddress(address) 
{
    if (geocoder) 
    {
        geocoder.getLatLng(address, showCallback);
    }
}

function showGeocode(point) 
{
    showCallback(point);
}

function showCallback(point) 
{
    if (point) 
    {
        gMap.setCenter(point, 13);          
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", 
            function()
            {
                marker.openInfoWindowHtml(getHotelAddressFormatted());
            }
        );
        gMap.addOverlay(marker);
        marker.openInfoWindowHtml(getHotelAddressFormatted());
    }
}

function getHotelAddressFormatted()
{
    var strHotelName = document.getElementById("hotelName").value;
    var strHotelAddressLine1 = document.getElementById("hotelAddressLine1").value;
    var strHotelAddressLine2 = document.getElementById("hotelAddressLine2").value;
    
    var sInfo = strHotelName + "<br />" + strHotelAddressLine1 + "<br />" + strHotelAddressLine2;
    return sInfo;
}

function recommendationSearch(ddl)
{
    searchType = 0;
    gLocalSearch.clearResults();
    
    if (recommendDropDownList.selectedIndex > 0) {
        var selectedTextSplit = recommendDropDownList.value.split("\t");
        var selectedPhone = null;
        
        if (selectedTextSplit.length == 4) {
            selectedPhone = selectedTextSplit[1];
        }
        if(selectedPhone != null && selectedPhone != "") {
            gSearchForm.execute(selectedPhone);
        } else {
            recommendationSearchByAddress();
        }
    }
}

// If the phone number lookup fails, try the address itself.
function recommendationSearchByAddress(ddl)
{
    searchType = 1;
    gLocalSearch.clearResults();
    
    if (recommendDropDownList.selectedIndex > 0) {
        var selectedTextSplit = recommendDropDownList.value.split("\t");
        var selectedAddress = null;
        
        if (selectedTextSplit.length == 4) {
            selectedAddress = selectedTextSplit[3];
        } else {
            // Otherwise it's probably a category
            searchType = 2;
            selectedAddress = recommendDropDownList.value;
        }
       
        if(selectedAddress != null && selectedAddress != "") {
            gSearchForm.execute(selectedAddress);
        }
    }
}