var regexp = new RegExp("[\r]","gi");
var isMozilla = (navigator.userAgent.toLowerCase().indexOf('gecko')!=-1) ? true : false;

function etiqueta_bbcode(formulario,campotexto,nombreEtiqueta)
{
	if (isMozilla) 
	{	//si es un navegador Mozilla

		campoTexto = document.forms[formulario].elements[campotexto];

		objectValue = campoTexto.value;

		deb = campoTexto.selectionStart;
		fin = campoTexto.selectionEnd;

		objectValueDeb = objectValue.substring( 0 , campoTexto.selectionStart );
		objectValueFin = objectValue.substring( campoTexto.selectionEnd , campoTexto.textLength );
		objectSelected = objectValue.substring( campoTexto.selectionStart ,campoTexto.selectionEnd );

			
		campoTexto.value = objectValueDeb + "[" + nombreEtiqueta + "]" + objectSelected + "[/" + nombreEtiqueta + "]" + objectValueFin;
		campoTexto.selectionStart = strlen(objectValueDeb);
		campoTexto.selectionEnd = strlen(objectValueDeb + "[" + nombreEtiqueta + "]" + objectSelected + "[/" + nombreEtiqueta + "]");
		campoTexto.focus();
		campoTexto.setSelectionRange(
			objectValueDeb.length + nombreEtiqueta.length + 2,
			objectValueDeb.length + nombreEtiqueta.length + 2);
	}
	else
	{	// si es el Internet Explorer
		
		campoTexto = document.forms[formulario].elements[campotexto];
		var str = document.selection.createRange().text;

		if (str.length>0) //si hay texto seleccionado
		{
			var sel = document.selection.createRange();
			sel.text = "[" + nombreEtiqueta + "]" + str + "[/" + nombreEtiqueta + "]";
			sel.collapse();
			sel.select();
		}
		else
		{
			campoTexto.focus(campoTexto.caretPos);
			campoTexto.focus(campoTexto.value.length);
			campoTexto.caretPos = document.selection.createRange().duplicate();
			
			var bidon = "%~%";
			var orig = campoTexto.value;
			campoTexto.caretPos.text = bidon;
			var i = campoTexto.value.search(bidon);
			campoTexto.value = orig.substr(0,i) + "[" + nombreEtiqueta + "][/" + nombreEtiqueta + "]" + orig.substr(i, campoTexto.value.length);
			var r = 0;
			for(n = 0; n < i; n++)
			{if(regexp.test(campoTexto.value.substr(n,2)) == true){r++;}};
			pos = i + 2 + nombreEtiqueta.length - r;
			var r = campoTexto.createTextRange();
			r.moveStart('character', pos);
			r.collapse();
			r.select();
		}
	}
}
