// ==UserScript==
// @name            Facebook In-Feed App Blocker
// @namespace       http://gdorn.nudio.net/greasemonkey
// @description     Adds "Block this app" button within the news feed
// @include         http://www.facebook.com/home.php*
// @include         https://www.facebook.com/home.php*
// ==/UserScript==

function add_block_app_buttons() {
    //stop more events from happening to prevent simultaneous runs
    window.removeEventListener('load', add_block_app_buttons, false);
    document.getElementById('home_stream').removeEventListener('DOMSubtreeModified', add_block_app_buttons, true);
    appIdFinder = /apps\/application\.php\?id\=(\d+)"/;
    var appStories = document.evaluate("//img[contains(@src, 'app')]/ancestor::div[contains(@class, 'UIStory')][contains(@class, 'UIIntentional')][1]", document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    //alert('Running...');
    var i = appStories.snapshotLength;
    while (appStory = appStories.snapshotItem(--i)){
	//get the app id
	html = appStory.innerHTML;
	
	if(html.indexOf('Block App') != -1){
	    //already added a link for this one, continue
	    continue;
	}
	
	var app_match = appIdFinder.exec(html);
	if (app_match){
	    app_id = app_match[1];
	    var myElement = document.createElement('a');
	    myElement.innerHTML = "Block App";
	    myElement.href = "http://www.facebook.com/apps/block.php?id=" + app_id + "&action=block&source=about";
	    myElement.target = "_blank";
	    //find the last element of <span class="action_links_bottom">
//	    var action_links_xpath = "//img[contains(@src, 'app')]/ancestor::div[contains(@class, 'UIStory')][contains(@class, 'UIIntentional')][1]//span[@class='action_links_bottom']//a[contains(@onclick, '" + app_id + "')]//ancestor::span[@class='action_links_bottom']";
	    var action_links_xpath = ".//span[@class='action_links_bottom']";
	    
	    var action_links_bottom = document.evaluate(action_links_xpath, appStory, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0);
	    var dot = document.createElement('span');
	    dot.innerHTML = ' &#183; ';
	    dot.class = "action_link_dash action_link_dash_1";
	    action_links_bottom.insertBefore(dot, action_links_bottom.firstChild);
	    action_links_bottom.insertBefore(myElement, action_links_bottom.firstChild)
	}
	//appStory.style.border = "red 4px dashed";
    }
    //add event listener back
    document.getElementById('home_stream').addEventListener('DOMSubtreeModified', add_block_app_buttons, true);
    
}


window.addEventListener("load", add_block_app_buttons, false);
window.addEventListener('load', function() {
  document.getElementById('home_stream').addEventListener('DOMSubtreeModified', add_block_app_buttons, true);
}, true);


//document.documentElement.addEventListener("DOMNodeInserted",add_block_app_buttons,false);
