

var tt_target = 'text';

function tt_getSelection() {
	var txt = document.getElementById(tt_target);
	if(txt.createTextRange) txt.caretPos = document.selection.createRange().duplicate();
	if(txt.selectionEnd && (txt.selectionEnd - txt.selectionStart > 0)) {
		// Mozilla
		return (txt.value).substring(txt.selectionStart, txt.selectionEnd);
	} else if(txt.createTextRange && txt.caretPos && txt.caretPos.text != '') {
		// IE
		return txt.caretPos.text;
	} else return '';
}

function tt_insertText(new_text) {
	var txt = document.getElementById(tt_target);
	if(txt.createTextRange) txt.caretPos = document.selection.createRange().duplicate();
	if(txt.selectionEnd && (txt.selectionEnd - txt.selectionStart > 0)) {
		// Mozilla
		var start = (txt.value).substring(0, txt.selectionStart);
		var middle = (txt.value).substring(txt.selectionStart, txt.selectionEnd);
		var end = (txt.value).substring(txt.selectionEnd, txt.textLength);
		txt.value = start + new_text + end;
	} else if(txt.createTextRange && txt.caretPos && txt.caretPos.text != '') {
		// IE
		txt.caretPos.text = new_text;
	} else {
		txt.value += new_text;
	}
	txt.focus();
}



function tt_insert_tag(start_tag,end_tag) {
	var selText = tt_getSelection();
	if(selText.substring(selText.length-1,selText.length) == ' ') {
		tt_insertText(start_tag + selText.substring(0,selText.length-1) + end_tag + ' ');
	} else tt_insertText(start_tag + selText + end_tag);
}


function tt_insert_link() {
	var selText = tt_getSelection();
	var l_title = selText;
	var space = (selText.substring(selText.length-1,selText.length) == ' ') ? ' ' : '';
	if(space) l_title = selText.substring(0,selText.length-1);
	l_title = prompt('Linktitel (optional)',l_title);
	var l_link = prompt('Link URL','http://');
	if(l_link == 'http://' || l_link == '' || l_link == null) l_link = '';
	if(l_title && l_link) tt_insertText('[url=' + l_link + ']' + l_title + '[/url]' + space);
	else if(l_link != '') tt_insertText('[url]' + l_link + '[/url]' + space);
}

function tt_insert_email() {
	var selText = tt_getSelection();
	var l_title = selText;
	var space = (selText.substring(selText.length-1,selText.length) == ' ') ? ' ' : '';
	if(space) l_title = selText.substring(0,selText.length-1);
	l_title = prompt('Linktitel (optional)',l_title);
	var l_link = prompt('E-Mail Adresse','');
	if(l_link == '' || l_link == null) l_link = '';
	if(l_title && l_link) tt_insertText('[url=mailto:' + l_link + ']' + l_title + '[/url]' + space);
	else if(l_link != '') tt_insertText('[url=mailto:' + l_link + ']' + l_link + '[/url]' + space);
}