// JavaScript Document
var displaySize = -1; //set to value of displaySize (how many results pop down at a time)
var menuLimit = -1; //set to -1 for no limit on max returnable results
var requireEnterOnSearch_WithDropDown = true; //require enter to initiate search (loose feedback, but may be required for large xml files)

var xmlDoc; //stores xmlDoc object
var xmlDropDown;
var start; //starting value in returned xpath nodes
var searchStr; //current search string
var searchTextParsed;
var menu;

var dropDownLimit = 10;
var GLOBAL_XML = 0;
var DROPDOWN_XML = 1;
var dropArr;
var currentDropDownIndex = -1;
var originalSearchText;
var dropDownVisible = false;
var mouseOverDropDown = false;
var curHash = parent.location.hash;

var d;
var t;

/**
This function is run on load.
It reads in the XML document.
*/

//setInterval('checkHash()',100);

function trim(thisText)
{
	thisText = thisText.replace(/^\s*/, "");
	thisText = thisText.replace(/\s*$/, "");
	return thisText;
}
/**
function checkHash()
{
	if(parent.location.hash != curHash)
	{
		//document.getElementById('searchText').value = parent.location.hash + "!=" + curHash;
		//alert(trim(parent.location.hash) + '!=' + curHash);
		loadPage();
	}
}

function updateHash(thisText)
{
	parent.location.hash = "q=" + thisText;
	curHash = "#q=" + thisText;
	//document.getElementById('hashCatch').name = 'q='+thisText;
	//document.location.href = '#q='+thisText;
}

function loadPage()
{
	parseURL();
	var searchText = getURL('q');
	if(searchText != null && searchText != "")
	{
		//alert("'"+searchText+"'");
		searchFor(searchText);
	}
	else
	{
		//alert('load entire page');
		clearResults();
		//curHash = parent.location.hash;
		//document.getElementById('onScreen').style.display = "none";
		//document.getElementById('everything').style.display = "";
		//document.title = "All " + resultTypeCap;
	}
}*/

function load()
{
	loading(true); //display loading text
	
	//document.getElementById('searchText').autocomplete = 'off';
	
	d = new Date();
	t = d.getTime();
	//xmlDoc = loadXMLDoc(xmlFileName); //+'?date='+t);	//make xmlDoc connection
	
	parseURL();
	var curCat = getURL('cat');

	if(curCat != null && curCat != "")
	{
		var curE = document.getElementById("Cat_"+curCat.replace(/\s/g,""));
		if(curE != null)
		{
			curE.style.cursor = "default";
			curE.style.fontWeight = "bold";
			curE.style.textDecoration = "none";
			curE.style.color = "#000";
		}
		else
		{
			parseSearch(curCat, GLOBAL_XML);
		}
	}
	
	if(requireEnterOnSearch_WithDropDown)
		xmlDropDown = loadXMLDoc(xmlDropDownName + '?date='+t);
	
	loading(false); //hide loading text
	
	//load query from linked page
	//loadPage();
}


/**
This function displays and then hides "loading..." on load

isLoading = boolean value for whether to show or hide text
*/
function loading(isLoading)
{
	if(isLoading)
	{
		document.getElementById('loading').innerHTML = "Loading ...";
		document.getElementById('loading').style.display = "";
	}
	else
	{
		document.getElementById('loading').style.display = "none";
	}
}


/**
This function parses the search text into an xpath

navBool = boolean value for whether to display full navigation (e.g. 1 2 3 >> or just 1 >>)
searchText = the searchText to parse
start = starting index for returned xpath nodes
*/
function subParse(searchText)
{
	searchText = searchText.replace(/[^A-Za-z0-9\s\-\.\(\)]/g, " ");
	
	return searchText
}
function parseSearch(searchText, sourceType)
{
	if(searchText != "")
	{	
		//using reg exp remove unwanted and save into an array
		//var parsed = searchText.replace(/\sand\s|^and\s|\sand$|^and$|\sor\s/g, " ");
					
		var parsed = searchText;
		
		if(sourceType == GLOBAL_XML)
		{
			parsed = parsed.replace(/\sand\s|\sor\s/g, " ");
			parsed = subParse(parsed);	
			
		}
		searchTextParsed = parsed;
		
		parsed = parsed.replace(/(\s){2,}/g, " ");
		parsed = parsed.split(" ");
		
		var whereStr = "";
		var curFields;
		
		if(sourceType == GLOBAL_XML)
		{
			whereStr = "//cat/entry[(";
			curFields = fields;
		}
		else
		{
			whereStr = "//e[(";
		    curFields = new Array('k');
		}
		
		var setBool = false;
		for(var i=0; i < parsed.length; i++)
		{
			if(parsed[i]!="")
			{
				if(setBool) { whereStr += ") and ("; } 
				//build search string here

				whereStr += toXpath(curFields,parsed[i].toLowerCase());
				setBool = true;
			}
		}
		whereStr += ")]";

		if(setBool)
		{
			if(sourceType == GLOBAL_XML)
			{
				if(xmlDoc == null)
					xmlDoc = loadXMLDoc(xmlFileName + '?date='+t);
			
				menu = getXpath(whereStr, menuLimit, xmlDoc);
				outputResults();
			}
			else
			{
				dropArr = getDropDownMenu(whereStr, dropDownLimit, xmlDropDown, searchTextParsed.toLowerCase());
				outputDropDown();
			}
		}
  	}
	else
		hideDropDown();
	
}


function setText(newText)
{
	document.getElementById('searchText').value = newText;
	document.getElementById('searchText').focus();
	hideDropDown();
}
function outputDropDown()
{
	//alert("drop down updated");
	
	if(dropArr.length > 0)
	{
		var curText = "";
		var resultText = "";
		
		for(var i = 0 ; i < dropArr.length; i ++)
		{
			curText = dropArr[i]; //.getElementsByTagName('k')[0].childNodes[0].nodeValue;
			resultText += "<div id='drop_"+i+"' style='padding-left: 20px; cursor:default' onmouseout='dropDown_mouseOut(this)' onmouseover='dropDown_mouseOver(this)'>" + curText + "</div>";
		}
		
		document.getElementById("dropDown").innerHTML = resultText;//topResults + otherResults;
		showDropDown();
	}
	else
		hideDropDown();
}

/**
This function converts an array of fields with a single keyword into an xpath that searches substrings ignoring case.

fields = array of fields in XML file to search
keyword = keyword to substring match in XML field contents
*/
function toXpath(fields, keyword)
{
	//alert('IE got here');
	var syntax = new String();

	//whereStr = "//cat/entry[contains(et, '" + parsed[0] + "')]";
	for(var i = 0; i<fields.length; i++)
	{
		if(i>0) syntax += " or ";
		  syntax += "contains(translate(" + fields[i] + ", 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'" + keyword + "')";
	}
	return syntax;
}
/**
function searchFor(searchStr)
{
	document.getElementById("searchText").value = searchStr;
	var searchText = document.getElementById("searchText").value
	originalSearchText = searchStr;
	parseSearch(searchText, GLOBAL_XML);
}*/
function clearResultsBtn()
{
	clearResults();
}
function clearResults()
{
	hideDropDown();
	document.getElementById("searchText").value = "";
	currentDropDownIndex = -1;
	originalSearchText = "";
	//document.getElementById("onScreen").style.display = 'none';
	//document.getElementById("everything").style.display = '';
	//updateHash("");
	//document.title = "All " + resultTypeCap;
	document.getElementById("searchText").focus();
}
/**
function searchText_onfocus(me)
{
	if(me.value != "")
	{
		currentDropDownIndex = -1;
		parseSearch(me.value, DROPDOWN_XML);
	}
}*/

/**
function updateHistory(newHash)
{
	document.getElementById('hashCatch').name = 'q='+newHash;
	document.location.href = '#q='+newHash;
}*/

function keyPress(e)
{
	var keynum;
	var searchText = document.getElementById("searchText").value;
	
	if(window.event) // IE
		keynum = e.keyCode;
	else if(e.which) // Netscape/Firefox/Opera
		keynum = e.which;
	
	if(keynum == "40")
	{
		if(dropDownVisible)
			goToNextDropDown();
		else
		{
			originalSearchText = searchText;
			parseSearch(searchText, DROPDOWN_XML);
		}
	}
	else if(keynum == "38")
		goToPrevDropDown();
	else if(keynum == "27") //escape key
	{
		if(dropDownVisible)
		{
			if(currentDropDownIndex != -1)
			{
				document.getElementById('searchText').value = originalSearchText;
				currentDropDownIndex = -1;
			}
			hideDropDown();
		}
		else
			clearResults();
	}
	else //any key but the escape key
	{
		originalSearchText = searchText; //save the current text in the searchbox
		currentDropDownIndex = -1; 
		
		if(requireEnterOnSearch_WithDropDown) //if in dropdown mode with enter to global search
		{
			if(keynum == "13") //on eneter, search!
			{
				//parseSearch(searchText, GLOBAL_XML);
				//parseSearch(searchText, GLOBAL_XML);
				searchText = subParse(searchText);
				document.location.href = "?cat=" + searchText;
				currentDropDownIndex = -1;
				hideDropDown();
			}
			else //else, update dropdown
				parseSearch(searchText, DROPDOWN_XML);
		}
		//else //not in dropdown mode, any keypress updates global search
		//	parseSearch(searchText, GLOBAL_XML);
	}
}
function dropDown_mouseOver(me)
{
	mouseOverDropDown = true;
	
	if(currentDropDownIndex != -1)
		changeBG_out(document.getElementById('drop_'+(currentDropDownIndex)));	
		
	changeBG_over(me);
	
	currentDropDownIndex = me.id.replace(/[^0-9]/g, "");
}
function dropDown_mouseOut(me)
{
	mouseOverDropDown = false;
	//currentDropDownIndex = -1;
	//changeBG_out(me);
}

function changeBG_over(me)
{
	//alert(currentDropDownIndex);
	//if(currentDropDownIndex != -1)
	//	changeBG_out(document.getElementById('drop_'+currentDropDownIndex), false);
		
	me.style.background = "#243A48";
	me.style.color = "#fff";
	//currentDropDownIndex = me.id.replace(/[^0-9]/g, "");
}
function changeBG_out(me)
{
	me.style.background = "";
	me.style.color = "#000";
	
	//if(mouseBool)
		//currentDropDownIndex = -1;
}
function goToNextDropDown()
{
	if(dropDownVisible)
	{		
		if(currentDropDownIndex != -1)
			changeBG_out(document.getElementById('drop_'+(currentDropDownIndex)));	
			
		currentDropDownIndex ++;
		if(currentDropDownIndex < dropArr.length)
		{
			changeBG_over(document.getElementById('drop_'+currentDropDownIndex));
			currentDropDownIndex = document.getElementById('drop_'+currentDropDownIndex).id.replace(/[^0-9]/g, "");
			document.getElementById('searchText').value = dropArr[currentDropDownIndex]; //.getElementsByTagName('k')[0].childNodes[0].nodeValue;
		}
		else
		{
			currentDropDownIndex = -1;
			document.getElementById('searchText').value = originalSearchText;
		}
	}
}
function goToPrevDropDown()
{
	if(dropDownVisible)
	{
		if(currentDropDownIndex == -1)
			currentDropDownIndex = dropArr.length - 1;
		else
		{
			changeBG_out(document.getElementById('drop_'+(currentDropDownIndex)));	
			currentDropDownIndex --;
		}
		
		if(currentDropDownIndex > -1)
		{
			changeBG_over(document.getElementById('drop_'+currentDropDownIndex));
			document.getElementById('searchText').value = dropArr[currentDropDownIndex]; //.getElementsByTagName('k')[0].childNodes[0].nodeValue;
		}
		else
		{
			currentDropDownIndex = -1;
			document.getElementById('searchText').value = originalSearchText;
		}
	}
}
function showHideSection( section )
{
	var sectionLink = document.getElementById(section+"Link");
	section = document.getElementById(section);
	
	if(section.style.display == "")
	{
		sectionLink.innerHTML = more_text;
		section.style.display = "none";
	}
	else
	{
		sectionLink.innerHTML = less_text;
		section.style.display = "";
	}
}
function searchText_Blur()
{
	if(currentDropDownIndex != -1 && mouseOverDropDown)
	{
		document.getElementById("searchText").value = dropArr[currentDropDownIndex]; //.getElementsByTagName('k')[0].childNodes[0].nodeValue;
		originalSearchText = dropArr[currentDropDownIndex];
		var searchText = subParse( document.getElementById("searchText").value);
		document.location.href = "?cat=" + searchText;
		//parseSearch(document.getElementById("searchText").value, GLOBAL_XML);
	}
	else if(dropDownVisible)
	{
		document.getElementById("searchText").value = originalSearchText;
	}
	currentDropDownIndex = -1;
	hideDropDown();
}
function hideDropDown()
{
	document.getElementById("dropDown").style.display = "none";
	dropDownVisible = false;
}

function showDropDown()
{
	document.getElementById("dropDown").style.display = "";
	dropDownVisible = true;
}

//UNUSED CODE:
/**
function hideResults()
{
	document.getElementById("onScreen").style.display = "none";
}*/

/**
function getViewingResults(start)
{
	start = Number(start);

	return "<div style='text-align:right; padding:0 0 0 0; font-family:Gill Sans MT; font-size:13px; font-weight:bold; color:#999'>Viewing <font style='font-weight:bold; color:#22511C;'>" + (start + 1) + " - " + ( arraySize < (start + displaySize) ? arraySize : (start + displaySize) ) + "</font> of <font style='font-weight:bold; color:#22511C;'>" + arraySize + "</font></div>";
}


function nextButton()
{
	var sections = "";
	
	sections = "<div style='font-family: Gill Sans MT; font-weight:bold; font-size:14px; padding:0px;margin-bottom:10px;text-align:center; background:#b7d1ef'>";
	
	sections += "<font style='font-size:17px'>1&nbsp;</font>";
	
	var numberSections = Number( (arraySize/displaySize).toString().split(".")[0]);
	if( (arraySize % displaySize) != 0) numberSections += 1;
	
	if(numberSections > 1)
		sections += ("<span style='color:blue; cursor:pointer; text-decoration:none' onclick='outputResults(true,"+ displaySize +")'><img alt='>>' title='Next "+displaySize+ " Results' src='http://alfalfa.ucdavis.edu/-images/arrows.gif'></span>");
	
	sections += "</div>";
	
	return sections;
}

function calculateLocation(start)
{
	var sections = "";
	var upperLim = (displaySize * 2) - 1;
	start = Number(start);
	
	//calculate number of sections, plus one if remainder
	var numberSections = Number( (arraySize/displaySize).toString().split(".")[0]);
	if( (arraySize % displaySize) != 0) numberSections += 1;
	
	var begin = 0;
	var end = numberSections;
	var currentSection = (start / displaySize);
	
	if(end > upperLim)
	{
		if(currentSection < displaySize)
		{
			begin = 0;
			end = upperLim;
		}
		else if(end - currentSection < displaySize)
		{
			begin = end - upperLim;
		}
		else
		{
			begin = currentSection - displaySize;
			end = currentSection + displaySize;
		}
	}
	
	sections = "<div style='font-family: Gill Sans MT; font-weight:bold; font-size:14px; padding:0px;margin-bottom:10px;text-align:center; background:#b7d1ef'>";
	
	if(currentSection != 0)
		sections += ("<span style='color:blue; cursor:pointer; text-decoration:none' onclick='outputResults(true,\""+ (start-displaySize) + "\")'><img alt='<<' title='Prev "+displaySize+" Results' src='http://alfalfa.ucdavis.edu/-images/barrows.gif'></span>&nbsp;&nbsp;");
		
	for(var i = begin; i<end; i++)
	{
		if(i == currentSection)
			sections += ("<font style='font-size:17px'>" + (i+1) + "</font>&nbsp;&nbsp;" );
		else
			sections += ("<span style='color:blue; cursor:pointer; text-decoration:none' onclick='outputResults(true,\""+ (i * displaySize) + "\")'>" + (i+1) + "</span>&nbsp;&nbsp;");
	}
	//next link
	if(currentSection != numberSections -1)
		sections += ("<span style='color:blue; cursor:pointer; text-decoration:none' onclick='outputResults(true, \""+ (start+displaySize) + "\")'><img alt='>>' title='Next "+displaySize+ " Results' src='http://alfalfa.ucdavis.edu/-images/arrows.gif'></span>");
	
	sections += "</div>";
	
	return sections;
}
*/