// JavaScript Document
/* Site search with the Google AJAX Search API.
 *
 * http://snarfed.org/space/site+search+with+the+Google+AJAX+Search+API
 * Copyright 2006 Ryan Barrett <pyblosxom@ryanb.org>.
 * Licensed under GPL v2.
 */

var results_div_id = 'page-content'
var results_header = '<div class="listingPrice">';
var results_footer = '</div>';
var searching_message = '<span class="listingPrice">Searching...</span>'

function site_search(domain, query) {
  // must not be empty
  if (!query.match('\\S')) {
    alert('Please enter a query.');
    return;
  }
  this.query = query;

  // save the current page
  if (document.getElementById('old' + results_div_id))
    site_search_back();

  old_page = document.getElementById(results_div_id);
  old_page.id = 'old' + results_div_id
  old_page.style.display = 'none';

  // tell the user we're searching
  this.page = document.createElement('div');
  this.page.id = results_div_id;
  this.page.innerHTML += searching_message;
  old_page.parentNode.insertBefore(this.page, old_page)

  // set up the search
  this.gwebsearch = new GwebSearch();
  this.gwebsearch.setResultSetSize(GSearch.LARGE_RESULTSET);
  this.gwebsearch.setUserDefinedLabel('');
  this.gwebsearch.setLinkTarget(GSearch.LINK_TARGET_SELF);
  this.gwebsearch.setSiteRestriction(domain);

  this.gwebsearch.clearResults();
  this.gwebsearch.setSearchCompleteCallback(this, site_search.prototype.done);
  this.gwebsearch.execute(query);
}

site_search.prototype.done = function() {
  // set up the page
  this.page.innerHTML =
   <!-- '<div class="gsc-back"> [<a href="#" onclick="site_search_back();">' + -->
   <!-- '<< back to ' + document.title + '</a>] </div>' + -->
    '<div class="listingPrice">Results for <b><u>' + this.query + '</u></b>:</div>';

  // insert the search results
  results = this.gwebsearch.results;
  for (i = 0; i < results.length; i++) {
    // show the full URL, not just the domain. (this is an ugly brittle hack!)
    results[i].html.childNodes[2].innerHTML = results[i].unescapedUrl;
    this.page.appendChild(results[i].html);
  }

  if (results.length == 0)
    this.page.innerHTML += '<p>No results.</p>';

  // send it out into the world!
  this.page.appendChild(GSearch.getBranding());
  this.page.innerHTML += results_footer;
}

function site_search_back() {
  results = document.getElementById(results_div_id);

  old_page = document.getElementById('old' + results_div_id);
  old_page.id = results_div_id;
  old_page.style.display = '';

  results.parentNode.removeChild(results);
}
