/*
 * ordering.js
 * Table ordering library for Sundial
 *
 * Author: Zach van Schouwen
 * Date: 01-29-2007
 *
 * Standardize the ordering of on-page tables.
 */

/*
 * When orderingLink() is called, it is on a link of this form:
 * <a class="tableOrder" order="SQL_Field_Name" href="...">SQL_Field_Title</a>
 * where SQL_Field_Name and SQL_Field_Title are user-supplied.
 *
 * If the page is currently ordered by this field, a CSS class is associated
 * with it to indicate that it is the current order.
 *
 * Either way, the link also has a JS function associated with it to reorder
 * the page.
 *
 * Note: See smartLinks.js for the place where this is actually called --
 * the page is scanned on load for appropriate links.
 */
function orderingLink(tag) {
	var sqlField = tag.getAttribute('order');
	if (!sqlField) return;

	var nextDir = '+';	/* that's a + sign */
	if (currentOrdering() == sqlField) {
		var dir = currentOrderingDir();
		tag.className += ' ' + dir;
		if (dir == 'ascending') nextDir = '-';
	}

	var tagChangeOrder = function() {
		changeOrder(sqlField + nextDir);
	};
	addElementEvent(tag, 'click', tagChangeOrder, true);
	tag.sqlField = sqlField;
}

/*
 * Change the current page to a new order.
 */
function changeOrder(order, append_to_url) {
	/* New, preferred method -- try form submission first */
	if (document.theForm) {
		document.theForm.orderBy.value = order;
		document.theForm.submit();
		return;
	}
	
	var newHref = window.location.href;
	if (newHref.indexOf('?') == -1) newHref += '?';
	if (order.indexOf('+') != -1)
		order = order.substr(0, order.length - 1) + '%2B';
	if (append_to_url) newHref += '&' + append_to_url;
	var removeOrder = new RegExp('\&?orderBy=[^\&]*', 'i');
	window.location.href = newHref.replace(removeOrder, '') +
		'&orderBy=' + order;
}

/*
 * Returns the current SQL field by which the page is being ordered.
 */
function currentOrdering() {
	var elt = document.getElementById('orderBy');
	if (!elt) return false;
	return (elt.value.substr(0, elt.value.length - 1));
}

/*
 * Returns "ascending" or "descending", depending on which order is being
 * used currently.
 */
function currentOrderingDir() {
	var elt = document.getElementById('orderBy');
	if (!elt) return false;
	if (elt.value.substr(elt.value.length - 1) == '+')
		return 'ascending';
	return 'descending';
}