var selection = false; // Selection data
/**
* From http://www.massless.org/mozedit/
*/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	var scrollTop = txtarea.scrollTop;

	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;
	txtarea.selectionStart = selEnd + open.length + close.length;
	txtarea.selectionEnd = txtarea.selectionStart;
	txtarea.focus();
	txtarea.scrollTop = scrollTop;

	return;
}

// Catching selection
function catchSelection()
{
	if (window.getSelection)
	{
		selection = window.getSelection().toString();
	}
	else if (document.getSelection)
	{
		selection = document.getSelection();
	}
	else if (document.selection)
	{
		selection = document.selection.createRange().text;
	}
}

// Putting username to the post box
function putName(name)
{
	emoticon_wospaces('[b] to '+name+'[/b], ');
	//document.postform.message.focus();
	return;
}

// Putting selection to the post box
function quoteSelection(name)
{        var l_no_text_selected="Ничего не выделено";
	if (selection)
	{
		emoticon_wospaces('[quote="'+name+'"]' + selection + '[/quote]\n');
		selection = '';
		//document.postform.message.focus();
		return;
	}
	else
	{
		alert(l_no_text_selected);
		return;
	}
}

function emoticon(text) {
	var txtarea = document.getElementById('message');
	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 emoticon_wospaces(text) {
	if(document.getElementById('message')){
	var txtarea = document.getElementById('message');
	txtarea.focus();}
	else { return 0; }


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

