// ==UserScript==
// @name           Flickr BB Code
// @namespace      http://zoolcar9.lhukie.net/greasemonkey
// @include        http://www.flickr.com/photos/*/*/sizes/*
// @include        http://flickr.com/photos/*/*/sizes/*
// @description    Add BB code in photo size page
// ==/UserScript==

({
  getXPathNode: function(aXPath) {
    return document.evaluate(aXPath, document, null, 9, null).singleNodeValue;
  },

  getPageURL: function() {
    return this.getXPathNode("//div[@class='Bucket']//td/p/a");
  },

  getPhotoURL: function() {
    return this.getXPathNode("//div[@class='DownloadThis']" +
                             "/p/img[contains(@src, 'static')]");
  },

  paragraph: function() {
    return document.createElement("p");
  },

  init: function() {
    if (!(this.getPageURL() || this.getPhotoURL())) {
      throw new Error("Flickr BBCode script is broken!");
    }

    var para1 = this.paragraph();
    para1.textContent = "or this BB Code into your forum:";

    var para2 = this.paragraph();
    var t = para2.appendChild(document.createElement("textarea"));
    t.style.width = "520px";
    t.setAttribute("rows", ((typeof opera == "object") ? "2" : "1"));
    t.setAttribute("onfocus", "this.select();");
    t.textContent = "[url=" + this.getPageURL().href + "]" +
                    "[img]" + this.getPhotoURL().src + "[/img]" +
                    "[/url]";

    var tHTML = this.getXPathNode("//div[@class='ThinBucket']" +
                                  "/p/textarea[@name='textfield']");
    tHTML.parentNode.parentNode.insertBefore(para2,
                                             tHTML.parentNode.nextSibling);
    tHTML.parentNode.parentNode.insertBefore(para1,
                                             tHTML.parentNode.nextSibling);
  }

}).init()