event.add(window, "load", init_search, false);

function init_search() {
	// Find all tables with class "sort_me" and make them sortable.
	nodeList_table = document.getElementsByTagName("table");
	for (i_table = 0; i_table < nodeList_table.length; i_table++)
	{
		cur_table = nodeList_table[i_table];
		if (cur_table.className.indexOf("search_me") != -1) 
		{
			make_searchable(cur_table);
		}
	}
}

function make_searchable(table)
{
	if(table.tHead)
	{
		// The table has a thead
		num_cols = table.tHead.rows[0].cells.length;
		search_div = document.createElement("div");
		input = document.createElement("input");
		input.size = 20;
		event.add(input, "keyup", function() { search_rows(this); }, false);
		search_div.innerHTML = "Search Directory: ";
		search_div.appendChild(input);
		search_div.className = 'search_div';
		search_div.style.width = table.clientWidth + "px";
		table.parentNode.insertBefore(search_div, table);
	}
}

function search_rows(input)
{
	table = input.parentNode.nextSibling;
	search_term = input.value.toLowerCase();
	
	if(table.tHead)
	{
		skip_header = 1;
	}
	else
	{
		skip_header = 0;
	}
	
	// How many rows?
	num_rows = table.rows.length;
	
	// How many columns?
	if(num_rows)
	{
		num_cols = table.rows[0].cells.length;
	}
	else
	{
		return;
	}
	
	if(search_term.length)
	{
		for(i = 0; i < num_rows - skip_header; i++)
		{
			// Setting the row's display to "" will force the default display for the browser.
			// This being "table-row" for Firefox and "block" for IE.
			table.rows[i + skip_header].style.display = "";
		
			cur_row = table.rows[i + skip_header];
			cur_row_cells = cur_row.cells;
			 
			// Traverse the table, searching for search_term.
			j = 0;
			found_search_term = 0;
			while(!found_search_term  && j < num_cols)
			{
				// found_search_term will be the row number if the search_term was found.
				found_search_term = (i + skip_header) * (cur_row_cells[j].innerHTML.toLowerCase().indexOf(search_term) != -1);
				
				j++;
			}
			if(!found_search_term)
			{
				table.rows[i + skip_header].style.display = "none";
			}			
		}			
	}
	// The search_term is blank.
	// Display all the previously hidden table rows.
	else
	{
		for(i = 0; i < num_rows; i++)
		{
			table.rows[i].style.display = "";
		}
	}
	stripe_class.stripe();
}
