$(document).ready(function() {
	// only search if query string is set
	var searchQuery = location.href.split('?')[1];

	if ( searchQuery != undefined )
	{
		// put our query back into the search box
		var myQuery = escape(getQueryKey('q'));
		myQuery = myQuery.replace(/\+/g, " ");
		myQuery = myQuery.replace(/\%20/g, " ");
		$('#query').val(myQuery);

		// prepare Options Object for AJAX request
		var options =
		{
			type:		'GET',
			url:		'search.php',
			data:		searchQuery,
			dataType: 	'xml',
			success:	processXml
		};

		$.ajax(options);
	}
	else
	{
		$("#searchcontrol").empty();
		$("#searchcontrol").append("<p><b>You must specify a search term. Use the search box above to try again.</b></p>");
	}
});

// look through XML to find out if data was accepted
function processXml(responseXML, statusText)
{
	// save searchcontrol into short var name
	var sc = $('#searchcontrol');

	// empty search control div
	sc.empty();

	// find <return_val> node in our XML doc
	var query = escape( $('Q', responseXML).text() );
	query = query.replace(/\+/g, " ");
	query = query.replace(/\%20/g, " ");

	// spelling suggestion
	if ( $('*', responseXML).index( $('Spelling', responseXML)[0] ) > -1 )
	{
		// parse out spelling suggestion
		var suggestion = $('Suggestion', responseXML).attr('q');
		var suggestiontext = $('Suggestion', responseXML).text();

		sc.append(
			'<p class="spelling">Did you mean: ' +
			'<a href="' + location.pathname + '?' +
			'cx=' + getQueryKey('cx') +
			'&client=' + getQueryKey('client') +
			'&output=' + getQueryKey('output') +
			'&q=' + suggestion + '">' +
			suggestiontext + '</a></p>'
		);
	}

	// if our XML doc <return_val> node contains number 0, go ahead and say thank you
	if ( $('*', responseXML).index( $('RES', responseXML)[0] ) > -1 )
	{
		// save result info into vars
		var max = $('M', responseXML).text();
		var start = $('RES', responseXML).attr('SN');
		var end = $('RES', responseXML).attr('EN');

		// write results list header
		sc.append('<p class="results">Results <b>' + start + '</b> - <b>' + end + '</b> of about <b>' + max + '</b> for <b>' + query + '</b></p>');
		//sc.append('<p class="results">Results <b>' + start + '</b> - <b>' + end + '</b> for <b>' + query + '</b></p>');

		// build results body code
		res = $('<div id="results"></div>');
		$('R', responseXML).each(function() 
		{
			// see if this is a PDF
			var mime = $(this).attr('MIME');
			if ( mime == 'application/pdf' )
			{
				var pdf = '<small>[PDF] </small>';
			}
			else
			{
				var pdf = '';
			}

			// save data for this result
			t = $(this).find('T').text();
			u = $(this).find('U').text();
			url = u.substring(7, u.length);
			ue = $(this).find('UE').text();
			s = $(this).find('S').text();

			// write result to results div
			res.append(
				'<div class="result">' +
				'<h3>' + pdf + '<a href="' + ue + '">' + t + '</a></h3>' +
				'<p>' + s + '<br />' +
				'<span class="anchor">' + url + '</span></p>' +
				'</div>'
			);
		});

		// write results body to document
		sc.append(res);

		if ( $('*', responseXML).index( $('NB', responseXML)[0] ) > -1 )
		{
			// paging links
			paging = $('<div id="paging"><span class="results">Results Page:</span><br /></div>');

			if ( $('*', responseXML).index( $('PU', responseXML)[0] ) > -1 )
			{
				pu = $('PU', responseXML).text();
				pulink = '<a href="' + location.pathname + '?' + pu.split('?')[1] + '">Previous</a>';
			}
			else
			{
				pulink = 'Previous';
			}

			if ( $('*', responseXML).index( $('NU', responseXML)[0] ) > -1 )
			{
				nu = $('NU', responseXML).text();
				nulink = '<a href="' + location.pathname + '?' + nu.split('?')[1] + '">Next</a>';
			}
			else
			{
				nulink = 'Next';
			}

			// append next and prev buttons
			paging.append('<span class="prev">' + pulink + '</span>&nbsp;|&nbsp;');
			paging.append('<span class="next">' + nulink + '</span>');

			// write paging to document
			sc.append(paging);
		}

		return false;
	}
	// otherwise, show data that needs to be corrected
	else
	{
		sc.append(
			'<h3>Your search - <b>' + query + '</b> - did not match any documents.</h3>' +
			'<p>Suggestions:' +
			'<ul>' +
			'<li>Make sure all words are spelled correctly.</li>' +
			'<li>Try different keywords.</li>' +
			'<li>Try more general keywords.</li>' +
			'</ul>'
		);

		return false;
	}
}

// retutn errror messages if we couldn't retrieve the XML
function handleError()
{
	alert('Error loading XML document. Please try again.');
	return false;
}

// return value from key in URL query string
function getQueryKey(searchKey)
{
	var url = location.href;
	var query = url.split("?");
	var pairs = query[1].split("&");

	var split, key, val, found = false;

	for ( var i = 0; i < pairs.length; i++ )
	{
		split = pairs[i].split("=");
		key = split[0];
		val = split[1];

		if ( key == searchKey )
		{
			found = val;
			found = unescape(found);
			found.replace(/\+/g, " ");
			found.replace(/\%20/g, " ");
			return found;
		}
	}

	if ( found == false )
	{
		return "";
	}
}

