// ==UserScript==
// @name           Delegate to Todoist
// @namespace      icr@delegate-to-todoist.com
// @description    Adds a "Delegate to Todoist" button to Gmail.
// @include        http://mail.google.com/mail/*
// @include        https://mail.google.com/mail/*
// ==/UserScript==
window.addEventListener('load', function() {
  var delegateText = "Delegate to Todoist";
  var scriptFunction = "javascript: (function() { var doc = top.document; if(top.js && top.js.document) doc = top.js.document; var script = doc.createElement('script'); doc.todoist_script = script; script.type = 'text/javascript'; script.src = 'http://todoist.com/getGmailJavaScript'; doc.getElementsByTagName('head')[0].appendChild(script); })(); void(0);"
  if (unsafeWindow.gmonkey) {
    unsafeWindow.gmonkey.load('1.0', function(gmail) {
      function setViewType() {
        if (gmail.getActiveViewType() == "cv") {
          var tables = gmail.getActiveViewElement().getElementsByTagName("table");
          for(var i = tables.length - 1; i >= 0; i--) {
            if (tables[i].className == "EWdQcf") {
              var tr = tables[i].firstChild.firstChild;
              var td = document.createElement("td");
              var div = document.createElement("div");
              div.setAttribute("class", "X5Xvu");
              var span = document.createElement("span");
              span.setAttribute("class", "qZkfSe");
              span.setAttribute("onclick", scriptFunction);
              var text = document.createTextNode(delegateText);
              span.appendChild(text);
              div.appendChild(span);
              td.appendChild(div);
              tr.insertBefore(td, tr.childNodes[tr.childNodes.length - 2]);
              break;
            }
          }
        }
      }
      gmail.registerViewChangeCallback(setViewType);
      setViewType();
    });
  // If we don't have the gmonkey extension we are on the old interface. Fall back.
  } else {
    var replyOrForwardLink = document.getElementById("sm_2") || document.getElementById("sm_4");
    if (replyOrForwardLink != null) {
      alert("BOO");
      var td = document.createElement("td");
      td.setAttribute("class", "ilc");
      td.setAttribute("onclick", scriptFunction);
      var text = document.createTextNode(delegateText);
      td.appendChild(text);
      alert(replyOrForwardLink.parentNode.innerHTML);
    
      replyOrForwardLink.parentNode.appendChild(td);
    }
  }
}, true);