$(document).ready(function () {
	$('.smiley a').click(insert_emoticon);

	// Open all external links in a new window.
	$('.message_text a').each(function () {
		if (this.href.match(/^http:/) && !this.href.match(/jumborewards\./)) {
			$(this).attr('target', '_blank');
		}
	});
});

function insert_emoticon () {
	var img = $(this).find('img');
	// Parse the tag name from the image filename.
	var src = $(img).attr('src');
	var tag = ':' + src.match(/([^\/]+)\.\w{3}$/)[1] + ':';

	// Insert the tag into the textarea.
	$('.category_postform textarea').each(function () {insertAtCursor(this, tag);});

	return false;
}

function insertAtCursor(obj, text) {
	if($.browser.msie) {
		// IE-specific handling.
		if (!obj.focus()) {
			obj.focus();
		}
		document.selection.createRange().text=text;
	}
	else {
		// Non-IE handling.
		var pos          = obj.selectionStart;
		var scrollPos    = obj.scrollTop
		var current_text = $(obj).val();
	
		$(obj).val(current_text.substr(0, pos) + text + current_text.substr(pos));
		obj.selectionStart = pos + text.length;
		obj.selectionEnd   = pos + text.length;
	
		obj.scrollTop = scrollPos;
	}
}
