File: HTLAL_postbox.user.js - Tab length: 1 2 4 8 - Lines: on off - No wrap: on off

?// ==UserScript==
// @name        HTLAL PostBox
// @description Makes writing posts easier
// @match       http://how-to-learn-any-language.com/forum/*
// @grant       none
// ==/UserScript==

var buttons = ["B","I","U","URL","IMG"];
var style = ["bold","italic","underline","url","image"];

for (var i = 0; i < buttons.length; i++) {
    regex = new RegExp("<a.*?JavaScript:Add.*?'"+buttons[i]+"'.*?>");
    document.body.innerHTML = document.body.innerHTML.replace(regex, '<a id="'+style[i]+'" href="JavaScript:addBBCode()">');
}
document.getElementById('bold').addEventListener('click', function () { addBBCode('[B]','[/B]'); }, false);
document.getElementById('italic').addEventListener('click', function () { addBBCode('[I]','[/I]'); }, false);
document.getElementById('underline').addEventListener('click', function () { addBBCode('[U]','[/U]'); }, false);
document.getElementById('url').addEventListener('click', function () { addBBCode('[URL]','[/URL]'); }, false);
document.getElementById('image').addEventListener('click', function () { addBBCode('[IMG]','[/IMG]'); }, false);

function addBBCode(open, close)
{
    var textareas = document.getElementsByTagName('textarea');  // grab the textarea element
    var textarea = textareas[0];
    textarea.focus();                           // put cursor into textarea
    var start = textarea.selectionStart;        // find the start and end of the selection (if available) in textarea
    var end = textarea.selectionEnd;
    var length = textarea.textLength;           // we need these 3 values to split up the text
    var before = textarea.value.substring(0,start);
    var between = textarea.value.substring(start, end);
    var after = textarea.value.substring(end, length);
    textarea.value = before + open + between + close + after;
    var position = end + open.length + close.length;
    if(start-end == 0)
        position = start+open.length;
    textarea.setSelectionRange(position,position);  // put cursor just after the last added tag
    return;
}