/*
 * These functions dynamically assign "customkey" attributes used by sorttable.js for stable-sorting (which is faster and more predictable).
 * This is mainly useful for columns that are not text or numeric (e.g., an image).
 * Author: Scott Baldwin
 * Version: 2010.06.11
 * Example Usage:
 *  <body onLoad="javascript:return (setSortKeys2('score', false) && setSortKeys2('cover', false));" >
 */

/*
 * setAttribute wrapper for compatibility
 */
function mySetAttribute(elem, attrName, attrValue) {
	/* only create if attr node does not already exist... */
	if ( elem.getAttributeNode(attrName) == null ) {
		var attrNode = document.createAttribute(attrName);
		attrNode.value = attrValue;
		elem.setAttributeNode(attrNode);
	}
}

/*
 * METHOD 1
 */
function setSortKeys1(tableId, className, sortAscending) {
	var counter = (sortAscending ? 1 : 999999999);
	var theTable = document.getElementById(tableId);
	if ( theTable ) {
		for ( var rowIdx=0,maxRowIdx=theTable.rows.length; rowIdx<maxRowIdx; rowIdx++ ) {
			var curRow = theTable.rows[rowIdx];
			for ( var cellIdx=0,maxCellIdx=curRow.cells.length; cellIdx<maxCellIdx; cellIdx++ ) {
				var curCell = curRow.cells[cellIdx];
				if ( curCell.className==className && curCell.getAttribute('sorttable_customkey') == null ) {
					if ( sortAscending ) {
						mySetAttribute(curCell, 'sorttable_customkey', counter++);
					} else {
						mySetAttribute(curCell, 'sorttable_customkey', counter--);
					}
				}
			}
		}
	}
	return true; /* for onLoad */
}

/*
 * METHOD 2 (*** PREFERRED ***)
 */
function setSortKeys2(className, sortAscending) {
	var counter = (sortAscending ? 1 : 999999999);
	forEach ( document.getElementsByTagName('td'), function(td) {
		if ( td.className==className && td.getAttribute('sorttable_customkey') == null ) {
			if ( sortAscending ) {
				mySetAttribute(td, 'sorttable_customkey', counter++);
			} else {
				mySetAttribute(td, 'sorttable_customkey', counter--);
			}
		}
	});
	return true; /* for onLoad */
}
