//
// Set up our simple tag open values
//
var b_open = 0; // [bold]
var i_open = 0; // [italic]
var u_open = 0; // [underlined]
var p_open = 0; // [paragraph]
var l_open = 0; // [left]
var r_open = 0; // [right]
var c_open = 0; // [center]

var bbtags = new Array();
var theSelection = false;

//
// Determine browser type and stuff
//
var myAgent   = navigator.userAgent.toLowerCase();
var myVersion = parseInt(navigator.appVersion);

var is_ie   = ((myAgent.indexOf("msie") != -1)  && (myAgent.indexOf("opera") == -1));
var is_nav  = ((myAgent.indexOf('mozilla')!=-1) && (myAgent.indexOf('spoofer')==-1)
                && (myAgent.indexOf('compatible') == -1) && (myAgent.indexOf('opera')==-1)
                && (myAgent.indexOf('webtv') ==-1)       && (myAgent.indexOf('hotjava')==-1));

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

//
// Current textarea, where alll bbtags will be put
//
var curFocTxtArea = null;


//
// Sets current textarea
//
function SetFocusTextArea(what)
{
  curFocTxtArea = what;
}


//
// Get stack size
//
function stacksize(thearray)
{
  if ( (thearray == "") || (thearray == null) || (thearray == 'undefined') ) return 0;

	for (var i = 0 ; i < thearray.length; i++ ) {
		if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') )
    {
			return i;
		}
	}
	
	return thearray.length;
}


//
// Push stack
//
function pushstack(thearray, newval)
{
	var arraysize = stacksize(thearray);
	
	thearray[arraysize] = newval;
}


//
// Pop stack
//
function popstack(thearray)
{
	var arraysize = stacksize(thearray);
	var theval = thearray[arraysize - 1];
	delete thearray[arraysize - 1];
	return theval;
}


//
// Close all tags
//
function closeall()
{
	if (bbtags[0]) {
		while (bbtags[0]) {
			tagRemove = popstack(bbtags)
			//document.post.message
      curFocTxtArea.value += "[/" + tagRemove + "]";
		}
	}

	// Ensure we got them all
	bbtags = new Array();
	//document.post.message
  curFocTxtArea.focus();
}


//
// SIMPLE TAGS (such as B, I U, etc)
//
function simpletag(thetag)
{
  if (curFocTxtArea == null) return;
  
	var tagOpen = eval(thetag + "_open");

	if (tagOpen == 0)
	{
		if(doInsert("[" + thetag + "]", "[/" + thetag + "]", true))
		{
			eval(thetag + "_open = 1");
			pushstack(bbtags, thetag);
		}
	}
	else
  {
		// Find the last occurance of the opened tag
		var lastindex = 0;

		for (var 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])
		{
			var tagRemove = popstack(bbtags);
			doInsert("[/" + tagRemove + "]", "", false)
		}
		
		eval(thetag + "_open = 0");
	}
	
	//document.post.message
  curFocTxtArea.focus();
}

function bbcolor(whatColor)
{
  if (curFocTxtArea == null) return;
  
	var txtarea = curFocTxtArea; // document.post.message;
	var bbopen = "[color=" + whatColor + "]";
	var bbclose = "[/color]";

	if ((myVersion >= 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);
}

// 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();
}

function tag_url()
{
  var enterURL   = prompt("Въведете адрес на сайта:", "http://");
  var enterTITLE = prompt("Въведете име на сайта:", "My Webpage");

  if (!enterTITLE || !enterURL) return;

  doInsert("[url="+enterURL+"]"+enterTITLE+"[/url]", "", 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 = curFocTxtArea; //document.post.message;

	if ( (myVersion >= 4) && is_ie && is_win) // Ensure it works for IE4up / Win only
	{
		if(obj_ta.isTextEdit){ // this doesn't work for NS, but it works for IE 4+ and compatible browsers
			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;
		}
	}
	else if (document.getSelection) {  
		var text = obj_ta.value;
		var selTxt = text.substring(obj_ta.selectionStart, obj_ta.selectionEnd);
		var cursorPos = obj_ta.selectionStart;
		
		if(ibClsTag != "" && selTxt.length > 0)
			ibTag += selTxt + ibClsTag;
		else if(isSingle)
			isClose = true;
 		cursorPos += ibTag.length;
      	
		replaceSelection(obj_ta, ibTag);  
		obj_ta.focus();
		obj_ta.selectionStart = cursorPos;
		obj_ta.selectionEnd = cursorPos;      
	} 
	else
	{
		if(isSingle)
			isClose = true;

		obj_ta.value += ibTag;
	}

	obj_ta.focus();

	return isClose;
}	


// Replaces the current selection in the TextArea o with the string s
function replaceSelection(o, s)
{
   var s2 = o.value;
   o.value = s2.substring(0, o.selectionStart) + s + s2.substr(o.selectionEnd);
}
