function InsertSmiley(dObject) 
{
	var dElement = GetElement(dObject);
	if( ! dElement || ! document.getElementById('mess'))
		return;
	
	var txtBox = document.getElementById('mess');
	var smiley = dElement.title;
		
	if (document.selection) 
	{
		txtBox.focus();
		sel      = document.selection.createRange();
		sel.text = smiley;
	}
	else if (txtBox.selectionStart || txtBox.selectionStart == '0') 
	{
		var startPos = txtBox.selectionStart;
		var endPos   = txtBox.selectionEnd;
		txtBox.value = txtBox.value.substring(0, startPos)
		             + smiley
		             + txtBox.value.substring(endPos, txtBox.value.length);
	}
	else 
	{
		txtBox.value += smiley;
	}
}

function InsertTags(dObject)
{
	var dElement = GetElement(dObject);
	if( ! dElement || ! document.getElementById('mess'))
		return;
	
	var txtBox = document.getElementById('mess');
	
	var begTag = null;
	var endTag = null;
	switch(dElement.id)
	{
		case 'boldControl':
			begTag = '[b]';
			endTag = '[/b]';
			break;
		case 'italicControl':
			begTag = '[i]';
			endTag = '[/i]';
			break;
		default:
			return;
	}

	if (document.selection)
	{
		txtBox.focus();
		sel      = document.selection.createRange();
		sel.text = begTag + sel.text + endTag;
		txtBox.focus();
	}
	else if (txtBox.selectionStart || txtBox.selectionStart == '0')
	{
		var startPos = txtBox.selectionStart;
		var endPos   = txtBox.selectionEnd;
		txtBox.value = txtBox.value.substring(0, startPos)
		+ begTag + txtBox.value.substring(txtBox.selectionStart, txtBox.selectionEnd)
		+ endTag + txtBox.value.substring(endPos, txtBox.value.length);
		txtBox.selectionStart = startPos;
		txtBox.selectionEnd   = endPos + endTag.length + begTag.length;
		txtBox.focus();
	}
	else
	{
		txtBox.value += begTag + endTag;
	}
}

function getPattern(dClass)
{
	return new RegExp('(^| )' + dClass + '( |$)');
}

function Init()
{
	var arr = document.getElementsByTagName('img');
	var pattern = getPattern('smileyControl');

	for(var i = 0; i < arr.length; i++)
	{
		if(arr[i].className && pattern.test(arr[i].className))
		{
			SetListener(arr[i], 'click', InsertSmiley);
		}
	}
	
	if(document.getElementById('boldControl'))
		SetListener(document.getElementById('boldControl'), 'click', InsertTags);
		
	if(document.getElementById('italicControl'))
		SetListener(document.getElementById('italicControl'), 'click', InsertTags);
}
SetListener(window, 'load', Init);