// Startup variables
var bbcode_imageTag = false;
var bbcode_flashTag = false;
var bbcode_selection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var bbcode_clientPC = navigator.userAgent.toLowerCase(); // Get client info
var bbcode_clientVer = parseInt(navigator.appVersion); // Get browser version

var bbcode_isIE = ((bbcode_clientPC.indexOf("msie") != -1) && (bbcode_clientPC.indexOf("opera") == -1));
var bbcode_isMoz  = ((bbcode_clientPC.indexOf('mozilla')!=-1) && (bbcode_clientPC.indexOf('spoofer')==-1)
&& (bbcode_clientPC.indexOf('compatible') == -1) && (bbcode_clientPC.indexOf('opera')==-1)
&& (bbcode_clientPC.indexOf('webtv')==-1) && (bbcode_clientPC.indexOf('hotjava')==-1));

var bbcode_isWin   = ((bbcode_clientPC.indexOf("win")!=-1) || (bbcode_clientPC.indexOf("16bit") != -1));
var bbcode_isMac    = (bbcode_clientPC.indexOf("mac")!=-1);


// Helpline messages
b_help = "Удебелен текст: [b]текст[/b]  (alt+b)";
i_help = "Наклонен текст: [i]текст[/i]  (alt+i)";
u_help = "Подчертан текст: [u]текст[/u]  (alt+u)";
q_help = "Цитат: [quote]текст[/quote] или [quote=име]текст[/quote] (alt+q)";
c_help = "Код: [code]код[/code]  (alt+c)";
p_help = "Картинка: [img]http://image_url[/img]  (alt+p)";
w_help = "URL: [url]http://url[/url] или [url=http://url]URL текст[/url]  (alt+w)";
a_help = "Затвори всички bbCode тагове";
rm_help = "Премахва всички тагове в посочения текст";
s_help = "Цвят на текст: [color=red]текст[/color]  Можете да използвате и color=#FF0000";
f_help = "Големина на текст: [size=x-small]малък текст[/size]";
sh_help = "Сянка: [shadow=red,left,1]текст[/shadow]";
g_help = "Glow: [glow=red,2,1]текст[/glow]";
al_help = "Подреждане: [align=center]текст[/align]";
t_help = "Телетекст: [tt]текст[/tt]";
ff_help = "Шрифт: [font=verdana]текст[/font]";
h_help = "Хоризонтална линия: [hr]";
li_help = "Списък: [li]текст[/li]";
ul_help = "Точка от списък: [ul]текст[/ul]";
ol_help = "Номер от списък: [ol]текст[/ol]";
m_help = "Move: [move]текст[/move]";
fl_help = "Флаш: [flash=200,200]URL[/flash]";
sb_help = "Под-текст: [sub]текст[/sub]";
sp_help = "Над-текст: [sup]текст[/sup]";
st_help = "Задраскан текст: [s]текст[/s] (alt+s)";
e_help = "Email: [email]name@domain[/email] или [email=name@domain]email текст[/email]  (alt+e)";
bl_help = "Block text: [block=right,200]text[/block]";
im_help = "Choose/Upload image from the gallery";
cut_help = "Cut the selection to your clipboard";
copy_help = "Copy the selection to your clipboard";
paste_help = "Paste the selection from your clipboard";
cell_help = "Table cell: [cell]text[/cell] (row+table required)";
row_help = "Table Row: [row]text[/row] (table required)";
table_help = "Table: [table]text[/table]";

if (typeof bbcode_field != 'undefined' && bbcode_field) {
    if (typeof hookEvent != 'undefined') {
        hookEvent(bbcode_field, 'onselect', function (e) { storeCaret(this); });
        hookEvent(bbcode_field, 'onclick', function (e) { storeCaret(this); });
        hookEvent(bbcode_field, 'onkeyup', function (e) { storeCaret(this); });
        hookEvent(bbcode_field, 'onload', function (e) { storeCaret(this); });
    } else {
        bbcode_field.onselect = function () { storeCaret(this); }
        bbcode_field.onclick = function () { storeCaret(this); }
        bbcode_field.onkeyup = function () { storeCaret(this); }
        bbcode_field.onload = function () { storeCaret(this); }
    }
} else {
    delete bbcode_field;
    delete bbcode_form;
}

// Define the bbCode tags
bbcode_open = new Array();
bbcode_tags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[s]','[/s]','[sub]','[/sub]','[sup]','[/sup]','[shadow=red,left,1]','[/shadow]','[glow=red,2,1]','[/glow]','[tt]','[/tt]','[hr]','[move]','[/move]','[quote]','[/quote]','[code]','[/code]','[img]','[/img]','[url]','[/url]','[email]','[/email]','[flash=200,200]','[/flash]','[align=left]','[/align]');
//bbcode_tags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[img]','[/img]','[url]','[/url]');

// Shows the help messages in the helpline window
function helpline(help) {
    if (bbcode_form && bbcode_form.helpbox) {
        bbcode_form.helpbox.value = eval(help + "_help");
    }
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
    for (i = 0; i < thearray.length; i++) {
        if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null)) return i;
    }
    return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
    thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
    thearraysize = getarraysize(thearray);
    retval = thearray[thearraysize - 1];
    delete thearray[thearraysize - 1];
    return retval;
}


function checkForm() {
    formErrors = false;

    if (bbcode_field.value.length < 2 || bbcode_form.comment_headline.length < 1) {
        alert("Fill all fields!");
        return false;
    }
    bbstyle(-1);

    if (bbcode_form) {
        if (bbcode_form.postbutton) {
            bbcode_form.postbutton.disabled=true;
        }
        if (bbcode_form.submit) {
            bbcode_form.submit.disabled=true;
        }
    }

    return true;
}

function emoticon(text, space) {
    if (space) {
        space = '';
    } else {
        space=' ';
    }
    text = space + text + space;
    insertAtCaret(bbcode_field, text);
    bbcode_field.focus();
}

function bbfontstyle(bbopen, bbclose) {
    if ((bbcode_clientVer >= 4) && bbcode_isIE && bbcode_isWin) {
        bbcode_selection = document.selection.createRange().text;
        if (!bbcode_selection) {
            bbcode_field.value += bbopen + bbclose;
            bbcode_field.focus();
            return;
        }
        document.selection.createRange().text = bbopen + bbcode_selection + bbclose;
        bbcode_field.focus();
        return;
    } else {
        bbcode_field.value += bbopen + bbclose;
        bbcode_field.focus();
        return;
    }
    storeCaret(bbcode_field);
}


function bbstyle(bbnumber) {
    var donotinsert = false;
    var bblast = 0;
    bbcode_selection = false;

    if (bbnumber == -1) { // Close all open tags & default button names
        while (bbcode_open[0]) {
            butnumber = arraypop(bbcode_open) - 1;
            bbcode_field.value += bbcode_tags[butnumber + 1];
            buttext = eval('bbcode_form.addbbcode' + butnumber + '.value');
            eval('bbcode_form.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
        }
        bbcode_imageTag = false; // All tags are closed including image tags :D
        bbcode_flashTag = false;
        bbcode_field.focus();
        return;
    }

    if ((bbcode_clientVer >= 4) && bbcode_isIE && bbcode_isWin)
    bbcode_selection = document.selection.createRange().text; // Get text selection

    if (bbcode_selection) {
        // Add tags around selection
        document.selection.createRange().text = bbcode_tags[bbnumber] + bbcode_selection + bbcode_tags[bbnumber+1];
        bbcode_field.focus();
        bbcode_selection = '';
        return;
    }

    // Find last occurance of an open tag the same as the one just clicked
    for (i = 0; i < bbcode_open.length; i++) {
        if (bbcode_open[i] == bbnumber+1) {
            bblast = i;
            donotinsert = true;
        }
    }

    if (donotinsert) {                // Close all open tags up to the one just clicked & default button names
        while (bbcode_open[bblast]) {
            butnumber = arraypop(bbcode_open) - 1;
            bbcode_field.value += bbcode_tags[butnumber + 1];
            buttext = eval('bbcode_form.addbbcode' + butnumber + '.value');
            eval('bbcode_form.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
            bbcode_imageTag = false;
            bbcode_flashTag = false;
        }
        bbcode_field.focus();
        return;
    } else { // Open tags

        if (bbcode_imageTag && (bbnumber != 25)) {                // Close image tag before adding another
            bbcode_field.value += bbcode_tags[26];
            lastValue = arraypop(bbcode_open) - 1;        // Remove the close image tag from the list
            bbcode_form.addbbcode25.value = "Img";        // Return button back to normal state
            bbcode_imageTag = false;
        }
        if (bbcode_flashTag && (bbnumber != 31)) {                // Close image tag before adding another
            bbcode_field.value += bbcode_tags[32];
            lastValue = arraypop(bbcode_open) - 1;        // Remove the close image tag from the list
            bbcode_form.addbbcode31.value = "Flash";        // Return button back to normal state
            bbcode_flashTag = false;
        }
        // Open tag
        bbcode_field.value += bbcode_tags[bbnumber];
        if ((bbnumber == 25) && (bbcode_imageTag == false)) bbcode_imageTag = 1 // Check to stop additional tags after an unclosed image tag
        if ((bbnumber == 31) && (bbcode_flashTag == false)) bbcode_flashTag = 1
        arraypush(bbcode_open,bbnumber+1);
        eval('bbcode_form.addbbcode'+bbnumber+'.value += "*"');
        bbcode_field.focus();
        return;
    }
    storeCaret(bbcode_field);
}


function set_clipboard(clear) {
    var text_field = bbcode_field;
    var selectedHtml = text_select(text_field);
    var res = false;
    if (selectedHtml!= "") {
        if (window.clipboardData) {
            res = window.clipboardData.setData("Text", selectedHtml);
        }
    }
    if (clear && res) {
        text_replace(comment_text, "");
        text_field.focus();
    }
}

function get_clipboard() {
    var text_field = bbcode_field;
    text_field.focus();
    if (document.selection) {
        var selectedHtml = document.selection.createRange();
        selectedHtml.execCommand("paste");
    }
}

function text_select(text_field) {
    if ((bbcode_clientVer >= 4) && bbcode_isIE && bbcode_isWin) {
        bbcode_selection = document.selection.createRange().text; // Get text selection
        if (bbcode_selection) {
            return bbcode_selection;
        }
    } else if (text_field.selectionEnd && (text_field.selectionEnd - text_field.selectionStart > 0)) {
        var selLength = text_field.textLength;
        var selStart = text_field.selectionStart;
        var selEnd = text_field.selectionEnd;
        if (selEnd == 1 || selEnd == 2) {
            selEnd = selLength;
        }
        return (text_field.value).substring(selStart, selEnd);
    }
    return false;
}

function text_replace(text_field, new_text) {
    if ((bbcode_clientVer >= 4) && bbcode_isIE && bbcode_isWin) {
        bbcode_selection = document.selection.createRange().text;
        if (bbcode_selection) {
            document.selection.createRange().text = new_text;
        }
    } else if (text_field.selectionEnd && (text_field.selectionEnd - text_field.selectionStart > 0)) {
        var selLength = text_field.textLength;
        var selStart = text_field.selectionStart;
        var selEnd = text_field.selectionEnd;
        if (selEnd == 1 || selEnd == 2) {
            selEnd = selLength;
        }

        var s1 = (text_field.value).substring(0,selStart);
        var s2 = (text_field.value).substring(selStart, selEnd)
        var s3 = (text_field.value).substring(selEnd, selLength);
        text_field.value = s1 + new_text + s3;
    }
}

function storeCaret(text_field) {
    if (text_field.createTextRange) text_field.caretPos = document.selection.createRange().duplicate();
}

function insertAtCaret(text_field, new_text) {
    if (document.all) {
        if (text_field.createTextRange && text_field.caretPos) {
            var caretPos = text_field.caretPos;
            caretPos.text = (caretPos.text.length ? caretPos.text : '') + (caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? new_text + ' ' : new_text);
        } else {
            text_field.value += new_text;
        }
    } else {
        if (text_field.setSelectionRange){
            var rangeStart = text_field.selectionStart;
            var rangeEnd = text_field.selectionEnd;
            var tempStr1 = text_field.value.substring(0, rangeStart);
            var tempStr2 = text_field.value.substring(rangeStart);
            text_field.value = tempStr1 + new_text + tempStr2;
        } else {
            alert("This version of Mozilla based browser does not support setSelectionRange");
        }
    }
}

