/* Copy URL Lite
 *   nanto_vi (TOYAMA Nao), 2006-12-26
 *
 * Copy URL and extra informations from the context menu.
 */

(function CopyURLLite() {

const EOL = "\r\n";

var mMenus = [
  {
    label: "タイトルと URL をコピー",
    accesskey: "T",
    get text() {
      var win = document.commandDispatcher.focusedWindow;
      return win.document.title + EOL + win.location.href + EOL;
    }
  },
  {
    label: "タイトルと選択した部分と URL をコピー",
    accesskey: "U",
    get text() {
      var win = document.commandDispatcher.focusedWindow;
      return win.document.title + EOL +
             win.getSelection().toString() + EOL +
             win.location.href + EOL;
    },
    get shouldDisplay() {
      return gContextMenu.isTextSelected;
    }
  }
];

init: {
  let contextMenu = document.getElementById("contentAreaContextMenu");
  let separator = document.getElementById("context-sep-properties");

  for (let i = 0, menu; menu = mMenus[i]; i++) {
    let menuItem = document.createElementNS(kXULNS, "menuitem");
    menuItem.id = "copyurllite-menu-" + i;
    menuItem.setAttribute("label", menu.label);
    if ("accesskey" in menu)
      menuItem.setAttribute("accesskey", menu.accesskey);
    menuItem.culMenu = menu;
    menuItem.addEventListener("command", copyText, false);
    contextMenu.insertBefore(menuItem, separator);
  }

  contextMenu.addEventListener("popupshowing", setMenuDisplay, false);
}

function copyText(aEvent) {
  Cc["@mozilla.org/widget/clipboardhelper;1"]
    .getService(Ci.nsIClipboardHelper)
    .copyString(aEvent.target.culMenu.text);
}

function setMenuDisplay() {
  for (var i = 0, menu; menu = mMenus[i]; i++)
    document.getElementById("copyurllite-menu-" + i).hidden =
      "shouldDisplay" in menu && !menu.shouldDisplay;
}

})();
