var bold = false;
var italic = false;
var underline = false;
var quote = false;

function storeCaret(textEl) {
	if (textEl.createTextRange)
		textEl.caretPos = document.selection.createRange().duplicate();
}
function insertAtCaret(textEl, text) {
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
	}
	else
		textEl.value  = textEl.value + text;
	textEl.focus();
}
function insertStyle(textEl, style, state) {
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		if (caretPos.text && caretPos.text != "") {
			caretPos.text = "[" + style + "]" + caretPos.text + "[/" + style + "]";
			state = false;
		}
		else {
			if (!state)
				caretPos.text  = "[" + style + "]";
			else
				caretPos.text  = "[/" + style + "]";
			state = !state;
		}
	}
	else {
		if (!state)
			textEl.value  = textEl.value + "[" + style + "]";
		else
			textEl.value  = textEl.value + "[/" + style + "]";
		state = !state;
	}
	textEl.focus();
	return state;
}
function insertBold(textEl) {
	bold = insertStyle(textEl, "b", bold);
}
function insertItalic(textEl) {
	italic = insertStyle(textEl, "i", italic);
}
function insertUnderline(textEl) {
	underline = insertStyle(textEl, "u", underline);
}
function insertQuote(textEl) {
	if (document.getSelection) 
		txt = document.getSelection();
	else if (document.selection) 
		txt = document.selection.createRange().text;
		
	if (txt == null || txt == "") {
		quote = insertStyle(textEl, "quote", quote);
		return;
	}

	//document.forms[0].selectedtext.value = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
	if (textEl.createTextRange && textEl.caretPos) {
		var caretPos = textEl.caretPos;
		caretPos.text = "[quote]" + txt + "[/quote]";
	}
	else
		textEl.value  = textEl.value + "[quote]" + txt + "[/quote]";
	textEl.focus();
}
