
/*
 * Original script from: http://www.vonloesch.de/node/23
 *
 * Modified August 2006 by philipp.reichart@vxart.de (ignoreCase, searchMode)
 */

// "Constants" for search modi
var STARTS= 0;
var CONTAINS= 1;
var ENDS= 2;

/*
 * Utility function to cut down the size of onFoo handlers in the form.
 * This function assumes certain form element names, change them if necessary.
 *
 * formElement	the form element (usually "this") -- not the form!
 * tableId		[see filter(..)]
 * column		[see filter(..)]
 */
function filterForm(formElement, tableId, column) {
	with(formElement.form) {
		filter(query.value,
			tableId,
			column.value,
			1,
			0);
	}	
}

/**
 * term			the search term to filter by
 * tableId		the ID of the table to filter
 * column		the number of the column to filter by (0..n)
 * searchMode	[see find(..)]
 * ignoreCase	[see find(..)]
 */
function filter(term, tableId, column, ignoreCase, searchMode) {
	var table = document.getElementById(tableId);
	for (var i = 1; i < table.rows.length; i++) {
		with (table.rows[i]) {
			// search over all child nodes, but strip out HTML tags
			var elem = cells[column].innerHTML.replace(/<[^>]+>/g, "");
			if (find(term, elem, ignoreCase, searchMode)) {
				style.display = '';
			} else {
				style.display = 'none';
			}
		}
	}
	
	// recolor table rows (sortable.js)
// 	alternate(table);
}

/*
 * Finds the needle in the haystack, optionally ignoring
 * case and using three different search modes.
 *
 * searchMode	one of "start", "contains", "end"
 * ignoreCase	true to filter case insensitively
 */
function find(needle, haystack, ignoreCase, searchMode) {
	if (needle == "") {
		return true;
	}
	
	if (ignoreCase) {
		needle = needle.toLowerCase();
		haystack = haystack.toLowerCase();
	}
	
	var pos = haystack.indexOf(needle);
	
	switch (searchMode) {
		case STARTS:
			return pos == 0;
		case CONTAINS:
			return pos >= 0;
		case ENDS:
			return pos == (haystack.length - needle.length);
	}
	
	alert("invalid search mode");
	return false;
}

