
function ltrim(s) {
	return s.replace( /^\s*/, "" );
}
function rtrim(s) {
	return s.replace( /\s*$/, "" );
}
function trim ( s ) {
	return rtrim(ltrim(s));
}

function AddText(text,Id) 
{
    console.log('add text');
    var tarea = Id;
	if(typeof Id == 'string')
	    tarea = document.getElementById(Id);

	if (typeof tarea.selectionStart)
	{ 
	    // if it supports DOM2
		start = tarea.selectionStart;
		end = tarea.selectionEnd;
		tarea.value = tarea.value.substr(0,tarea.selectionStart) + text + tarea.value.substr(tarea.selectionEnd);
		tarea.focus();
		tarea.selectionStart = ((start - end) == 0) ? start + text.length : start;
		tarea.selectionEnd = start + text.length;
	} 
	else 
	{
		if (tarea.createTextRange && tarea.caretPos) 
		{
			var caretPos = tarea.caretPos;
			caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?   text + ' ' : text;
		}
		else 
		{
			tarea.value += text;
		}
		tarea.focus(caretPos);
	}
}

function InsertVariable(variable,Id) 
{
    console.log('insert variable');
	var text = getText(Id);
	if (variable) 
	{
	    console.log('asdf:');
		AddTxt="["+variable+"]" + text + "[/"+variable+"]";
		AddText(AddTxt,Id);
	}					
}

//function storeCaret(ftext) 
//{
//	if (ftext.createTextRange) 
//		ftext.caretPos = document.selection.createRange().duplicate();
//}

function getText(Id) 
{
    console.log('get text');
    var tarea = Id;
	if(typeof Id == 'string')
		tarea = document.getElementById(Id);
	 
	if (tarea.createTextRange && tarea.caretPos) 
	{
	    return tarea.caretPos.text;
	} 
	else if (typeof tarea.selectionStart)
	{
	    return tarea.value.substr(tarea.selectionStart,tarea.selectionEnd-tarea.selectionStart)
	}
	else
	    return '';
}
