// ==UserScript==
// @name           FriendFeed Eraser
// @namespace      http://www.evilgeniuschronicles.org/
// @description    Remove crap from FriendFeed
// @include        http://friendfeed.com/*
// This is mostly a distillation of Twitter Killfile
// http://hellonline.com/blog/?p=114
// and FriendFeed Savior
// http://userscripts.org/scripts/show/33389
// to hide FriendFeed entries by regular expression content. I modified FFS to include
// the ability to use regex and to allow for configuration by popup
// rather than requiring editing code to enter expressions and to also put the info about what matched
// in the "Hiding this from you" message
//
// Send feedback to dave@evilgeniuschronicles.org
//
// 0.05 Correct the wording in the prompt. You don't really have to double the backslashes for RE variables
// 0.04 trim the value before splitting on whitespace. Thanks Paul Reynolds!
// 0.03 fixed the problem that would hide your own entries and then reshow them when you commented to actually not hide your entries
// ==/UserScript==


(function() {
    var version = '0.04';
 
    //    comment out the line below to turn on debugging output
    var GM_log = function (){};
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

    /*
     * load_config: load filters from config.
     */
    load_config = function() {
        var v;

        // load key from config
        get_key = function(key) {
        var v = GM_getValue(key); 
            return v ? (v.trim().split(/\s*\s+\s*/)) : [];
        }

        // deserialize config and return as hash
        return {
            users: get_key('users'),
            keywords: get_key('keywords'),
        }
    }

    /*
     * get_regexps: build list of filter regexps.
     */
    get_regexps = function(cfg) {
        var i, re, re_opt = 'i',
        ret = { users: [], keyword: [] };

        // add keyword matches
        for (i = 0; i < cfg.keywords.length; i++) {
            re = new RegExp(cfg.keywords[i], re_opt);
            ret.keyword.push(re);
        }
        // add author names
        for (i = 0; i < cfg.users.length; i++) {
            re = new RegExp("\\/" + cfg.users[i] + '$', re_opt);
            GM_log("added " + re.toString());
            ret.users.push(re);
        }

        return ret;
    }

    match_content = function(text) {
        if (text == null || text == '') {
            return false;
        }
        for (var i = 0; i < res.keyword.length; i++) {
            if (text.match(res.keyword[i])) {
                GM_log("Matched regexp: " + res.keyword[i].toString());
                return true;
            }
        }
    }

    match_author = function(href) {
        if (href == null || href == '') {
            return false;
        }
        for (var i = 0; i < res.users.length; i++) {
            if (href.match(res.users[i])) {
                GM_log("Matched author: " + res.users[i].toString());
                return true;
            }
        }
    }

    /* gen_cb: generate menu callback for given entry key.
     */
    gen_cb = function(key) {
	return eval("function() {\n" +
        "var val = GM_getValue('" + key + "s');\n" +
        "if (!val)\n" +
        "  val = '';\n" +

        "val = window.prompt('Edit blocked " + key + " regex list (space seperated):', val);\n" +
        "if (val != null) {\n" +
        "  GM_setValue('" + key + "s', val);\n" +
        "  GM_log('Setting "+key+" ');\n" +
        "}\n" +
		    "}\n");
    }

    gen_keyword_cb = function() {
        var val = GM_getValue('keywords');
        if (!val) {
	    val='';
        }
        val = window.prompt('Edit blocked keyword regex list (space seperated) and use double \\\ for regex variables:', val);
        if (val != null) {
	    GM_setValue('keywords', val);
	    GM_log('Setting keyword to '+val);
        }
    }

    /*
     * init_menu: initialize menu entries.
     */
    init_menu = function() {
	GM_registerMenuCommand('Edit Blocked Regexes', gen_keyword_cb);
    }


    /*
     * init: set up twitter content blocker
     */
    init = function() {
	var cfg = load_config(),
	matches;

	GM_log('Version ' + version + ' started. config = ' + cfg.toSource());

	init_menu();
	return cfg;
    }

    function concatObject(obj) {
	str='';
	for(prop in obj)
	    {
		str+=prop + " value :"+ obj[prop]+"\n";
	    }
	return(str);
    }

    function needstobesaved(){
  var theList = regs.keyword
      GM_log("regs = " + concatObject(theList));
  for(var i=0;i<theList.length;i++) {
      var currentVal = unsafeWindow.$(this).html();
      var result;
      var pVal = unsafeWindow.$(this).siblings(".summary").html();
      if((result=currentVal.match(theList[i])) && pVal.indexOf('<a href')<=5 && pVal.toLowerCase().indexOf('">you</a>')<=0) {
	  GM_log("Matched "+ currentVal+" with "+ theList[i] + " for "+ result);
	  unsafeWindow.$(this).attr("id", unsafeWindow.$(this).attr("eid"));
	  var save_id = unsafeWindow.$(this).attr("id");
	  var filtered_div = document.getElementById(save_id);
	  var div_notice = document.createElement('div');
	  div_notice.className = 'entry';
	  div_notice.innerHTML = 'You have been saved from this post, it had something you didn\'t want to see in it. PS, it matched '+ theList[i]+ ' with ' + result + ' <br /><a onclick="this.parentNode.style.display=\'none\'; this.parentNode.nextSibling.style.display=\'\'; return false;" href="#"><i>Click here</i></a> if you cannot resist the temptation.';
	  filtered_div.parentNode.insertBefore(div_notice, filtered_div);
	  unsafeWindow.$(this).css("display", "none");
      return
	  } else {
	  GM_log("Didn't match  "+ currentVal+" with "+ theList[i]);
      }
  }
    }

    cfg=init();
    regs=get_regexps(cfg);
    GM_log("Regexes = " + concatObject(regs));
    unsafeWindow.$("div.entry").each( needstobesaved );

})();
