﻿// ==UserScript==
// @name          Edit This Journal
// @namespace     net.moeffju.dA
// @description	  Adds buttons to easily edit your journals
// @include       http://*.deviantart.com/
// @include       http://*.deviantart.com/journal/*
// ==/UserScript==

// © 2005, 2006 Matthias Bauer <http://moeffju.deviantart.com/>
// Licensed under the GNU General Public License, version 2 (and no later version)

var xpath = function (query, contextNode, resultType) {
  if (null == contextNode) contextNode = document;
  if (null == resultType) resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE;
  return document.evaluate(query, contextNode, null, resultType, null);
}

var xpath1 = function (query, contextNode) {
  return xpath(query, contextNode, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
}

var init = function () {
  // Check whether we are on the user's own page.
  if (!unsafeWindow.deviantART.deviant) return;
  var dm = unsafeWindow.deviantART.deviant;
  if (!dm || !dm.username) return;
  if (document.location.href.substr(7, dm.username.length).toLowerCase() != dm.username.toLowerCase())
    return;
  
  if (document.editThisPostRun == 1) {
    alert('Already applied. Not running again.');
    return;
  }
  
  var style = document.createElement('style');
  style.type = 'text/css';
  style.innerHTML = '.moeffju_edit-post-link { float: right; background-color: #bbde5c; padding: 3px; -moz-border-radius: 3px; }';
  document.getElementsByTagName('head')[0].appendChild(style);
  
  var journals = xpath("//div[contains(@class,'journalbox')]");
  for (var i = journals.snapshotLength - 1; i >= 0; i--) {
    var s = journals.snapshotItem(i);
    var jid;
    if (/\/journal\/\d+\//.test(document.location.href)) {
      jid = document.location.href.replace(/.*\/(\d+)\/?$/, '$1');
    }
    else {
      jid = xpath("./div[3]/a/@href", s, XPathResult.STRING_TYPE).stringValue.replace(/.*\/(\d+)\/?$/, '$1');
    }
    
    var el = document.createElement('a');
    el.href = ['http://my.deviantart.com/journal/edit/', jid].join('');
    el.className = 'moeffju_edit-post-link';
    el.textContent = 'Edit Post';
    
    var target = xpath1("./div[1]/h2", s);
    target.parentNode.insertBefore(el, target);
  }
  
  document.editThisPostRun = 1;

  return;
}

init();
