/**
 * @author igorf
 */
// bbCode control by
// subBlue design
// www.subBlue.com

// Startup variables
var imageTag = false;
var theSelection = 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 clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla') != -1) && (clientPC.indexOf('spoofer') == -1) &&
(clientPC.indexOf('compatible') == -1) &&
(clientPC.indexOf('opera') == -1) &&
(clientPC.indexOf('webtv') == -1) &&
(clientPC.indexOf('hotjava') == -1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win") != -1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac") != -1);

var areaName = "post[text]";
var bbColor = "black";

// Helpline messages
b_help = "Жирный текст: [b]текст[/b]  (alt+b)";
i_help = "Наклонный текст: [i]текст[/i]  (alt+i)";
u_help = "Подчёркнутый текст: [u]текст[/u]  (alt+u)";
q_help = "Цитата: [quote]текст[/quote]  (alt+q)";
c_help = "Код (программа): [code]код[/code]  (alt+c)";
l_help = "Список: [list]текст[/list] (alt+l)";
o_help = "Нумерованный список: [list=]текст[/list]  (alt+o)";
p_help = "Вставить картинку: [img]http://image_url[/img]  (alt+p)";
w_help = "Вставить ссылку: [url]http://url[/url] или [url=http://url]текст ссылки[/url]  (alt+w)";
a_help = "Закрыть все открытые теги bbCode";
s_help = "Цвет шрифта: [color=red]текст[/color]  Подсказка: можно использовать color=#FF0000";
f_help = "Размер шрифта: [size=x-small]маленький текст[/size]";
y_help = "Видео с youtube.com: [youtube]код видео[/youtube]";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]', '[quote]', '[/quote]', '[code]', '[/code]', //0-8
 '[list]', '[/list]', '[list=]', '[/list]', '[img]', '[/img]', '[url]', '[/url]', '[size=x-large]', '[/size]', //10-18
 '[size=x-small]', '[/size]', '[color]', '[/color]', '[s]', '[/s]', '[youtube]', '[/youtube]');

imageTag = false;

// Shows the help messages in the helpline window
function helpline(help){
    document.post.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 (document.getElementById(areaName).value.length < 2) {
        formErrors = "Вы должны ввести текст сообщения";
    }
    
    if (formErrors) {
        alert(formErrors);
        return false;
    }
    else {
        bbstyle(-1);
        //formObj.preview.disabled = true;
        //formObj.submit.disabled = true;
        return true;
    }
}

function emoticon(text){
    var txtarea = document.getElementById(areaName);
    text = ' ' + text + ' ';
    if (txtarea.createTextRange && txtarea.caretPos) {
        var caretPos = txtarea.caretPos;
        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
        txtarea.focus();
    }
    else {
        txtarea.value += text;
        txtarea.focus();
    }
}

function bbfontstyle(bbopen, bbclose){
    var txtarea = document.getElementById(areaName);
    
    if ((clientVer >= 4) && is_ie && is_win) {
        theSelection = document.selection.createRange().text;
        if (!theSelection) {
            txtarea.value += bbopen + bbclose;
            txtarea.focus();
            return;
        }
        document.selection.createRange().text = bbopen + theSelection + bbclose;
        txtarea.focus();
        return;
    }
    else 
        if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
            mozWrap(txtarea, bbopen, bbclose);
            return;
        }
        else {
            txtarea.value += bbopen + bbclose;
            txtarea.focus();
        }
    storeCaret(txtarea);
}


function bbstyle(bbnumber)
{
    var txtarea = document.getElementById(areaName);
    
    txtarea.focus();
    donotinsert = false;
    theSelection = false;
    bblast = 0;
    
    if (bbnumber == -1) { // Close all open tags & default button names
        while (bbcode[0]) {
            butnumber = arraypop(bbcode) - 1;
            txtarea.value += bbtags[butnumber + 1];
            //			buttext = eval('document.post.addbbcode' + butnumber + '.value');
            //			eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
        }
        imageTag = false; // All tags are closed including image tags :D
        txtarea.focus();
        return;
    }
    
    openTag = bbtags[bbnumber];
    closeTag = bbtags[bbnumber + 1];
    
    if (bbnumber == 22)//[color]
    {
        openTag = '[color=' + bbColor + ']';
    }
    
    if ((clientVer >= 4) && is_ie && is_win) {
        theSelection = document.selection.createRange().text; // Get text selection
        if (theSelection) {
            // Add tags around selection
            document.selection.createRange().text = openTag + theSelection + closeTag;
            txtarea.focus();
            theSelection = '';
            return;
        }
    }
    else 
        if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0)) {
            mozWrap(txtarea, openTag, closeTag);
            return;
        }
    
    // Find last occurance of an open tag the same as the one just clicked
    for (i = 0; i < bbcode.length; i++) {
        if (bbcode[i] == bbnumber + 1) {
            bblast = i;
            donotinsert = true;
        }
    }
    
    if (donotinsert) { // Close all open tags up to the one just clicked & default button names
        while (bbcode[bblast]) {
            butnumber = arraypop(bbcode) - 1;
            txtarea.value += bbtags[butnumber + 1];
            //				buttext = eval('document.post.addbbcode' + butnumber + '.value');
            //				eval('document.post.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
            imageTag = false;
        }
        txtarea.focus();
        return;
    }
    else { // Open tags
        if (imageTag && (bbnumber != 14)) { // Close image tag before adding another
            txtarea.value += bbtags[15];
            lastValue = arraypop(bbcode) - 1; // Remove the close image tag from the list
            //			document.post.addbbcode14.value = "Img";	// Return button back to normal state
            imageTag = false;
        }
        
        // Open tag
        txtarea.value += openTag;
        if ((bbnumber == 14) && (imageTag == false)) 
            imageTag = 1; // Check to stop additional tags after an unclosed image tag
        arraypush(bbcode, bbnumber + 1);
        //		eval('document.post.addbbcode'+bbnumber+'.value += "*"');
        txtarea.focus();
        return;
    }
    storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close){
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    if (selEnd == 1 || selEnd == 2) 
        selEnd = selLength;
    
    var s1 = (txtarea.value).substring(0, selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd)
    var s3 = (txtarea.value).substring(selEnd, selLength);
    txtarea.value = s1 + open + s2 + close + s3;
    return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl){
    if (textEl.createTextRange) 
        textEl.caretPos = document.selection.createRange().duplicate();
}

//========================================================
var bbWebColors = new Array(new Array('Black', 'Maroon', 'Green', 'Navy'), new Array('Silver', 'Red', 'Lime', 'Blue'), new Array('Gray', 'Purple', 'Olive', 'Teal'), new Array('White', 'Fuchsia', 'Yellow', 'Aqua'));
function bb_getCoords(element) 
{
    var left = element.offsetLeft;
    var top = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
        left += parent.offsetLeft;
        top += parent.offsetTop;
    }
    return {
    	left: left,
    	top: top,
    	width: element.offsetWidth,
    	height: element.offsetHeight
    };
}

var list_down = '';

function bb_dropList(anchorDiv, htmlText)
{
	div = document.getElementById('bb_div');
    coords = bb_getCoords(document.getElementById(anchorDiv));
	
	if (anchorDiv != list_down) 
	{
		div.style.left = coords['left'] + 'px';
		div.style.top = coords['top'] + coords['height'] + 'px';
		
		div.innerHTML = htmlText;
		div.style.display = '';
		list_down = anchorDiv;
	}
	else
	{
		div.style.display = 'none';
		list_down = '';
	}
}
function bb_colorList()
{
    html = '<table border="0" cellpadding="0" cellspacing="1">';
	
    for (i = 0; bbWebColors[i]; ++i) 
	{
        html += '<tr>';
        for (j = 0; bbWebColors[i][j]; ++j) 
		{
            html += '<td height="20" width="20" bgcolor="' + bbWebColors[i][j] +
            '" onclick="bb_setColor(\'' +
            bbWebColors[i][j] +
            '\');"><a href="#bb_editor" class="opt_color"><img alt="' +
            bbWebColors[i][j] +
            '"  src="/images/pixel.gif" height="20" width="20" style="border: 1px solid gray;" /></a></td>';
        }
        html += '</tr>';
    }
	
    html += '</table>';

	bb_dropList('bb_color', html);
	
    return false;
}

function bb_setColor(name)
{
	bbColor = name;
	bbstyle(22);
	document.getElementById('bb_div').style.display = 'none';
}

function bb_insertSmile(num)
{
    var smile_code = '[smile=' + num + ']';
	emoticon(smile_code);
	document.getElementById('bb_div').style.display = 'none';
}

function bb_smileList()
{
	smileys = 18;
	
    html = '<table border="0" cellpadding="0" cellspacing="0">';
	
    for (i = 0; i < 5; ++i) 
	{
        html += '<tr>';
        for (j = 1; j <= 4; ++j) 
		{
			num = i*4 + j;
			
			if(num > smileys) break;
			if(num < 10) num = '0' + num;

            html += '<td height="16" width="16" bgcolor="white"' +
            '" onclick="bb_insertSmile(\'' +
            num +
            '\');"><a href="#bb_editor" class="opt_color"><img ' +
            '"  src="/forum/images/smiles/' + num + '.gif" height="16" width="16" style="border: 1px solid gray;" /></a></td>';
        }
        html += '</tr>';
    }
	
    html += '</table>';

	bb_dropList('bb_smile', html);
	
    return false;
}