function compare_dates(a,b) {
    var re = /^(\d\d) (\S+) (\d\d\d\d)/;
    var d1 = a.match(re);
    var d2 = b.match(re);

    if (d1 == null || d2 == null) {
	throw new Error("Invalid date in stories list");
    }

    var date1 = "" + d1[3] + months[d1[2]] + d1[1];
    var date2 = "" + d2[3] + months[d2[2]] + d2[1];
    return date1 - date2;
}

compare_by = {
    name: function(a, b) { return a.n - b.n; },
    ctime: function(a, b) { return compare_dates(a.ctime, b.ctime); },
    mtime: function(a, b) { return compare_dates(a.mtime, b.mtime); },
};

var stories = new Array();
var s = document.getElementById("stories");
var months = { January: "01", February: "02", March: "03", April: "04", May: "05", June: "06",
	       July: "07", August: "08", September: "09", October: "10", November: "11", December: "12" };

var nstories = 0;
var is_sorted_by = "name";
var sort_order = "ascend";

if (s) {
    for (var node = s.firstChild; node != null; node = node.nextSibling) {
	if (node.nodeType != 1) {
	    continue;
	}

	nstories++;
	var story = node.getAttribute("id");
	var ctime = null;
	var mtime = null;
	var re = /(\d\d \S+ \d\d\d\d)/;
	for (var subnode = node.firstChild; subnode != null; subnode = subnode.nextSibling) {
	    if (subnode.nodeType == 1) {
		if (subnode.getAttribute("class") == "ctime") {
		    var txt = subnode.innerText || subnode.textContent;
		    ctime = txt.match(re)[0];
		}
		else if (subnode.getAttribute("class") == "mtime") {
		    var txt = subnode.innerText || subnode.textContent;
		    mtime = txt.match(re)[0];
		}
	    }
	}
	if (mtime == null) mtime = ctime;
	stories.push( { story: story, ctime: ctime, mtime: mtime, n: nstories, node: node} );
    }
}

function sort_by(what) {
    if (!s) { return; }
    var story_list = stories.slice(0);
    story_list.sort(compare_by[what]);

    if (what == is_sorted_by) {
	sort_order = (sort_order == "ascend") ? "descend" : "ascend";
	if (sort_order == "descend") {
	    story_list.reverse();
	}
    }
    else if (what != "name") {
	story_list.reverse();
	sort_order = "descend";
    }
    else {
	sort_order = "ascend";
    }
    is_sorted_by = what;

    for (var i = 0; i != nstories; i++) {
	s.appendChild(story_list[i].node);
    }
}
