// ==UserScript==
// @name           Hacker News: New Comment Marker
// @namespace      http://arantius.com/misc/greasemonkey/
// @description    Make "new" comments since your last visit especially visible
// @include        http://news.ycombinator.com/item?id=*
// @require        http://arantius.com/misc/greasemonkey/imports/dollarx.js
// ==/UserScript==

function idForLink(link) {
	return parseInt( link.href.replace(/.*\?id=/, ''), 10 );
}

function rowFor(el) {
	el=el.parentNode;
	while (el && el.tagName && 'TR'!=el.tagName) el=el.parentNode;
	return el;
}

// Find all the post item links, and their IDs, and the latest ID.
var postLinks=$x("//span[@class='comhead']/a[starts-with(@href, 'item?id=')]");
var postIds=postLinks.map(idForLink);
var lastId=Math.max.apply(Math, postIds);
var lastRead=false;
var m=document.cookie.match(/last_read=([0-9]+)/)
if (m && m[1]) {
	lastRead=parseInt(m[1], 10);
}

// Mark posts newer than the last read post.
if (lastRead) {
	for (var i=0, link=null; link=postLinks[i]; i++) {
		if (idForLink(link)>lastRead) {
			try {
				var row=rowFor(link);
				row=rowFor(row);
				row.style.backgroundColor='#FBFB78';
			} catch (e) {
				console.error(e);
			}
		}
	}
}

// Store the last-read post id.
document.cookie=
	'last_read='+lastId
	+'; path='+document.location.pathname+document.location.search
	+'; expire='+( new Date( new Date().valueOf() + 1209600000 ).toGMTString() );
