$(document).ready(function(){
	register(0, "\u2193", gt);
    });

function register(col, sorting, sortfunc) {
    sortfuncs = {0 : lt, 1 : lt};
    sortings = {0 : "\u2191", 0 : "\u2191"};

    sortfuncs[col] = sortfunc;
    sortings[col] = sorting;

    $("#byName").click(function() {
	    sortBy("#dirlist", 0, sortfuncs[0], sortings[0]);
	}).end();
    $("#byDate").click(function() {
	    sortBy("#dirlist", 1, sortfuncs[1], sortings[1]);
	}).end();

    removeSortIndicator();
    addSortIndicator(col, sorting);
}

function removeSortIndicator() {
    $("#sortIndicator").remove();
}

function otherSorting(sorting) {
    if (sorting == "\u2193") {
	return "\u2191";
    }
    return "\u2193";
}

function otherSortFunc(f) {
    if (f == gt) {
	return lt;
    }
    return gt;
}

function addSortIndicator(col, sorting) {
    var names = {0 : "#byName", 1 : "#byDate"};
    $(names[col]).append($("<span id=\"sortIndicator\"/>"));
    $("#sortIndicator").append(" ");
    $("#sortIndicator").append(sorting);
}

function lt(a, b) {
    return (a < b) ? -1 : ((a > b) ? 1 : 0);
}

function gt(a, b) {
    return (a > b) ? -1 : ((a < b) ? 1 : 0);
}

function extractSortable(row, column) {
    if (column == 0) {
	return $(row).children('td').eq(0).children('a').text();
    } else {
	return $(row).children('td').eq(1).text();
    }
}

function sortBy(tableid, column, cmp, sorting) {
    curTable = $(tableid);
    sortedTable = curTable.clone();
    sortedTable.children().children(".dirname").remove();
    sortedRows = new Array();

    curTable.children().children(".dirname").map(function() {
	    sortedRows.push(this);
	    return this;
	}).end();
    sortedRows.sort(function(lhs, rhs) {
	    var lcontent = extractSortable(lhs, column);
	    var rcontent = extractSortable(rhs, column);
	    return cmp(lcontent, rcontent);
	});
    jQuery.each(sortedRows, function() {
	    sortedTable.append(this);
	});
    curTable.replaceWith(sortedTable);
    register(column, otherSorting(sorting), otherSortFunc(cmp));
}

