// ==UserScript==
// @name           Reddit Conversation Minimizer
// @namespace      http://arantius.com/misc/greasemonkey/
// @description    Collapse low-score comments on Reddit, a'la Slashdot.
// @include        http://reddit.com/info/*/comments
// ==/UserScript==

const MIN_SCORE=10;
var collapsed=[];

function $x(p, context) {
    if (!context) context=document;
    var arr=[];
    var xpr=document.evaluate(
        p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null
    );
    for(i=0;item=xpr.snapshotItem(i);i++){ arr.push(item); }
    return arr;
}

var score,scores=$x('//table[@class="commenttable"]//span[starts-with(@id, "score")]');

for (var i=0, el=null; el=scores[i]; i++) {
	score=parseInt(el.textContent);
	if (score<MIN_SCORE) {
		while (el && 'TABLE'!=el.tagName) el=el.parentNode;
		if (!el) return;

		var img=document.createElement('img');
		img.src='chrome://global/skin/tree/twisty-clsd.png';
		img.setAttribute('style', el.getAttribute('style')); // get margin

		collapsed.push({'el':el, 'img':img});

		el.style.display='none';
		el.parentNode.appendChild(img);

		(function(el, img){
		img.addEventListener('click', function(){
			el.style.display='';
			img.style.display='none';
		}, false);
		})(el, img);
	}
}

if (collapsed.length>0) {
	var point=document.getElementById('commentform')
		.parentNode
		.childNodes[2];
	
	var a=document.createElement('a');
	a.href='javascript:void(0);';
	a.style.display='block';
	a.style.margin='1em 0';

	var img=document.createElement('img');
	img.src='chrome://global/skin/tree/twisty-clsd.png';

	a.appendChild(img);
	a.appendChild(document.createTextNode(' Expand All'));

	a.addEventListener('click', function() {
		for (var i=0, comment; comment=collapsed[i]; i++) {
			comment.el.style.display='';
			comment.img.style.display='none';
		}
		a.style.display='false';
	}, true);

	point.parentNode.insertBefore(a, point);

	console.log('all link', a);
}
