/* 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 = 'main_middle'
var results_header = '<div class="ajax_search_results">';
var results_footer = '</div>';

var searching_message = '<span class="ajax-message">Searching...</span>'

function fillBackLink() {
	if ($("#main_middle h1 :not(img)").html()) {
		return $("#main_middle h1 :not(img)").html();
	}
	else return "Home";
}

function site_search(domain, query) {
  // must not be empty
		search_error = document.getElementById('heading_search_error');
	if (!query.match('\\S')) {
		search_error.innerHTML = 'Please enter search criteria.';
    return;
  }
  this.query = query;

	closePopup();
//	buildWimpyObject();
	
  // save the current page
	$('#main_middle').hide();
	
	
	// tell the user we're searching
	$('#main_search').html('Searching...').show();
	
  this.page = document.getElementById('main_search');
  this.page.id = "main_search";

  // 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-title"><h1><img src="/images/orange_headline_arrow.gif" style="border-width:0px;" /><strong>search</strong>results</h1><a class="search_backLink" href="#" onclick="closePopup();return false;"> Back to ' +  fillBackLink() + ' </a><br /><br /> </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) {
		srchHold = $('#query').val();
		this.page.innerHTML +=
			'<p class="search_noresults">Your search - <strong>'+srchHold+'</strong> - did not match any documents.<br /><br />' +
			'Suggestions:<br />' +
			'<ul class="search_noresults"><li>Make sure all words are spelled correctly.</li>' +
			'<li>Try different keywords.</li>' +
			'<li>Try more general keywords.</li></ul></p>';
	}

	// clear input box
	$("#query").val('');
	// send it out into the world!
	this.page.innerHTML += '<br />';
  this.page.appendChild(GSearch.getBranding());
  this.page.innerHTML += results_footer;
}
