// ==UserScript==
// @namespace     http://www.squarefree.com/jsenv/autogenerated
// @name          Ask Metafilter Comment Resorter
// @description   Puts most-favorited comments at the top of every discussion.
// @include       http://ask.metafilter.com/*/*
// ==/UserScript==

/**
** TODO: Move named anchor links as well as comment divs
*/

var xeval = function(xpath, node) {
    node = node || document;
    var x = document.evaluate(xpath, node, null, 6, null);
    var rv = [];
    for(var i = 0; i < x.snapshotLength; ++i)
        rv[i] = x.snapshotItem(i);
    return rv;
}

var xapply = function(xpath, func) {
    for each(node in xeval(xpath))
        if(node) func(node);
};

var highlightNode = function(node) {
    node.setAttribute("highlighted", "true");
    node.style.outline = "5px solid red";
}

var undoHighlight = function(node) {
    node.removeAttribute("highlighted");
    node.style.outline = "none";
};

var highlight = function (xpath) {
    clearHighlights();
    xapply(xpath, highlightNode);
};

var clearHighlights = function() {
    xapply("//*[@highlighted]", undoHighlight);
};

var numFavs = function(comment) {
    var rv = xeval(".//a[contains(@title, 'favorite')]", comment);
    var matches = rv[0].title.match(/(\d+) user/);
    var match = matches && matches[1] || 0;
    return parseInt(match);
}

function sortByNumFavs(c1,c2) {
  var a = numFavs(c1);
  var b = numFavs(c2);
  if(a == b) return 0;
  if(a <  b) return -1;
  return 1; // ascending order
}

function firstComment() {
  return xeval("//div[@class='comments']")[0];
}

var page = document.getElementById('page');

var favs = xeval("//div[@class='comments' and .//a[contains(@title,'favorite')]]");
var sorted = favs.sort(sortByNumFavs);
for(var i = 0; i < sorted.length; ++i) {
  page.removeChild(sorted[i]);
  page.insertBefore(sorted[i], firstComment());
  sorted[i].appendChild(document.createElement('br'));
  sorted[i].appendChild(document.createElement('br'));
}
