/* 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 = 'google'
var results_header = '<div>';
var results_footer = '</div>';
var searching_message = '<p class="large loud">Suche &#8230;</p>'

function site_search(domain, query) {
  // must not be empty
  if (!query.match('\\S')) {
    alert('Bitte Begriff eingeben.');
    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 =  
  	'<h4>Ihre Suchergebnisse</h4>'
    +'<p class="right"><a href="#" onclick="site_search_back();" id="delete" title="Suchergebnisse löschen">löschen</a></p>' 
	+ '<p class="strapline">Ergebnisse f&#252;r &#8222;' + this.query + '&#8220;</p>';

  // 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>Leider nix gefunden!</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);
}
