var g_cache_whole_list = false;
var g_max_cache_entries = 1000;
var g_query_prev = null;
var oParsedResponseGlobal = null;

var g_staged = (document.getElementById("sp_staged") ? document.getElementById("sp_staged").value : 0);

function init_cache_whole_list_mode()
{
	acObj.queryMatchSubset = true;
	acObj.applyLocalFilter = true;

	var g_query_prev = null;

	acObj.filterResults = function(sQuery, oFullResponse, oParsedResponse, oCallback) {
		sQuery = document.getElementById("q").value;

		if (oParsedResponseGlobal == null)
			oParsedResponseGlobal = YAHOO.widget.AutoComplete._cloneObject(oParsedResponse);

		//alert("filterResults() sQuery='" + sQuery + "'");

		// Only if a query string is available to match against
		if (sQuery && sQuery !== "") {
			// Reset cache to the entire word-list if they back-spaced and changed the query
			if (oParsedResponseGlobal != null && (g_query_prev == null || g_query_prev.length > sQuery.length || g_query_prev.valueOf() != sQuery.substr(0, g_query_prev.length))) {
				//alert("Resetting client cache to entire word list!");
				oParsedResponse = oParsedResponseGlobal;
			}

			// Remember the previous query.
			g_query_prev = YAHOO.widget.AutoComplete._cloneObject(sQuery);

			// First make a copy of the oParseResponse
			oParsedResponse = YAHOO.widget.AutoComplete._cloneObject(oParsedResponse);

			var regExpObj = new RegExp("(?:^|^.*[ ])" + sQuery , "i");

			var oAC = oCallback.scope,
				oDS = this,
				allResults = oParsedResponse.results, // the array of results
				filteredResults = []; // container for filtered results

			// Loop through each result object...
			for (var i = allResults.length-1; i >= 0; i--) {
				var oResult = allResults[i];

				// Grab the data to match against from the result object...
				var sResult = null;

				// Result object is a simple string already
				if (YAHOO.lang.isString(oResult)) {
					sResult = oResult;
				}
				// Result object is an array of strings
				else if (YAHOO.lang.isArray(oResult)) {
					sResult = oResult[0];
				}
				// Result object is an object literal of strings
				else if (this.responseSchema.fields) {
					var key = this.responseSchema.fields[0].key || this.responseSchema.fields[0];
					sResult = oResult[key];
				}
				// Backwards compatibility
				else if (this.key) {
					sResult = oResult[this.key];
				}

				if (YAHOO.lang.isString(sResult)) {
					if (regExpObj.test(sResult)) {
						//alert("'" + sResult + "': MATCH");
						filteredResults.unshift(oResult);
					}
					else {
						//alert("'" + sResult + "': NO!");
					}
    			}
			}
			oParsedResponse.results = filteredResults;
		}
		return oParsedResponse;
	};
}


function init_cache_mode()
{
	var acDSGetLineCount = new YAHOO.util.ScriptNodeDataSource( (g_staged ? "http://content.atomz.com/autocomplete/sp10/04/15/02-stage/" : "http://content.atomz.com/autocomplete/sp10/04/15/02/"));
		
	acDSGetLineCount.responseSchema = {
		resultsList: "ResultSet.Result",
		fields: ["line_count"]
	};

	// Called asynchronusly!
	acDSGetLineCount.handleResponse = function(oRequest, oRawResponse, oCallback, oCaller, tId) {
		var line_count = oRawResponse;
		g_cache_whole_list = (line_count != null && line_count <= g_max_cache_entries);

		if (g_cache_whole_list)
			init_cache_whole_list_mode();	
	}
	// Trigger asynchronus request / response.
	acDSGetLineCount.sendRequest("?get_line_count=1", null);
}


// Data source
var acDataSource = new YAHOO.util.ScriptNodeDataSource( (g_staged ? "http://content.atomz.com/autocomplete/sp10/04/15/02-stage/" : "http://content.atomz.com/autocomplete/sp10/04/15/02/"));
acDataSource.asyncMode="ignoreStaleResponses";
acDataSource.maxCacheEntries = g_max_cache_entries;
acDataSource.responseSchema = {
	resultsList: "ResultSet.Result",
	fields: ["phrase"]
};

// AutoComplete object
var acObj = new YAHOO.widget.AutoComplete("q", "autocomplete", acDataSource);
acObj.queryDelay = 0.2;
acObj.useShadow = false;
acObj.autoHighlight = false;
acObj.minQueryLength = 1;
acObj.maxResultsDisplayed = 10;
acObj.animVert = false;
acObj.queryQuestionMark = true;
acObj.resultTypeList = false;

init_cache_mode();

acObj.formatResult = function(oResultData, sQuery, sResultMatch) {
	var sMarkup = (sResultMatch) ? sResultMatch : "";
	return sMarkup;
};

acObj.generateRequest = function(q) {
	if (g_cache_whole_list) {
		return "?get_all=1";
	}
	else {
        return "?query=" + q + "&max_results=" + acObj.maxResultsDisplayed;
	}
};

var acSelectHandler = function(){window.location.href ="http://search.intheswim.com/?q="+document.getElementById('q').value;};
acObj.itemSelectEvent.subscribe(acSelectHandler);
