// setup searchSuggest Dojo combobox on load
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileReadStore");
dojo.addOnLoad(function() {
	var testMode = false;
	var testJSON = {"suggestionGroups":[{"indexName":"1keywords","indexTitle":"1keywords","suggestions":[{"nrResults":101074,"searchterm":"kids bags"},{"nrResults":101074,"searchterm":"kids bed"},{"nrResults":101074,"searchterm":"kids bridesmaids"},{"nrResults":101074,"searchterm":"kids dress"},{"nrResults":101074,"searchterm":"kids hat"},{"nrResults":101074,"searchterm":"kids high heels"},{"nrResults":101074,"searchterm":"kids pineapple"},{"nrResults":101074,"searchterm":"kids pyjamas"},{"nrResults":101074,"searchterm":"kids sale"},{"nrResults":101074,"searchterm":"kids socks"}]}]};
	var blankStoreData = {identifier : 'abbr',label: 'searchterm', items : "" };
	
	var stateStore = new dojo.data.ItemFileReadStore({
	    data : 	{identifier: 'abbr',
		label: 'searchterm',
		items: "" }
	});
	var filteringSelect = new dijit.form.ComboBox({
	    id: "searchSuggestSelect",
	    name: "txt",
	    store: stateStore,
	    searchAttr: "searchterm"
	},
	"searchSuggestSelect");
	
	dojo.connect(dijit.byId("searchSuggestSelect"), "onKeyDown", function(evt) {
		// The following code allows the search form to be submitted when enter
		// is pressed and the dropdown isnt showing. This code would not be needed if
		// dojo 1.5 or greater was used as the combobox dijit will do this automatically
		if ((evt.keyCode == 13) && !(this._isShowingNow)){
			submitSearch();
		}
	});
	
	// function to run on keyUp event of combobox
	dojo.connect(dijit.byId("searchSuggestSelect"), "onKeyUp", function(evt) {
		if (!testMode && isSSEnabled && isValidKey(evt.keyCode)){
			changeDataStore(blankStoreData);
			var searchStr = this.getDisplayedValue();
			var searchURL = retrieveSSURL();
			if (searchStr.length >= 3){
					 ajaxSearch(searchURL,searchStr);
			}  else {
				// reset combobox here
			}
		}

	});
	//use ajax to query if SS should be enabled 
	retrieveIsSSEnabled();
	// setup the data store with test data for test mode operation
	if(testMode && isSSEnabled){
		changeDataStore(transposeFredHopperJSON(testJSON));
	}

});

var isSSEnabled = false;


// helper function to transpose Reponse from FH search to format required by combobox data store
function transposeFredHopperJSON(fhJSON){
	var filterData = {identifier : 'abbr',label: 'searchterm', items : "" };
	var items = new Array();
	if (fhJSON.suggestionGroups[0] != null){
		for (x in fhJSON.suggestionGroups[0].suggestions){
			var anItem = fhJSON.suggestionGroups[0].suggestions[x];
			items.push({abbr: x + "-" + anItem.nrResults,searchterm: anItem.searchterm});
		}
		filterData.items = items;
	}
	return filterData;
}

// helper function to determine if the cursor arrows or enter has been pressed
function isValidKey(keyCode){
	if (keyCode == 13 || (keyCode >= 37 && keyCode <=40)){
		return false;
	} else {
		return true;
	}
}

// helper function to show the current contents of the combobox data store
function showStore(){
	var theStore = dijit.byId('searchSuggestSelect').store;
	alert(JSON.stringify(theStore._jsonData));
}

// Update the Search Suggest combo box data store with the new contents
function changeDataStore(dataStoreContents) {
	var combo = dijit.byId('searchSuggestSelect')
	var newStore = new dojo.data.ItemFileReadStore({
	    data : dataStoreContents
	});
	combo.store = newStore;
}

// function used to send ajax search suggest url 
function ajaxSearch(searchURL,searchStr){
	// var searchURL = "http://localhost:9182/suggest/json?search=" + searchStr;
	var proxiedURL = '/webapp/wcs/stores/servlet/SearchSuggestProxy?jsonURL=' + escape(searchURL+searchStr);
	makeHttpRequest(proxiedURL, 'ajaxSearchCallback',false);
}

// call back function used when response recived from ajax search suggest url 
function ajaxSearchCallback(jsonResult){
	var err = null;
	var jsonObject = null;
	if (jsonResult != ""){
		try {
			jsonObject = eval('(' + jsonResult + ')');
		} catch (err) {
		// swallow the error
		}
	}
	if (jsonObject != null) {
		var theData = transposeFredHopperJSON(jsonObject);
		changeDataStore(theData);
		// force the popup to show when the datastore has changed somehow
		var combo = dijit.byId('searchSuggestSelect');
		combo._startSearch(""); 
	}
}

