// initialize Google services
google.setOnLoadCallback(onLoad);
google.load("search", "1");

var googleReady;
var yahooReady;
var googleResults;
var yahooResults;


/**
* Initialize the raw search service provided by the Google AJAX Search API
* as well as the Yahoo! search object provided by the Yahoo! Search API
*/
function onLoad()
{
	// initialize the Google and Yahoo! search services
	new RawSearchControl();			// Google
	obj.init();						// Yahoo!
	
	// initialize the ready states for the Google and Yahoo! result indicators
	window.googleReady = 0;
	window.yahooReady = 0;
	
	// initialize the search box - empty it out and give it focus
	var searchBox = document.getElementById("searchInput");
	searchBox.value = '';
	searchBox.focus();
}  // onLoad

/**
* Prepare search service for searching and returning results
*/
function RawSearchControl()
{
	// latch on to key portions of the document
	searchForms = document.getElementById("searchForm");
	resultSet = document.getElementById("results");
	
	// wire up a raw GwebSearch searcher
	searcher = new GwebSearch();
	searcher.setResultSetSize(GSearch.LARGE_RESULTSET);
	searcher.setNoHtmlGeneration();
	searcher.setSearchCompleteCallback(this, RawSearchControl.prototype.searchComplete, [searcher]);
	
	// detect external searches
	if (true)
	{	
		obj.init();
		searcher.execute(searchForms.searchInput.value);
		obj.pingSearch();
	}  // if statement
}  // RawSearchControl

/**
* Perform actual search.  Calls both Google and Yahoo! search APIs to execute search.  Also navigates
* hidden frame to PHP page to archive search query.
*/
function searchIt(event)
{
	// prevent default submit action
	event.preventDefault();
	
	// navigate hidden frame to archive search query
	frames['hiddenFrame'].location.href = "./searchCounter.php?searchQuery=" + searchForms.searchInput.value;
	
	// reset search indicators
	window.googleReady = 0;
	window.yahooReady = 0;
	
	// execute Google search
	searcher.execute(searchForms.searchInput.value);
	
	// execute Yahoo! search
	document.getElementById('q').value = searchForms.searchInput.value;
	obj.pingSearch();
	
	return false;
}  // searchIt

/**
* Called when search is completed.  Changes ready-indicator to indicate that Google's results
* are ready.  If Yahoo!'s results are ready as well, then display them both.
*/
RawSearchControl.prototype.searchComplete = function(searcher)
{
	window.googleResults = searcher.results;
	window.googleReady = 1;
	this.clearResults();
	
	if (window.yahooReady && window.googleReady)
	{
		displayResults();
		Ext.example.msg('', '<center>Results provided to you by <a href="http://www.yahoo.com"><img src="./images/yahoo_logo_small.png" align="middle"/></a>&nbsp;&nbsp;&nbsp;and&nbsp;&nbsp;<a href="http://www.google.com"><img src="./images/google_logo_small.png" align="middle"/></a></center>');
	}  // if statement
}  // searchComplete

/**
* Clears out any old search results from the page.
*/
RawSearchControl.prototype.clearResults = function()
{
	removeChildren(resultSet);
}  // clearResults

/**
* Static DOM Helper Functions
*/
function removeChildren(parent)
{
	while (parent.firstChild)
	{
		parent.removeChild(parent.firstChild);
	}  // while loop
}  // removeChildren

function createDiv(opt_text, opt_className)
{
	var el = document.createElement("div");
	
	if (opt_text)
	{
		el.innerHTML = opt_text;
	}  // if statement
	
	if (opt_className)
	{
		el.className = opt_className;
	}  // if statement
	
	return el;
}  // createDiv

/**
* Displays actual search results obtained from both Google and Yahoo! searches.
*/
function displayResults()
{
	var googleIndex = 0;
	var yahooIndex = 0;
	
	for (var i = 0; i < 10; i++)
	{
		// process a Google search result
		if (Math.floor(Math.random()*2) == 0 && googleIndex < 5)
		{
			var result = googleResults[googleIndex];
			
			if (result)
			{
				result.content = result.content.replace(/\<.*?\>/g, ''); 
				div = createDiv("<font size='4'><u><a href='" + result.unescapedUrl + "' target='_blank'  onclick='return addPoint(\"Google\", \"" + result.unescapedUrl + "\")'>" + result.titleNoFormatting + "</a></u></font><br />" + result.content + "<br /><font color='green' size='2'>" + result.url + "</font><br />&nbsp;");
			}  // if statement
			else
			{
				div = createDiv("** failed to display Google result **");
			}  // else statement
			
			googleIndex++;
		}  // if statement
		// process a Yahoo! search result
		else
		{
			var result = yahooResults.ResultSet.Result[yahooIndex];
			
			if (result)
			{
				div = createDiv("<font size='4'><u><a href='" + result.Url + "' target='_blank' onclick='return addPoint(\"Yahoo!\", \"" + result.Url + "\")'>" + result.Title + "</a></u></font><br />" + result.Summary + "<br /><font color='green' size='2'>" + result.Url + "</font><br />&nbsp;");
			}  // if statement
			else
			{
				div = createDiv("** failed to display Yahoo! result ** ");
			}  // else statement
			
			yahooIndex++;
		}  // else statement
		
		resultSet.appendChild(div);
	}  // for loop
}  // displayResults

function quoteGenerator()
{
	var quotes = new Array("Search does a body good",
						   "Who are you?",
						   "&lt;insert random phrase here&gt;",
						   "Let the isolation cultivate your madness", 
						   "Time is of the essence",
						   "Who else watches LOST?",
						   "Doesn't work in IE and I don't really care",
						   "Master Chief says \"Drink your milk\"");

	return quotes[Math.floor(Math.random() * quotes.length)];
}  // quoteGenerator

function addPoint(clickProvider, clickLink)
{
	if (clickProvider == "Google")
	{
		alertIcon = "<center><img src='./images/google_logo_small.png'/></center>";
		alertMessage = "Link provided to you by <a href='http://www.google.com'>Google Inc.</a>";
	}  // if statement
	else
	{
		alertIcon = "<center><img src='./images/yahoo_logo_small.png'/></center>";
		alertMessage = "Link provided to you by <a href='http://www.yahoo.com'>Yahoo! Inc.</a>";
	}  // else statement
	
	Ext.MessageBox.alert(alertIcon, alertMessage, function()
		{
			//Ext.example.msg(alertIcon, '<center>Openeed link in new window</center>');
			
			document.clickForm.clickLink.value = clickLink;
			document.clickForm.clickProvider.value = clickProvider;
			document.clickForm.submit();
		}
	);
	
	// stop default click action
	return false;
}  // addPoint


var obj =
{
	init : function()
	{
		obj.q = document.getElementById('q');
		obj.b = document.getElementById('b');
		obj.r = document.getElementById('results');
	},
	
	pingSearch : function()
	{
		if (obj.q.value)
		{
			obj.s = document.createElement('script');
			obj.s.type ='text/javascript';
			obj.s.charset ='utf-8';
			obj.s.src = 'http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=aEt7gjrV34ER8dRjg11uSx3fV60STi_5VFOQiNQpCrEsknSgLFz83MREjY_gd53CbJZYTA--&output=json&callback=obj.pongSearch&query=' + obj.q.value;
			document.getElementsByTagName('head')[0].appendChild(obj.s);
		}  // if statement
	},
	
	pongSearch : function(z)
	{
		window.yahooResults = z;
		window.yahooReady = 1;
		
		if (window.yahooReady && window.googleReady)
		{
			displayResults();
			Ext.example.msg('', '<center>Results provided to you by <a href="http://www.google.com"><img src="./images/google_logo_small.png" align="middle"/></a>&nbsp;&nbsp;&nbsp;and&nbsp;&nbsp;<a href="http://www.yahoo.com"><img src="./images/yahoo_logo_small.png" align="middle"/></a></center>');
		}  // if statement
	}
};
