//==========================================
// Set up
//==========================================

// Sniffer based on http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html

var uagent    = navigator.userAgent.toLowerCase();
var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) );
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) );
var is_moz    = (navigator.product == 'Gecko');
var is_ns     = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) );
var is_ns4    = ( (is_ns) && (parseInt(navigator.appVersion) == 4) );
var is_opera  = (uagent.indexOf('opera') != -1);
var is_kon    = (uagent.indexOf('konqueror') != -1);
var is_webtv  = (uagent.indexOf('webtv') != -1);

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) );
var is_mac    = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") );
var ua_vers   = parseInt(navigator.appVersion);
	
// IBC Code stuff
var text_enter_url      = "Введите полный URL ссылки";
var text_enter_url_name = "Введите название сайта";
var text_enter_image    = "Введите полный URL изображения";
var text_enter_email    = "Введите e-mail адрес";
var text_enter_flash    = "Введите полный URL для Flash.";
var text_code           = "Использование: [CODE] Здесь Ваш код.. [/CODE]";
var text_quote          = "Использование: [QUOTE] Здесь Ваша Цитата.. [/QUOTE]";
var error_no_url        = "Вы должны ввести URL";
var error_no_title      = "Вы должны ввести название";
var error_no_email      = "Вы должны ввести e-mail адрес";
var prompt_start        = "Введите текст для форматирования";
var img_title   = "Введите по какому краю выравнивать картинку (left, center, right)";
var email_title   = "Введите описание ссылки (необязательно)";
//--------------------------------------------
// Set up our simple tag open values
//--------------------------------------------

var B_open = 0;
var I_open = 0;
var U_open = 0;
var QUOTE_open = 0;
var CODE_open = 0;
var SQL_open = 0;
var HTML_open = 0;
var CENTER_open = 0;

var selField  = "gbtext";

var bbtags   = new Array();

var fombj    = 'document.usergb';

//==========================================
// Array: Get stack size
//==========================================

function stacksize(thearray)
{
	for (i = 0 ; i < thearray.length; i++ )
	{
		if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') )
		{
			return i;
		}
	}
	
	return thearray.length;
}
//==========================================
// Array: Push stack
//==========================================

function pushstack(thearray, newval)
{
	arraysize = stacksize(thearray);
	thearray[arraysize] = newval;
}
//==========================================
// Array: Pop stack
//==========================================

function popstack(thearray)
{
	arraysize = stacksize(thearray);
	theval = thearray[arraysize - 1];
	delete thearray[arraysize - 1];
	return theval;
}

function setFieldName(which)
{
            if (which != selField)
            {
				allcleartags();
                selField = which;

            }
}


//==========================================
// Set the number of tags open box
//==========================================

function cstat()
{
	var c = stacksize(bbtags);
	
	if ( (c < 1) || (c == null) ) {
		c = 0;
	}
	
	if ( ! bbtags[0] ) {
		c = 0;
	}
	

}


//==========================================
// Close all tags
//==========================================

function closeall()
{
	if (bbtags[0])
	{
		while (bbtags[0])
		{
			tagRemove = popstack(bbtags)
			var closetags = "[/" + tagRemove + "]";

			eval ("fombj." +selField+ ".value += closetags");
			
			//--------------------------------------------
			// Change the button status
			// Ensure we're not looking for FONT, SIZE or COLOR as these
			// buttons don't exist, they are select lists instead.
			//--------------------------------------------
			
			if ( (tagRemove != 'FONT') && (tagRemove != 'SIZE') && (tagRemove != 'COLOR') )
			{
if (tagRemove == 'CENTER') tagnewvalue = 'По центру'; 
else if (tagRemove == 'QUOTE') tagnewvalue = ' Цитата ';
else if (tagRemove == 'LEFT') tagnewvalue = 'Слева';
else if (tagRemove == 'RIGHT') tagnewvalue = 'Справа';
else tagnewvalue = ' '+tagRemove+' ';

				eval("fombj." + tagRemove + ".value = '" + tagnewvalue + "'");
				eval(tagRemove + "_open = 0");
			}
		}
	}

	//--------------------------------------------
	// Ensure we got them all
	//--------------------------------------------
	
	bbtags = new Array();

}
//==========================================
// Clear all tags
//==========================================

function allcleartags()
{
	if (bbtags[0])
	{
		while (bbtags[0])
		{
			tagRemove = popstack(bbtags)
			
			//--------------------------------------------
			// Change the button status
			// Ensure we're not looking for FONT, SIZE or COLOR as these
			// buttons don't exist, they are select lists instead.
			//--------------------------------------------
			
			if ( (tagRemove != 'COLOR') )
			{
				eval("fombj." + tagRemove + ".value = ' " + tagRemove + " '");
				eval(tagRemove + "_open = 0");
			}
		}
	}

	//--------------------------------------------
	// Ensure we got them all
	//--------------------------------------------
	
	bbtags = new Array();

}

//==========================================
// EMOTICONS
//==========================================

function emoticon(theSmilie)
{
	doInsert(" " + theSmilie + " ", "", false);
}

function pagebreak()
{
	doInsert("{PAGEBREAK}", "", false);
}
//==========================================
// ADD CODE
//==========================================

function add_code(NewCode)
{
    fombj.selField.value += NewCode;
    fombj.selField.focus();
}

//==========================================
// ALTER FONT
//==========================================

function alterfont(theval, thetag)
{
    if (theval == 0)
    	return;
	
	if(doInsert("[" + thetag + "=" + theval + "]", "[/" + thetag + "]", true))
		pushstack(bbtags, thetag);
	

    fombj.fcolor.selectedIndex = 0;
    
    cstat();
	
}


//==========================================
// SIMPLE TAGS (such as B, I U, etc)
//==========================================

function simpletag(thetag)
{
	var tagOpen = eval(thetag + "_open");
	

		if (tagOpen == 0)
		{
			if(doInsert("[" + thetag + "]", "[/" + thetag + "]", true))
			{
				eval(thetag + "_open = 1");
				
				//--------------------------------------------
				// Change the button status
				//--------------------------------------------
				
				eval("fombj." + thetag + ".value += '*'");
		
				pushstack(bbtags, thetag);
				cstat();

			}
		}
		else
		{
			//--------------------------------------------
			// Find the last occurance of the opened tag
			//--------------------------------------------
			lastindex = 0;
			
			for (i = 0 ; i < bbtags.length; i++ )
			{
				if ( bbtags[i] == thetag )
				{
					lastindex = i;
				}
			}
			
			//--------------------------------------------
			// Close all tags opened up to that tag was opened
			//--------------------------------------------
			
			while (bbtags[lastindex])
			{
				tagRemove = popstack(bbtags);
				doInsert("[/" + tagRemove + "]", "", false)

var tagnewvalue = false;
			
				//--------------------------------------------
				// Change the button status
				//--------------------------------------------
				
				if ( (tagRemove != 'FONT') && (tagRemove != 'SIZE') && (tagRemove != 'COLOR') )
				{
if (tagRemove == 'CENTER') tagnewvalue = 'По центру'; 
else if (tagRemove == 'QUOTE') tagnewvalue = ' Цитата ';
else if (tagRemove == 'LEFT') tagnewvalue = 'Слева';
else if (tagRemove == 'RIGHT') tagnewvalue = 'Справа';
else if (tagRemove == 'NEXT') tagnewvalue = 'Следующая страница';  
else tagnewvalue = ' '+tagRemove+' ';


					eval("fombj." + tagRemove + ".value = '" + tagnewvalue + "'");
					eval(tagRemove + "_open = 0");
				}
			}
			
			cstat();
		}

}

//==========================================
// PAGE tag
//==========================================

function pagelink()
{
    var FoundErrors = '';
	var thesel ='';
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
	thesel = document.selection.createRange().text;
	} else thesel ='Страница';

    if (!thesel) {
        thesel ='Страница';
    }

    var enterURL   = prompt(text_enter_page, "1");
    var enterTITLE = prompt(text_enter_page_name, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE) {
        FoundErrors += " " + error_no_title;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[PAGE="+enterURL+"]"+enterTITLE+"[/PAGE]", "", false);
}

//==========================================
// URL tag
//==========================================

function tag_url()
{
    var FoundErrors = '';
	var thesel ='';
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
	thesel = document.selection.createRange().text;
	} else thesel ='My Webpage';

    if (!thesel) {
        thesel ='My Webpage';
    }

    var enterURL   = prompt(text_enter_url, "http://");
    var enterTITLE = prompt(text_enter_url_name, thesel);

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }
    if (!enterTITLE) {
        FoundErrors += " " + error_no_title;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

	doInsert("[URL="+enterURL+"]"+enterTITLE+"[/URL]", "", false);
}

//==========================================
// Insert attachment tag
//==========================================

function insert_attach_to_textarea(aid)
{
	doInsert( "[attachmentid="+aid+"]" );
}

//==========================================
// Image tag
//==========================================

function tag_image()
{
    var FoundErrors = '';
    var enterURL   = prompt(text_enter_image, "http://");

    var Title = prompt(img_title, "left");

    if (!enterURL) {
        FoundErrors += " " + error_no_url;
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors);
        return;
    }

if (Title == "center") {
	doInsert("[CENTER][IMG]"+enterURL+"[/IMG][/CENTER]", "", false);
}
else {
	doInsert("[IMG="+Title+"]"+enterURL+"[/IMG]", "", false);
}
if (Title == "")
           {
	doInsert("[IMG]"+enterURL+"[/IMG]", "", false);
           }

}

function tag_email()
{
    var emailAddress = prompt(text_enter_email, "");

    if (!emailAddress) { 
		alert(error_no_email); 
		return; 
	}

	var thesel ='';
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
	thesel = document.selection.createRange().text;
	} else thesel ='';

    if (!thesel) {
        thesel ='';
    }

	var Title = prompt(email_title, thesel);

if (!Title) Title = emailAddress;

	doInsert("[EMAIL="+emailAddress+"]"+Title+"[/EMAIL]", "", false);
}

//--------------------------------------------
// GENERAL INSERT FUNCTION
//--------------------------------------------
// ibTag: opening tag
// ibClsTag: closing tag, used if we have selected text
// isSingle: true if we do not close the tag right now
// return value: true if the tag needs to be closed later

//

function doInsert(ibTag, ibClsTag, isSingle)
{
	var isClose = false;

	var obj_ta = eval(fombj + '.' + selField);

	//----------------------------------------
	// It's IE!
	//----------------------------------------
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
		if (obj_ta.isTextEdit)
		{
			obj_ta.focus();
			var sel = document.selection;
			var rng = sel.createRange();
			rng.colapse;
			if((sel.type == "Text" || sel.type == "None") && rng != null)
			{
				if(ibClsTag != "" && rng.text.length > 0)
					ibTag += rng.text + ibClsTag;
				else if(isSingle)
					isClose = true;
	
				rng.text = ibTag;
			}
		}
		else
		{
			if(isSingle)
			{
				isClose = true;
			}
			
			obj_ta.value += ibTag;
		}
	}
	//----------------------------------------
	// It's MOZZY!
	//----------------------------------------
	
	else if ( obj_ta.selectionEnd )
	{ 
		var ss = obj_ta.selectionStart;
		var st = obj_ta.scrollTop;
		var es = obj_ta.selectionEnd;
		
		if (es <= 2)
		{
			es = obj_ta.textLength;
		}
		
		var start  = (obj_ta.value).substring(0, ss);
		var middle = (obj_ta.value).substring(ss, es);
		var end    = (obj_ta.value).substring(es, obj_ta.textLength);
		
		//-----------------------------------
		// text range?
		//-----------------------------------
		
		if (obj_ta.selectionEnd - obj_ta.selectionStart > 0)
		{
			middle = ibTag + middle + ibClsTag;
		}
		else
		{
			middle = ibTag + middle;
			
			if (isSingle)
			{
				isClose = true;
			}
		}
		
		obj_ta.value = start + middle + end;
		
		var cpos = ss + (middle.length);
		
		obj_ta.selectionStart = cpos;
		obj_ta.selectionEnd   = cpos;
		obj_ta.scrollTop      = st;


	}
	//----------------------------------------
	// It's CRAPPY!
	//----------------------------------------
	else
	{
		if (isSingle)
		{
			isClose = true;
		}
		
		obj_ta.value += ibTag;
	}
	
	obj_ta.focus();

	return isClose;
}		

