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/*
// @exclude     http://how-to-learn-any-language.com/forum/login_user.asp*
// @grant       none
// ==/UserScript==
function addBBCode_delegate(open,close) {
    return function(){
        addBBCode(open,close)
    }
}

var buttons = ["B","I","U","URL","EMAIL","CENTER","LIST","INDENT","IMG"];
var style = ["bold","italic","underline","url","email","center","list","indent","image"];

var links = document.querySelectorAll("form a");
for(var i = 0; i < links.length; i++) {
    links[i].href = "JavaScript:addBBCode()";
    links[i].id = style[i];
}

for (var i = 0; i < buttons.length; i++) {
    open = '[' + buttons[i] + ']';
    close = '[/' + buttons[i] + ']';
    document.getElementById(style[i]).addEventListener('click', addBBCode_delegate(open,close), 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;
}