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

//
// By iescripts.org
// Ported from http://userscripts.org/scripts/show/1419
//

(function(){

textArray = new Array();

tagIt = function(tagOpen,tagClose,i) {
	// most of this bit is from http://placenamehere.com/photographica/js_textareas.html
	var ta = textArray[i];
	var st = ta.scrollTop;
		
	if (document.selection) { //IE win
		// code ripped/modified from Meg Hourihan 
		// http://www.oreillynet.com/pub/a/javascript/2001/12/21/js_toolbar.html
		var str = document.selection.createRange().text;
		ta.focus();
		var sel = document.selection.createRange();
		sel.text = tagOpen + str + tagClose;
	} else 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;
	}	
}

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

//textareas = document.evaluate("//textarea",document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);

textareas = document.getElementsByTagName('textarea');

for (i=0; i<textareas.length; i++) {
	textArray[i] = textareas[i];
	var accessBar = document.createElement("div");
	accessBar.setAttribute('style','');
	accessBar.innerHTML = "<a href=\"javascript:tagIt('<i>','</i>',"+ i +")\"><i>italic</i></a> " +
		"<a href=\"javascript:tagIt('<b>','</b>',"+ i +")\"><b>bold</b></a> " +
		"<a href=\"javascript:tagIt('<blockquote>','</blockquote>',"+ i +")\">quote</a> " +
		"<a href=\"javascript:linkIt("+i+")\">link</a>";
	
	textArray[i].parentNode.insertBefore(accessBar, textArray[i]);
}

})();
