// 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 CRAIGSLIST_LIVE_SEARCH_NAME = "Craigslist";
const CRAIGSLIST_LIVE_SEARCH_CLASSID =
  Components.ID("{67a9e610-313f-11db-a98b-0800200c9a66}");

const CRAIGSLIST_SEARCH_API_URL = "http://www.craigslist.org/cgi-bin/search";


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

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


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

CraigslistLiveSearch.prototype = FlockLiveSearchProvider.generateComponent(
  CRAIGSLIST_LIVE_SEARCH_NAME,
  CRAIGSLIST_LIVE_SEARCH_CLASSID,
  CraigslistLiveSearch,
  null,
  "http://craigslist.com/favicon.ico",
  "http://craigslist.org/search/sss?query="
);

CraigslistLiveSearch.prototype._getQueryURL =
function CLLS__getQueryURL(aQuery, aNumResults) {
  return CRAIGSLIST_SEARCH_API_URL + "?"
         + "areaID=1"
         + "&query=" + aQuery
         + "&catAbbreviation=sss"
         + "&format=rss";
}

CraigslistLiveSearch.prototype._getResults =
function CLLS__getResults(aXHR, aMaxResults) {
  var items = aXHR.responseXML.getElementsByTagName("item");

  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("link")[0].firstChild.nodeValue;

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

  return results;
}

var NSGetModule =
  FlockLiveSearchProvider.generateNSGetModule(CRAIGSLIST_LIVE_SEARCH_NAME,
                                              CraigslistLiveSearch);
