// This file is licensed under the BSD-new license:
// http://www.opensource.org/licenses/bsd-license.php
//
// CHANGES
// 2005-08-06 Fixed to work with GM 0.5
// 2005-06-06 Fixed to work with new interface.

// ==UserScript== 
// @name          delicious post helper
// @namespace     http://ponderer.org
// @description   Adds a button to the delicious post page to show the source
//                page in an iframe.
// @include       http://del.icio.us/*
// ==/UserScript==

var SHOW_TEXT = 'show page in iframe';
var HIDE_TEXT = 'hide page';

function xpath(expr, doc) {
  if (!doc) {
    doc = document;
  }
  var items = document.evaluate(expr, doc, null,
                               XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var ret = [];
  for (var i = 0; i < items.snapshotLength; ++i) {
    ret.push(items.snapshotItem(i));
  }
  return ret;
}

window.addEventListener('load', function(ev) {
  var nodes = xpath("//form[@id='delForm']//td");
  if (nodes.length < 2)
    return;
  var table_cell = nodes[nodes.length - 2];
  
  // create the embedded iframe
  var iframe = document.createElement('iframe');
  iframe.style.width = "90%";
  iframe.style.height = "50%";
  iframe.style.display = "none";
  iframe.style.margin = "0 auto";

  // create a new button
  var newlink = document.createElement('a');
  newlink.appendChild(document.createTextNode(SHOW_TEXT));
  newlink.style.cursor = 'pointer';
  newlink.style.color = '#00f';

  // get the target url out of the cgi argument
  var url;
  var tokens = document.location.href.split(/&|[?]/);
  for (var t = 0; t < tokens.length; ++t) {
    var token = tokens[t];
    if (token.substr(0, 4) == "url=") {
      url = decodeURIComponent(token.split('=')[1]);
    }
  }
  if (!url) {
    return;
  }

  newlink.addEventListener('click', function(ev) {
    if (!iframe.getAttribute('src')) {
      iframe.setAttribute('src', url);

      // attach the iframe
      var nodes = xpath("//ul[@class='bundles']");
      if (nodes.length < 1)
        return false;
      var ul = nodes[0];
      ul.parentNode.insertBefore(iframe, ul);
    }
    
    if ('block' == iframe.style.display) {
      iframe.style.display = 'none';
      this.firstChild.nodeValue = SHOW_TEXT;
    } else {
      iframe.style.display = 'block';
      this.firstChild.nodeValue = HIDE_TEXT;
    }
    return true;
  }, true);
  
  // attach the new button
  table_cell.appendChild(newlink);
}, true);
