/*

Apply highlighting to a particular row, defined by the array cssClassNames:
  [0] = none (normal / mouseout)
  [1] = row moused over
  [2] = row selected
  
*/

var highlightSelected = -1;
var highlightPosition = -1;
var highlightClasses = Array();
var highlightID = null;
var highlightIDs = Array();

function highlightInit(cssClassNames, selectedIndex) {
	
	highlightPosition = -1;
	highlightSelected = -1;
	highlightID = null;
	
	highlightClasses = cssClassNames;
	if (selectedIndex) highlightPosition = selectedIndex;
}

function highlightRow(element, highlight) {
	
	// Element id's follow the pattern name_row_column.
	// Example: td_01_03
	highlightPosition = parseInt(element.id.split("_")[1]);
	if (highlightPosition == highlightSelected) return;
	
	// Apply highlight to each cell in the row.
	var td = element.parentNode.childNodes;
	for (var i = 0; i < td.length; i++) {
		if (td[i].nodeName == "TD") {
			td[i].className = highlightClasses[highlight];
		}
	}
}

function highlightSelect(id) {
	
	if (highlightPosition == -1) return;
	
	if (id == null) {
		// On 'Sort' page move, restore the previously selected element.
		if (highlightID == null || highlightID == "") return;
		id = highlightID;
		
	} else if(id.indexOf("_") == -1) {
		// Allow retrieval of previously selected element when switching 
		// between utilities (Sort, Search, List).
		id = highlightRetrieve(id);
		
	} else {
		// If there's an existing selection, remove all highlighting from that row.
		if (highlightID != null && highlightID != "") {
			var td = document.getElementById(highlightID).parentNode.childNodes;
			for (var i = 0; i < td.length; i++) td[i].className = highlightClasses[0];
		}
		highlightSelected = highlightPosition;
		highlightStore(id);
	}
	
	// Switch formatting for the highlighted row.
	var td = document.getElementById(id).parentNode.childNodes;
	for (var i = 0; i < td.length; i++) {
		if (td[i].nodeName == "TD") {
			td[i].className = highlightClasses[2];
		}
	}
}

function highlightStore(id) {
	var prefix = id.split("_")[0];
	
	// If the prefix already has a storage spot,
	// store the new full id at that location.
	for (var i = 0; i < highlightIDs.length; i++) {
		if (prefix == highlightIDs[i][0]) {
			highlightIDs[i][1] = id;
			highlightID = id;
			return;
		}
	}
	
	// Otherwise create a new storage element.
	var index = highlightIDs.length;
	highlightIDs[index] = Array();
	highlightIDs[index][0] = prefix;
	highlightIDs[index][1] = id;
	highlightID = id;
}
function highlightRetrieve(id) {
	var prefix = id.split("_")[0];
	
	// Find the storage for matching prefix.
	for (var i = 0; i < highlightIDs.length; i++) {
		if (prefix == highlightIDs[i][0]) {
			return document.getElementById(highlightIDs[i][1]);
		}
	}
	return null;
}

