// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// END FLOCK GPL

const GOOGLE_LIVE_SEARCH_NAME = "Google";
const GOOGLE_LIVE_SEARCH_CLASSID =
  Components.ID("{6c865d49-e87a-49a9-9241-fad18e701a74}");

// API docs: http://code.google.com/apis/ajaxsearch/documentation/#fonje

const GOOGLE_API_REFERER = "http://flock.com/";


const CC = Components.classes;
const CI = Components.interfaces;
const CR = Components.results;
const CU = Components.utils;

CU.import("resource:///modules/FlockLiveSearchProvider.jsm");

function GoogleLiveSearch() {
  this._init();
}

GoogleLiveSearch.prototype = FlockLiveSearchProvider.generateComponent(
  GOOGLE_LIVE_SEARCH_NAME,
  GOOGLE_LIVE_SEARCH_CLASSID,
  GoogleLiveSearch,
  "Google"
);

GoogleLiveSearch.prototype._requestHook =
function GLS__requestHook(aXHR) {
  aXHR.setRequestHeader("Referer", GOOGLE_API_REFERER);
};

GoogleLiveSearch.prototype._getResults =
function GLS__getResults(aXHR, aMaxResults) {
  var unescapeHTML = CC["@mozilla.org/feed-unescapehtml;1"]
                     .getService(CI.nsIScriptableUnescapeHTML);
  var results = [];

  try {
    var nsJSON = CC["@mozilla.org/dom/json;1"].createInstance(CI.nsIJSON);
    var data = nsJSON.decode(aXHR.responseText);
    for each (var result in data.responseData.results) {
      results.push({ title: unescapeHTML.unescape(result.titleNoFormatting),
                     url: result.unescapedUrl });
    }
  } catch (ex) {
    // just ignore errors
  }

  return results;
};

var NSGetModule =
  FlockLiveSearchProvider.generateNSGetModule(GOOGLE_LIVE_SEARCH_NAME,
                                              GoogleLiveSearch);
