/*

Copyright (c) 2005, Daniel Juliano
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.
    * The names of contributors to this source code may not be used to endorse 
      or promote products derived from this software without specific prior 
      written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

/*

Script Summary:

Perform a client-side only text search across a two-dimensional array of contact 
information, and paint the results with a 'Hit' column to a table.  All columns 
of the contact information array are searched against, but only two columns, 
determined during the initializeSearch call, are displayed alongside the 'Hit' 
column.

Usage:

  1) Call initializeSearch() once the xml contacts array has loaded.
  2) Call searchDisplay() whenever the 'Sort' button is clicked on the form.

*/

var searchArray = null;
var searchAvailable = false;
var searchColumnFirstName = -1;
var searchColumnLastName = -1;

var searchExpression = /^(\d)$/;	// format numbers to two digits.

// Run once xml doc has loaded.
function initializeSearch(records, first, last) {
	
	// Transfer parameters to global variables.
	searchArray = records;
	if (records == null) searchArray = Array();
	if (searchArray.length == 0) {
		//alert("Sorry, no records exist to search against.");
		searchAvailable = false;
	}
	searchAvailable = true
	
	searchColumnFirstName = first;
	searchColumnLastName = last;
}

// Run when 'Search' button is clicked.
function searchDisplay() {
	// Wipe the search area.
	document.getElementById("search_txt").value = "";
	document.getElementById("search_txt").focus();
	document.getElementById("search_results_div").innerHTML = "<table id='search_results_table'><tbody><tr><td>Empty</td></tr></tbody></table>\n";
}

function searchAllRecords(element) {
	
	// Check array has loaded.
	if (!searchAvailable) return false;
	
	// Convert search terms entered into regular expressions.
	var search = element.value;
	var words = search.split(" ");
	var expressions = new Array();
	var spans = new Array();
	for (var i = 0; i < words.length; i++) {
		// Check all words entered are more than three characters.
		if (words[i].length < 2) return false;
		expressions[i] = new RegExp(words[i], "i");
		spans[i] = new RegExp("(" + words[i] + ")", "i");
	}
	
	// Loop thru all records and add matches against
	// search terms to table.  Must match all words.
	var expression = null;
	var record = "";
	var valid = true;
	
	var id = Array(3);
	var result = "";
	var counter = -1;
	
	var html = "";
	html += "<table id='search_results_table'><tbody>\n";
	html += "<tr>";
	html += "<td class='search_title'>First Name</td>";
	html += "<td class='search_title'>Last Name</td>";
	html += "<td class='search_title'>Hit Column</td>";
	html += "</tr>\n";
	
	// searchArray is a two dimensional array.  Search thru every
	// single element in the array, and if you get a hit, only show
	// the hit field in your results span.
	for (var i = 0; i < searchArray.length; i++) {
		for (var j = 0; j < searchArray[i].length; j++) {
			
			// Validate against all expressions.
			valid = true;
			for (var k = 0; k < expressions.length; k++) {
				record = searchArray[i][j];
				if (!expressions[k].test(record)) {
					valid = false;
					break;
				} else {
					record = record.replace(spans[k], "<span class='search_span'>$1</span>");
					break;
				}
			}
			
			if (valid) {
				counter++;
//				id = "search_" + mainFormatToTwo(counter);
				id = "search_" + mainFormatToTwo(i);
				
				result = "";
				result += "<tr><td id='" + id + "_00'>";
				result += searchArray[i][searchColumnFirstName];
				result += "</td><td id='" + id + "_01'>";
				result += searchArray[i][searchColumnLastName];
				result += "</td><td id='" + id + "_02'>";
				result += record;
				result += "</td></tr>\n";
				
				html +=  result;
			}
		}
	}
	html += "</tbody></table>";
	document.getElementById("search_results_div").innerHTML = html;
	
	// Set cell actions.
	var arrayTD = document.getElementById("search_results_table").getElementsByTagName("TD");
	for(var i = 0; i < arrayTD.length; i++) {
		if (arrayTD[i].className == null || arrayTD[i].className == "") {
			arrayTD[i].className = "search_td";
			arrayTD[i].onmouseover = function(event) { highlightRow(this, 1); };
			arrayTD[i].onmouseout = function(event) { highlightRow(this, 0); };
			arrayTD[i].onclick = function(event) { buttonDisplayAction("action_view", this); highlightSelect(this.id); };
		}
	}
	
	// Initialize the row highlighting routine.
	highlightInit(new Array("search_td", "search_td_highlight", "search_td_selected"));
}

function searchHighlightRow(element, highlight) {
	element.className = highlight;
}

