var jQueryScriptOutputted = false;
initJQuery();

function initJQuery() {
    // if the jQuery object isn't available
	if (typeof (jQuery) == 'undefined') {
		if (!jQueryScriptOutputted) {
			// only output the script once..
			jQueryScriptOutputted = true;

			// output the script (load it from google api)
			var s;
			s = document.createElement('script');
			s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
			s.setAttribute('type', 'text/javascript');
			document.getElementsByTagName('head')[0].appendChild(s);

			s = document.createElement('script');
			s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js');
			s.setAttribute('type', 'text/javascript');
			document.getElementsByTagName('head')[0].appendChild(s);

			s = document.createElement('link');
			s.setAttribute('href', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css');
			s.setAttribute('type', 'text/css');
			s.setAttribute('rel', 'Stylesheet');
			document.getElementsByTagName('head')[0].appendChild(s);
		}
		setTimeout("initJQuery()", 50);
	} else {

		$(function() {
			// do anything that needs to be done on document.ready
			var changed;
			var cache = {};
			
			$(document).ready(function() {
				// Setup the search form
				if (!$("#SearchBox").size()) {
					$("input[name='s']").attr('id', 'SearchBox');
				}
				$("#SearchForm").removeAttr('id');
				$("#SearchBox").parents('form').attr('id', 'SearchForm');
				
				$("#SearchBox").autocomplete({
					source: function(request, response) {
						var urlPath = 'test';
						if (typeof(searchPath) === 'undefined') {
							urlPath = '/words/';
						} else {
							urlPath = searchPath;
						}
						if (request.term in cache) {
							response(cache[request.term]);
							return;
						}
						$.ajax({
							url: urlPath + 'ajax-search.php',
							dataType: 'json',
							data: request,
							success: function(data) {
								cache[request.term] = data;
								response(data);
							}
						});
					},
					select: function(event, ui) {
						changed = true;
					},
					close: function(event, ui) {
						if (changed) {
							$("#SearchForm").submit();
						}
					}
				});
			});
		});
	}
            
}
