/* order of operation:

	1.0 user gives focus to the search field
		1.1 focusSearchField() is called
	2.0 user types in something
		2.1 enterSubmit() is called
		2.2 enterSubmit() shows the search flyout
		2.3 if user hits the enter key validateSearch() is called
	3.0 user rolls over the flyout
		3.1 setFlyoutFocus() is called
	4.0 user clicks something in this flyout
		4.1 blurSearchField() is called because the searchField has lost focus
	5.0 user clicks elsewhere on the page
		5.1 blurSearchField() can be called again, if the searchField has lost focus
		5.2 setFlyoutFocus() is called, setting flyoutFocus = false;

*/

var initSearchValue = "Search";
var frmSearch;
var searchField;
var searchPopup;
var searchPopupInput;
var flyoutFocus = false;

function defineSearchField() {
	frmSearch = document.getElementById("searchForm") || "";
	searchField = frmSearch.strSearch;
	searchPopup = document.getElementById("searchPopup") || "";
	searchPopupInput = document.getElementById("currTypedSearchInput") || "";
}

function focusSearchField() {
	//we don't want to show the flyout here, because focus to the search field may be done on page load by the browser.
	if(!frmSearch) {
		defineSearchField();
	}
	if(searchField.value == initSearchValue) {
		searchField.value = "";
	}
}

function blurSearchField() {
	if(searchField.value == "") {
		searchField.value = initSearchValue;
	}
	// if the search flyout is shown, we need to hide it, as they have left focus on the search field.
	// must do it on delay because this onBlur gets hit before functions regarding interactivity of the search flyout.
	if(searchPopup.style.display == "block") {
		setTimeout("hideFlyoutOnBlur()", 200);
	}
}

function hideFlyoutOnBlur() {
	if(!flyoutFocus) {
		searchPopup.style.display = "none";
	}
}

//setFlyoutFocus() called onMouseOver of the flyout div, and onMouseOff
function setFlyoutFocus(isRolledOver) {
	flyoutFocus = isRolledOver;
	if(flyoutFocus) {
		if(searchPopup.style.display != "block") {
			searchPopup.style.display = "block";
		}
	} else {
		searchPopup.style.display = "none";
	}
}

function validateSearch(isFromClick) {
	if(isFromClick) {
		defineSearchField();
	}
	if(searchField.value == "" || searchField.value == " " || searchField.value == null || searchField.value == initSearchValue) {
		alert("Please enter a search term");
	}else{
		frmSearch.submit();
	}
}

function enterSubmit(thisEvent) {
	var keycode;
			
	if (window.event) {
		//ie
		keycode = window.event.keyCode;
	} else if (thisEvent) {
		//other
		keycode = thisEvent.which;
	}
	
	searchPopupInput.innerHTML = "Search for '"+ searchField.value +"' in:";
	if(searchPopup.style.display != "block") {
		searchPopup.style.display = "block";
	}
		
	if(keycode == 13) {
		validateSearch(false);
	}
}