/*	limitlist.js

	provides functionality for searching a list of objects on a webpage in
	real time.
	
	Author: Jonathan Stuart-Moore
	Date: 10-24-05
	
	provides:
		- limitList(searchstring)
		this method should be called with the search string desired, i.e. from
		the text field where you are entering the string.
		
	requires:
		- an array called listItems
		
		- setStringsToMatch(index)
		you should implement this function to set what fields you want searched.
		A sample:
			function setStringsToMatch(index)
			{
				stringsToMatch = new Array();
				stringsToMatch[0] = listItems[index].name;
				stringsToMatch[1] = listItems[index].descrip;
			}
		will search the name and description for each index of listItems
		
		- printRow(index, counter)
		returns the row for the given index, so that you can set the
		page-specific formatting in the page javascript

		- startList()
		returns text to go at the beginning of the div-- i.e. table starts
		
		- endList()
		returns text to go at the end of the div
		
		-a div on the page called listingdiv
*/


function limitList(searchstring, listsize)
{
	// if the search string contains white space,
	// split on the white space and search using AND on the terms
	
	// if there is white space
	if (searchstring.indexOf(" ") != -1)
	{
		whiteSpace = /[ \t]/g;
	
		// split on the white space
		searchterms = searchstring.split(" ");
		for (i = 0; i < searchterms.length; i++)
		{
			// grep for extra white space and kill it
			searchterms[i].replace(whiteSpace, "");
		}
	// if no white space
	} else {
		// make the search terms be a 1-elt array
		searchterms = new Array();
		searchterms[0] = searchstring;
	}
	
	// counter is counter of output rows
	// passed to user as formatting info
	counter = 0;
	
	// the output string initiated
//	outString = startList();
	// for every list item
	for (j = 0; j < listsize; j++){
	
		// get the strings of it that we want to match within
		setStringsToMatch(j);
		
		// boolean for the "AND" component
		willdisplay = true;
		
		// go through all the search terms and make sure all are
		// matched in at least one field
		for (k = 0; k < searchterms.length; k++)
		{
			// make a new regular expression based on the current search term
			rExp = new RegExp(searchterms[k], "i");
			
			// OR boolean for the "at least one field"
			innerboolean = false;
			
			// look through all the possible fields that are open for search
			for (l = 0; l < stringsToMatch.length; l++)
			{
				// if we find a match, flag it
				if (stringsToMatch[l].match(rExp)){
					innerboolean = true;
				}
			}
			
			// if no match has been flagged, unflag the AND boolean
			if (innerboolean == false)
			{
				willdisplay = false;
			}
		}
		
		// if all terms are matched, append the printRow output to the
		// output string
		if (willdisplay)
		{
			addRow(j);
			counter++;
		}
	}
	
}

