/*----------------------------------------------------------
 * google_search_helper.js
 *
 * This file contains all sorts of useful helper functions
 * for using Google Search API 
 *--------------------------------------------------------*/
function googleSuggestionSearch(){

  this.localSearch = '';
  this.gSearchResultMarkerList = new Array();
  this.gSearchFormList = new Object();
  this.postSearchAction;
  this.searchFailureAcion;
  this.searchHelperObjectName = '';

  
  var searchFormInputField;
  var searchResultsContainer;

  this.setSearchInputField = function( fieldName ){
    searchFormInputField = fieldName;
  }
  
  this.setSearchResultContainer = function( fieldName ){
    searchResultsContainer = fieldName;
  }

  this.setSearchResultReadyFunction = function(postSearchAction){
  	this.postSearchAction = postSearchAction;
  }
  this.setSearchFailureFunction = function(searchFailureAction){
  	this.searchFailureAction = searchFailureAction;
  }
  this.openSearchResultPoint = function(result_number){
    google.maps.event.trigger( this.gSearchResultMarkerList[result_number], 'click');
  }

  this.doGoogleSearch = function(){
    //get form value from form
    var idValue = "#" + searchFormInputField;
    var latLongString = gMap.getCenter().toString();
    this.localSearch.setCenterPoint(latLongString);
    this.localSearch.execute($(idValue).val());
    $("#suggestheader").hide();
    this.postSearchAction();
  }

  this.clearSearchResults = function(){
    if( this.gSearchResultMarkerList.length > 0){
      for(var i=0; i < this.gSearchResultMarkerList.length; i++){
        this.gSearchResultMarkerList[i].setMap(null);
      }
      //reset marker list to prevent messiness
      this.gSearchResultMarkerList = new Array();
    }
  }

  this.mapSearchResults = function(){
    //unshow all place markers
    this.clearSearchResults();
    var results = this.localSearch.results; // Grab the results array
    // We loop through to get the points
    for (var i = 0; i < results.length; i++) {
      var result = results[i]; // Get the specific result
      var markerLatLng = new google.maps.LatLng(parseFloat(result.lat),
                                                parseFloat(result.lng));
      var marker = makeSearchMarker(gMap, parseFloat(result.lat), parseFloat(result.lng), result.titleNoFormatting);
      marker.set("marker_num", i);
      this.gSearchResultMarkerList.push(marker);
      this.gSearchFormList[i] = result;
      
      google.maps.event.addListener(marker, 'click', function() {
        gMap.setCenter(this.getPosition());
        var thisResult = searchHelper.gSearchFormList[this.get("marker_num")];
        var entryPhoneNumber = "";
        
        clearAddSuggestionFields();
        if(thisResult.phoneNumbers){
          entryPhoneNumber = thisResult.phoneNumbers[0].number;
        }
        
        hideSuggestionSearchResults();
        showSuggestionSubmission();
        showSuggestionFields( thisResult.titleNoFormatting, 
        		thisResult.streetAddress, 
        		thisResult.city, 
        		thisResult.region, 
        		thisResult.country, 
        		entryPhoneNumber, 
        		thisResult.lat, 
        		thisResult.lng)
      });
      result.marker = marker; // bind the marker to the result
    }

    // Store where the map should be centered
    var center = this.localSearch.resultViewport.center;

    // Calculate what the zoom level should be
    var ne = new google.maps.LatLng(this.localSearch.resultViewport.ne.lat,
                                    this.localSearch.resultViewport.ne.lng);
    var sw = new google.maps.LatLng(this.localSearch.resultViewport.sw.lat,
                                    this.localSearch.resultViewport.sw.lng);
    var bounds = new google.maps.LatLngBounds(sw, ne);
    var zoom = gMap.fitBounds(bounds);

    // Set the new center of the map
    // parseFloat converts the lat/lng from a string to a float, which is what
    // the LatLng constructor takes.
    gMap.setCenter(new google.maps.LatLng(parseFloat(center.lat),
                                         parseFloat(center.lng)),
                                         zoom);
  }    
  this.searchComplete = function() {
     this.mapSearchResults();
     var searchContainerId = "#" + searchResultsContainer;
     
    $(searchContainerId).html("");
    var typeName = 'suggestion';
    var newInfoBoxTitle = "<span><img src='"+ gPointTypeList[typeName].iconPath +"' /> " + typeName +  " search</span>";
    setInfoBoxTitle(newInfoBoxTitle);
    if (this.localSearch.results && this.localSearch.results.length > 0) {
      // Loop through our results, printing them to the page.
      var results = this.localSearch.results;
      if(results.length == 0){
      	$("#feedback").show();
		$("#feedback").text("No search results found, bummer.");
		$("#feedback").fadeOut(4000);
	      }
      else{ 
        for (var i = 0; i < results.length; i++) {
          // For each result write it's title and image to the screen
          var result = results[i];
          var result_html = "<div class='search_entry' >";
          var functionCall = 'javascript:searchHelper.openSearchResultPoint('+ i + ');';
          result_html += " <div class='search_entry_buttons'><div class='suggest_image'><form action='" + functionCall + "'><input type='image' name='image'  src='/images/buttons/mediumbuttonblank.png'></form></div></div>";
          result_html += "<div class='search_entry_main'>";
          result_html += "<div class='search_entry_text title' >";
          var resultPhoneNumber = "";
          if(!result.phoneNumbers){
            resultPhoneNumber = "No Phone Number";
          }
          else{
            resultPhoneNumber = result.phoneNumbers[0].number;
          }
          result_html += result.titleNoFormatting +"</div>"; 

          for (key in result.addressLines){
            result_html += "<div class='search_entry_text'>" + result.addressLines[key]+ "</div>";
          }

          result_html += "<div class='search_entry_text search_entry_phone_number'>" + resultPhoneNumber+ "</div>";
          
          result_html += "</div></div>"; 
          $(searchContainerId).append(result_html);
        }
      }
      // Now add the paging links so the user can see more results.
      this.addPaginationLinks();
    }
    else{
    	//Search failed.
    	this.searchFailureAction();
    	$("#feedback").show();
    	$("#feedback").text("No search results found, bummer.");
    	$("#feedback").fadeOut(5000);
    	return false;
    }
    return true;
  }


  this.addPaginationLinks = function(){
    // The cursor object has all things to do with pagination
    var cursor = this.localSearch.cursor;
    var curPage = cursor.currentPageIndex; // check what page the app is on
    var pagesDiv = document.createElement('div');
    pagesDiv.id = "search_page_navigation";
    for (var i = 0; i < cursor.pages.length; i++) {
      var page = cursor.pages[i];
      if (curPage == i) { // if we are on the curPage, then don't make a link
        var label = document.createTextNode(' ' + page.label + ' ');
        pagesDiv.appendChild(label);
      } 
      else {
        // If we aren't on the current page, then we want a link to this page.
        // So we create a link that calls the gotoPage() method on the searcher.
        var link = document.createElement('a');
        link.href = 'javascript:'+ this.searchHelperObjectName +'.localSearch.gotoPage('+i+');';
        link.innerHTML = page.label;
        link.style.marginRight = '2px';
        pagesDiv.appendChild(link);
      }
    }

    var contentDiv = document.getElementById(searchResultsContainer);
    contentDiv.appendChild(pagesDiv);
  }

}
