// ==UserScript==
// @name          Vox Rich Edit
// @description	  Adds a simple rich edit interface (Bold, Italic, Blockquote, Link) to any comment textarea on Vox.
// @namespace     http://www.rhyley.org/gm/
// @include       http://*.vox.com/*
// ==/UserScript==

unsafeWindow.ta = document.getElementById('comment-text');

if (unsafeWindow.ta) {

	unsafeWindow.tagIt = function (tagOpen,tagClose) {
		// most of this bit is from http://placenamehere.com/photographica/js_textareas.html
		var ta = unsafeWindow.ta;
		var st = ta.scrollTop;

		if (ta.selectionStart | ta.selectionStart == 0) { // Mozzzzzzila relies on builds post bug #88049
			// work around Mozilla Bug #190382
			if (ta.selectionEnd > ta.value.length) { ta.selectionEnd = ta.value.length; }

			// decide where to add it and then add it
			var firstPos = ta.selectionStart;
			var secondPos = ta.selectionEnd+tagOpen.length; // cause we're inserting one at a time

			ta.value=ta.value.slice(0,firstPos)+tagOpen+ta.value.slice(firstPos);
			ta.value=ta.value.slice(0,secondPos)+tagClose+ta.value.slice(secondPos);

			// reset selection & focus... after the first tag and before the second 
			ta.selectionStart = firstPos+tagOpen.length;
			ta.selectionEnd = secondPos;
			//ta.focus();
			ta.scrollTop=st;
		}	
	}

	unsafeWindow.linkIt = function () {
		var myLink = prompt("Enter URL:","http://");
		if (myLink != null) {
			unsafeWindow.tagIt('<a href="' +myLink+ '">','</a>');
		}
	}

	var TiG = document.evaluate("//p[@class='comment-form-props']",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(0);
	TiG.innerHTML += " | <a href=\"javascript:tagIt('<i>','</i>');\"><i>italic</i></a> " +
		"<a href=\"javascript:tagIt('<b>','</b>');\"><b>bold</b></a> " +
		"<a href=\"javascript:tagIt('> ','');\">quote</a> " +
		"<a href=\"javascript:linkIt();\">link</a>";
}