// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2008
// 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 EBAY_LIVE_SEARCH_NAME = "EBay";
const EBAY_LIVE_SEARCH_CLASSID =
  Components.ID("{46a6a8b0-3327-11db-a98b-0800200c9a66}");

const EBAY_SEARCH_API_URL = "http://rest.api.ebay.com/restapi";
const EBAY_USERNAME = "flocknflow";
const REST_API_TOKEN = "jCu2LHQ247Q%3D**pWWu%2BOldh2Bj13OcHs1ZZcSytoI%3D";

// The following codes are passed to the api so that flock
// recieves commissions
const EBAY_AFFILIATE_TRACKING_PARTNER_CODE = "1";
const EBAY_AFFILIATE_TRACKINGID = "2500336";


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

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

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

EBayLiveSearch.prototype = FlockLiveSearchProvider.generateComponent(
  EBAY_LIVE_SEARCH_NAME,
  EBAY_LIVE_SEARCH_CLASSID,
  EBayLiveSearch,
  null,
  "chrome://flock/content/search/ebayIcon.png"
);

EBayLiveSearch.prototype.getFullResultsURL =
function ELS_getFullResultsURL(aQuery) {
  return "http://search.ebay.com/" + encodeURIComponent(aQuery)
         + "?TrackingID=" + EBAY_AFFILIATE_TRACKINGID;
};

EBayLiveSearch.prototype._getQueryURL =
function ELS__getQueryURL(aQuery, aNumResults) {
  return EBAY_SEARCH_API_URL + "?"
         + "CallName=GetSearchResults"
         + "&RequestUserId=" + EBAY_USERNAME
         + "&RequestToken=" + REST_API_TOKEN
         + "&Version=491"
         + "&UnifiedInput=1"
         + "&Query=" + encodeURIComponent(aQuery)
         + "&TrackingPartnerCode=" + EBAY_AFFILIATE_TRACKING_PARTNER_CODE
         + "&TrackingID=" + EBAY_AFFILIATE_TRACKINGID;
}

EBayLiveSearch.prototype._getResults =
function ELS__getResults(aXHR, aMaxResults) {
  var items = aXHR.responseXML.getElementsByTagName("SearchResultItem");

  var maxResults = Math.min(items.length, aMaxResults);

  var results = [];
  for (var i = 0; i < maxResults; i++) {
    var item = items[i];

    var title = item.getElementsByTagName("Title")[0].firstChild.nodeValue;
    var url = item.getElementsByTagName("ViewItemURL")[0].firstChild.nodeValue;

    results.push({ title: title, url: url });
  }

  return results;
}

var NSGetModule =
  FlockLiveSearchProvider.generateNSGetModule(EBAY_LIVE_SEARCH_NAME,
                                              EBayLiveSearch);
