// ==UserScript==
// @name           Google Reader: Feed Cleaner
// @namespace      http://arantius.com/misc/greasemonkey/
// @description    Clean unwanted things out of feed items in Google Reader
// @include        http://www.google.com/reader/view/*
// @include        https://www.google.com/reader/view/*
// @require        http://arantius.com/misc/greasemonkey/imports/dollarx.js
// ==/UserScript==

document.getElementById('entries').addEventListener(
	'DOMNodeInserted', handleNodeInserted, true
);

function handleNodeInserted(event) {
	var el=event.target;

	if (!el.className.match(/\bentry\b/)) {
		return;
	}

	if (1==$x(".//a[contains(., 'Ads by Pheedo')]", el).length) {
		stripAfter($x(
			".//div[@class='item-body']/div/hr[position()=last()]",
			el
		));
	}

	stripAfter($x(
		".//p[contains(@style, 'border-top: 1px dashed')][em]",
		el
	));

	stripAfter($x(
		".//hr[following-sibling::text()[starts-with(., 'Brought to you')]][position()=last()]",
		el
	));

	stripAfter($x(
		".//a[text()='Email This Story']/preceding-sibling::br[1]",
		el
	));

	stripAfter($x(
		".//div/a/img[starts-with(@src, 'http://feeds2.feedburner.com')]/../..",
		el
	));

	stripAfter($x(
		".//map[starts-with(@name, 'ad')]",
		el
	));
	
	stripAfter($x(
		".//a[starts-with(@href, 'http://www.addtoany.com/')]",
		el
	));
}

function isElement(el) {
	return el.nodeName && 1==el.nodeType;
}

function stripAfter(el) {
	if (el && el[0] && isElement(el[0])) el=el[0];
	if (!isElement(el)) return;

	// Remove everything after el.
	while (el.nextSibling) strip(el.nextSibling);
	// Remove line breaks and empty elements before el.
	while (el.previousSibling && 
		(
			'HR'==el.previousSibling.tagName 
			|| 'BR'==el.previousSibling.tagName 
			|| (
				el.previousSibling.textContent.match(/^\s*$/)
				&& el.previousSibling.getElementsByTagName
				&& 0==el.previousSibling.getElementsByTagName('img').length
			)
		)
	) {
		el.parentNode.removeChild(el.previousSibling);
	}
	// Remove el.
	strip(el);
}

function strip(el) {
	el.parentNode.removeChild(el);
}
