$(document).ready(function(){
    $('.toolbar li a, .bb_link').click(function(){
        $(this).blur();
        var button_id = attribs = $(this).attr('rel');
        var def = $(this).attr('def');
        button_id = button_id.replace(/\[.*\]/, '');
        if (/\[.*\]/.test(attribs)) {
            attribs = attribs.replace(/.*\[(.*)\]/, '$1');
        }
        else 
            attribs = '';
        if (def) {
            def = def.replace(/\\r/gi, "\r\n");
        }
        var start = '[' + button_id + attribs + ']' + (def ? def : '');
        var end = '[/' + button_id + ']';
        insert(start, end);
        if ($(this).attr('showform')) {
            $('html').scrollTop($('.sendComment').position().top);
        }
        return false;
    });
});
function insert(start, end){
    element = document.getElementById('bb_body');
    var top = element.scrollTop;
    if (document.selection) {
        element.focus();
        sel = document.selection.createRange();
        sel.text = start + sel.text + end;
    }
    else {
        if (element.selectionStart || element.selectionStart == '0') {
            element.focus();
            var startPos = element.selectionStart;
            var endPos = element.selectionEnd;
            element.value = element.value.substring(0, startPos) + start + element.value.substring(startPos, endPos) + end + element.value.substring(endPos, element.value.length);
            element.selectionStart = element.selectionEnd = startPos + element.value.substring(startPos, endPos).length + start.length;
            element.scrollTop = top;
        }
        else {
            element.value += start + end;
        }
    }
}

