// ==UserScript==
// @name           Google Reader Unsubscribe Button
// @namespace      http://panoptic.com/google/
// @description    Simple script that adds an "unsubscribe" button right on the reading pane.  Version 0.2.
// @include        http://www.google.com/reader/view/*
// ==/UserScript==

/*
 * http://panoptic.com/google/google-reader-unsubscribe.user.js
 *
 * This Greasemonkey script inserts an "Unsubscribe" button to the right
 * of the "Mark all as read" and "Refresh" buttons in Google Reader's
 * feed reading pane.
 */

(function() {
  var u = document.createElement('table');
  u.setAttribute('id', 'unsubscribe-button');
  u.setAttribute('class', 'button-container unselectable button-container-tight viewer-buttons');
  u.innerHTML += '<tbody><tr><td class="btl"></td><td class="btr"></td></tr><tr><td class="bbl"></td><td class="bbr"><div class="button-body-container"><span class="button-body unselectable">Unsubscribe</span></div></td></tr></tbody>';
  u.addEventListener('click', function(e) {
    var ce = document.getElementById('current-entry');
    if (!ce) ce = document.getElementById('entries').firstChild;
    var cx = ce.getElementsByTagName('A');
    var m = null, f = null, t = null;
    for (var i = 0; i < cx.length; i++) {
      var o = cx[i].wrappedJSObject;
      if (o.getAttribute('class') && o.getAttribute('class').search(/entry-source-title/) >= 0) {
        f = o.getAttribute('href');
        if (m = f.match(/^\/reader\/view\/(feed\/.*)$/)) {
          f = unescape(m[1]);
        }
        t = o.textContent;
        break;
      }
    }
    if (!f) {
      alert('Could not identify feed to unsubscribe from.');
      return;
    }
    window.setTimeout("TB(['" + f + "'], '" + t.replace(/'/g, "\\'")
       + "', null, false)", 10);
  }, true);

  var r = document.getElementById('viewer-refresh');
  r.parentNode.insertBefore(u, r.nextSibling);
})();
