
/* needed for autosuggest -- included in later Dojo versions, so remove when updating */
dojo.keys={BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,META:dojo.isSafari?91:224,PAUSE:19,CAPS_LOCK:20,ESCAPE:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT_ARROW:37,UP_ARROW:38,RIGHT_ARROW:39,DOWN_ARROW:40,INSERT:45,DELETE:46,HELP:47,LEFT_WINDOW:91,RIGHT_WINDOW:92,SELECT:93,NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_PLUS:107,NUMPAD_ENTER:108,NUMPAD_MINUS:109,NUMPAD_PERIOD:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,NUM_LOCK:144,SCROLL_LOCK:145,copyKey:dojo.isMac&&!dojo.isAIR?(dojo.isSafari?91:224):17};

/** This variable indicates whether the browser used is Internet Explorer or not. */
var isIE = (document.all) ? true : false;

/** Initializes the variable to false. **/
	var correctBrowser = false;

/** 
 * This variable indicates whether a request has been submitted or not.
 * The value is initialized to true and resets to false on full page load.
 */
var requestSubmitted = true;

/** 
 * This variable stores the id of the element (ex: button/link) which the user clicked.
 * This id is set when the user clicks an element which triggers an Ajax request.
 */
var currentId = "";

/** 
 * This variable keeps track of the number of active ajax requests currently running on the page 
 * The value is initialized to 0.
 */
var numAjaxRequests = 0;

/** 
 * This variable controls the timer handler before triggering the autoSuggest.  If the user types fast, intermittent requests will be cancelled.
 * The value is initialized to -1.
 */
var autoSuggestTimer = -1;

/** 
 * This variable controls the delay of the timer in milliseconds between the keystrokes before firing the search request.
 * The value is initialized to 250.
 */
var autoSuggestKeystrokeDelay = 250;

/** 
 * This variable indicates whether or not the user is hovering over the autoSuggest results popup display.
 * The value is initialized to false.
 */
var autoSuggestHover = false;

/** 
 * This variable stores the old search term used in the auto suggest search box
 * The value is initialized to empty string.
 */
var autoSuggestPreviousTerm = "";

/** 
 * This variable stores the URL of currently selected static autosuggest recommendation
 * The value is initialized to empty string.
 */
var autoSuggestURL = "";

/** 
 * This variable stores the index of the selected auto suggestion item when using up/down arrow keys.
 * The value is initialized to -1.
 */
var autoSelectOption = -1;

/** 
 * This variable stores the index offset of the first previous history term
 * The value is initialized to -1.
 */
var historyIndex = -1;

/** 
 * This variable indicates whether a the cached suggestions have been retrieved.
 * The value is initialized to false.
 */
var retrievedCachedSuggestions = false;

/** 
 * This variable sets the total number of static autosuggest recommendations used for each static category/grouping.
 * The value is initialized to 4.
 */
var TOTAL_SUGGESTED = 4;

/** 
 * This variable sets the total number of previous search history terms.
 * The value is initialized to 2.
 */
var TOTAL_HISTORY = 2;

/** 
 * This variable controls when to trigger the auto suggest box.  The number of characters greater than this threshold will trigger the auto suggest functionality.
 * The static/cached auto suggest will be performed if this threshold is exceeded.
 * The value is initialized to 1.
 */
var AUTOSUGGEST_THRESHOLD = 1;

/** 
 * This variable controls when to trigger the dynamic auto suggest.  The number of characters greater than this threshold will trigger the request for keyword search.
 * The static/cached auto suggest will be be displayed if the characters exceed the above config parameter, but exceeding this threshold will additionally perform the dynamic search to add to the results in the static/cached results.
 * This value should be greater or equal than the AUTOSUGGEST_THRESHOLD, as the dynamic autosuggest is secondary to the static/cached auto suggest.
 * The value is initialized to 1.
 */
var DYNAMIC_AUTOSUGGEST_THRESHOLD = 1;

/** 
 * This variable is an internal constant used in the element ID's generated in the autosuggest content.
 * The value is initialized to 1000.
 */
var CACHED_AUTOSUGGEST_OFFSET = 1000;


/**
* This function gets a cookie
* @param {String} c the name of the cookie to be get.
*/
function getCookie(c) {
	var cookies = document.cookie.split(";");
	for (var i = 0; i < cookies.length; i++) {
		var index = cookies[i].indexOf("=");
		var name = cookies[i].substr(0,index);
		name = name.replace(/^\s+|\s+$/g,"");
		if (name == c) {
			return unescape(cookies[i].substr(index + 1));
		}
	}
}

/**
 * Clears the Search term string displayed in Simple Search field.
 */
function clearSearchField() {
	searchText = document.getElementById("SearchBox").value;
	if(searchText == document.getElementById("searchTextHolder").innerHTML){
		document.getElementById("SearchBox").value = "";
	}
	else{
		document.getElementById("SearchBox").select();
		showAutoSuggestIfResults();
		autoSuggestHover = false;
	}
}

/**
 * Displays the Search term string in Simple Search field.
 */
function fillSearchField() {
	if (document.getElementById("SearchBox").value == "") {
		document.getElementById("SearchBox").value = document.getElementById("searchTextHolder").innerHTML;
	}
	// hide the search box results
	if(!autoSuggestHover) {
		showAutoSuggest(false);
	}
}



function doDynamicAutoSuggest(url, searchTerm, showHeader) {		
	// if pending autosuggest triggered, cancel it.
	if(autoSuggestTimer != -1) {
		clearTimeout(autoSuggestTimer);
		autoSuggestTimer = -1;
	}

	// call the auto suggest
	autoSuggestTimer = setTimeout(function() {
		wc.render.getRefreshControllerById("AutoSuggestDisplayController").url = url + "&term=" + escape(searchTerm) + "&showHeader=" + showHeader;
		wc.render.updateContext("AutoSuggest_Context", {});
		autoSuggestTimer = -1;
	}, autoSuggestKeystrokeDelay);
}


function showAutoSuggest(display) {
	var autoSuggest_Result_div = document.getElementById("autoSuggest_Result_div");
	if (dojo.isIE < 7){
		var autoSuggest_content_div = document.getElementById("autoSuggest_content_div");
		var autoSuggestDropDownIFrame = document.getElementById("autoSuggestDropDownIFrame");
	}
	
	if(autoSuggest_Result_div != null && autoSuggest_Result_div != 'undefined') {
		if(display) {
			autoSuggest_Result_div.style.display = "block";
			if (dojo.isIE < 7) {
				autoSuggestDropDownIFrame.style.height = autoSuggest_content_div.scrollHeight;
				autoSuggestDropDownIFrame.style.display = "block";
			}
		}
		else {
			if (dojo.isIE < 7) {
				autoSuggestDropDownIFrame.style.display = "none";
				autoSuggestDropDownIFrame.style.height = 0;
			}
			autoSuggest_Result_div.style.display = "none";
		}
	}
}

function showAutoSuggestIfResults() {
	// if no results, hide the autosuggest box
	if(typeof(staticContent) != "undefined" && document.getElementById(staticContentSectionDiv[0]).innerHTML == "" && document.getElementById("autoSuggestHistory").innerHTML == "" && document.getElementById("dynamicAutoSuggestTotalResults") == null) {
		showAutoSuggest(false);
	}
	else if(document.getElementById("SearchBox").value.length <= AUTOSUGGEST_THRESHOLD) {
		showAutoSuggest(false);
	}
	else {
		showAutoSuggest(true);
	}
}

function selectAutoSuggest(term) {
	var searchBox = document.getElementById("SearchBox");
	searchBox.value = term;
	searchBox.focus();
	autoSuggestPreviousTerm = term;
	requestSubmitted = false;
	submitSpecifiedForm(document.CatalogSearchForm)
}

/**
 * Submits the form parameter.
 * Requires a form element to be passed in and submits form with its inputs.
 * Used for Non-ajax calls that requires multiple clicks handling.
 *
 * @param {element} form The form to be submitted.
 */
function submitSpecifiedForm(form) {
	if(!submitRequest()){
		return;
	}
	form.submit();
}

function submitRequest() {
	if(!requestSubmitted) {
		requestSubmitted  = true;
		return true;
	}
	return false;
}
 

function highLightSelection(state, index) {
	var selection = document.getElementById("autoSelectOption_" + index);
	if(selection != null && selection != 'undefined') {
		if(state) {
			selection.className = "autoSuggestSelected";
			var searchBox = document.getElementById("SearchBox");
			searchBox.setAttribute("aria-activedescendant", "suggestionItem_" + index);
			var totalDynamicResults = document.getElementById("dynamicAutoSuggestTotalResults");
			if((totalDynamicResults != null && totalDynamicResults != 'undefined' && index < totalDynamicResults.value) || (index >= historyIndex)) {
				searchBox.value = selection.title;
				autoSuggestPreviousTerm = selection.title;
				autoSuggestURL = "";
			}
			else {
				autoSuggestURL = selection.href;
			}
		}
		else {
			selection.className = "";
		}
		return true;
	}
	else {
		return false;
	}
}

function enableAutoSelect(index) {
	highLightSelection(false, autoSelectOption);
	var item = document.getElementById('autoSelectOption_' + index);
	item.className = "autoSuggestSelected";
	autoSelectOption = index;
}

function resetAutoSuggestKeyword() {
	var originalKeyedSearchTerm = document.getElementById("autoSuggestOriginalTerm");
	if(originalKeyedSearchTerm != null && originalKeyedSearchTerm != 'undefined') {
		var searchBox = document.getElementById("SearchBox");
		searchBox.value = originalKeyedSearchTerm.value;
		autoSuggestPreviousTerm = originalKeyedSearchTerm.value;
	}
}

function clearAutoSuggestResults() {
	// clear the static search results.
	for (var i = 0; i < staticContent.length; i++) {
		document.getElementById(staticContentSectionDiv[i]).innerHTML = "";
	}
	autoSuggestPreviousTerm = "";
	autoSuggestURL = "";
	// clear the dynamic search results;
	document.getElementById("autoSuggestDynamic_Result_div").innerHTML = "";
	showAutoSuggest(false);
}

function doAutoSuggest(event, url, searchTerm) {
	if(searchTerm.length <= AUTOSUGGEST_THRESHOLD ) {
		showAutoSuggest(false);
	}

	if(event.keyCode == dojo.keys.ENTER) {
		return;
	}

	if(event.keyCode == dojo.keys.TAB) {
		autoSuggestHover = true;
		return;
	}

	if(event.keyCode == dojo.keys.ESCAPE) {
		showAutoSuggest(false);
		return;
	}

	if(event.keyCode == dojo.keys.UP_ARROW) {
		var totalDynamicResults = document.getElementById("dynamicAutoSuggestTotalResults");
		if(highLightSelection(true, autoSelectOption-1)) {
			highLightSelection(false, autoSelectOption);
			if(autoSelectOption == historyIndex) {
				resetAutoSuggestKeyword();
			}
			autoSelectOption--;
		}
		else if(autoSelectOption == CACHED_AUTOSUGGEST_OFFSET && totalDynamicResults != null && totalDynamicResults != 'undefined') {
			highLightSelection(false, CACHED_AUTOSUGGEST_OFFSET);		
			autoSelectOption = totalDynamicResults.value-1;
			highLightSelection(true, autoSelectOption);
		}
		else {
			// up arrow back to the very top
			highLightSelection(false, autoSelectOption);
			autoSelectOption = -1;
			var originalKeyedSearchTerm = document.getElementById("autoSuggestOriginalTerm");
			resetAutoSuggestKeyword();
		}
		return;
	}

	if(event.keyCode == dojo.keys.DOWN_ARROW) {
		if(highLightSelection(true, autoSelectOption+1)) {
			highLightSelection(false, autoSelectOption);
			autoSelectOption++;
		}
		else if(autoSelectOption < CACHED_AUTOSUGGEST_OFFSET && highLightSelection(true, CACHED_AUTOSUGGEST_OFFSET)) {
			// down arrow into the cached autosuggest section
			highLightSelection(false, autoSelectOption);
			autoSelectOption = CACHED_AUTOSUGGEST_OFFSET;
			resetAutoSuggestKeyword();
		}
		return;
	}

	if(searchTerm.length > AUTOSUGGEST_THRESHOLD && searchTerm == autoSuggestPreviousTerm) {
		return;
	}
	else {
		autoSuggestPreviousTerm = searchTerm;
	}

	if(searchTerm.length <= AUTOSUGGEST_THRESHOLD) {
		return;
	};

	// cancel the dynamic search if one is pending
	if(autoSuggestTimer != -1) {
		clearTimeout(autoSuggestTimer);
		autoSuggestTimer = -1;
	}

	if(searchTerm != "") {
		autoSelectOption = -1;
		var hasResults = doStaticAutoSuggest(searchTerm);
		if(searchTerm.length > DYNAMIC_AUTOSUGGEST_THRESHOLD) {
			var showHeader = true; // hasResults;
			doDynamicAutoSuggest(url, searchTerm, showHeader);
		}
		else {
			// clear the dynamic results
			document.getElementById("autoSuggestDynamic_Result_div").innerHTML = "";
		}
	}
	else {
		clearAutoSuggestResults();
	}
}


function doStaticAutoSuggest(searchTerm) {
	var resultList = ["", "", "", "", "", ""];
	var emptyCell = 0;
	var searchTermLower = searchTerm.toLowerCase();
	var listCount = CACHED_AUTOSUGGEST_OFFSET;

	for(var i = 0; i < staticContent.length; i++) {
		var count = 0;
		for(var j = 0; j < staticContent[i].length; j++) {
			var searchName = staticContent[i][j][0];
			var searchURL = staticContent[i][j][1];
			var displayName = staticContent[i][j][2];
			var index = searchName.toLowerCase().indexOf(searchTermLower);
			if(index != -1) {
				var displayIndex = index + displayName.length - searchName.length;
				resultList[i] = resultList[i] + "<li id='suggestionItem_" + listCount + "' role='listitem' tabindex='-1'><a id='autoSelectOption_" + listCount + "' title='" + displayName + "' onmouseout='this.className=\"\"; autoSuggestURL=\"\";' onmouseover='enableAutoSelect(" + listCount + "); autoSuggestURL=this.href;' href=\"" + searchURL + "\">" + displayName.substr(0, displayIndex) + "<strong>" + displayName.substr(displayIndex, searchTerm.length) + "</strong>" + displayName.substr(displayIndex + searchTerm.length) + "</a></li>";
				count++;
				listCount++;
				if(count >= TOTAL_SUGGESTED) {
					break;
				}
			}
		}
	}

	for (var i = 0; i < staticContent.length; i++) {
		document.getElementById(staticContentSectionDiv[i]).innerHTML = "";
		if(resultList[i] != "") {
			document.getElementById(staticContentSectionDiv[emptyCell]).innerHTML = "<div class='results'><div class='heading'>" + staticContentHeaders[i] + "</div><ul>" + resultList[i] + "</ul></div>";
			emptyCell++;
		}
	}

	var historyList = "";
	var searchHistorySection = document.getElementById("autoSuggestHistory");
	searchHistorySection.innerHTML = "";
	var historyArray = new Array();
	historyIndex = listCount;

	var searchHistoryCookie = getCookie("searchTermHistory");
	if(typeof(searchHistoryCookie) != 'undefined') {
		var termsArray = searchHistoryCookie.split("|");
		var count = 0;
		for(var i = termsArray.length - 1; i > 0; i--) {
			var theTerm = termsArray[i];
			var theLowerTerm = theTerm.toLowerCase();
			if(theLowerTerm.match("^"+searchTermLower) == searchTermLower) {
				var repeatedTerm = false;
				for(var j = 0; j < historyArray.length; j++) {
					if(historyArray[j] == theLowerTerm) {
						repeatedTerm = true;
						break;
					}
				}
				if(!repeatedTerm) {
					historyList = historyList + "<li id='suggestionItem_" + listCount + "' role='listitem' tabindex='-1'><a href='#' onmouseout='this.className=\"\"' onmouseover='enableAutoSelect(" + listCount + ");' onclick='selectAutoSuggest(this.title); return false;' title=\"" + theTerm + "\" id='autoSelectOption_" + listCount+ "'><strong>" + searchTerm + "</strong>" + theTerm.substring(searchTerm.length, theTerm.length) + "</a></li>";
					historyArray.push(theLowerTerm);
					count++;
					listCount++;
					if(count >= TOTAL_HISTORY) {
						break;
					}
				}
			}
		}
	}


	if(historyList != "") {
		searchHistorySection.innerHTML = "<div class='results'><div class='heading'>" + staticContentHeaderHistory + "</div><ul>" + historyList + "</ul></div>";
		emptyCell++;
	}

	if(emptyCell > 0) {
		showAutoSuggest(true);
		return true;
	}

	return false;
}

function retrieveCachedSuggestions(url) {
	if(!retrievedCachedSuggestions) {
		wc.render.getRefreshControllerById("AutoSuggestCachedSuggestionsController").url = url;
		wc.render.updateContext("CachedSuggestions_Context", {});
	}
}

