function count(element, open, closed)
{
	var opening = document.getElementById(element).value.split(open);
	var closing = document.getElementById(element).value.split(closed);
	return opening.length + closing.length - 2;
}

function addtag(element, tag1, tag2, twince)
{
	var textbox = document.getElementById(element);
	
	if (document.selection) {
		var string = document.selection.createRange().text;
		textbox.focus();
		var selection = document.selection.createRange();
		if (tag2 != "") {
			if (string == "") { // Une chaine n'est pas selectionnée
				if (twince == 0) {
					var instances = count(element, tag1, tag2);
					if (instances % 2 != 0) selection.text = selection.text + tag2;
					else selection.text = selection.text + tag1;
				} else {
					selection.text = selection.text + tag1 + tag2;
				}
			} else selection.text = tag1 + selection.text + tag2;
		} else selection.text = selection.text + tag1;
	} else if (textbox.selectionStart || textbox.selectionStart == 0) {
		if (textbox.selectionEnd > textbox.value.length) textbox.selectionEnd = textbox.value.length;
		var firstPos = textbox.selectionStart;
		var secondPos = textbox.selectionEnd + tag1.length;
		var contenuScrollTop = textbox.scrollTop;
		
		textbox.value = textbox.value.slice(0, firstPos) + tag1 + textbox.value.slice(firstPos);
		textbox.value = textbox.value.slice(0, secondPos) + tag2 + textbox.value.slice(secondPos);
		
		textbox.selectionStart = firstPos + tag1.length;
		textbox.selectionEnd = secondPos;
		textbox.focus();
		textbox.scrollTop = contenuScrollTop;
	} else { // Opera
		var selection = document.getElementById(element);
		var instances = count(element, tag1, tag2);
		if (instances % 2 != 0 && tag2 != "") selection.value = selection.value + tag2;
		else selection.value = selection.value + tag1;
	}
}
