var formattedStr = "";
startPosition = 0;
var endPosition = 0;
function insertBoldTags(myField){
findPositions(myField);
var text = myField.value;
if (startPosition!=endPosition) {
var sbStr = text.substring(startPosition,endPosition);
sbStr = '<b>'+ sbStr + '</b>';
fillsFormattedString(text,sbStr,myField);
}
}
function insertItalicTags(myField){
findPositions(myField);
var text = myField.value;
if (startPosition!=endPosition) {
var sbStr = text.substring(startPosition,endPosition);
sbStr = '<i>'+ sbStr + '</i>';
fillsFormattedString(text,sbStr,myField);
}
}
function insertLinkTags(myField){
findPositions(myField);
var text = myField.value;
if (startPosition!=endPosition) {
var sbStr = text.substring(startPosition,endPosition);
sbStr = '<a target="_blank" href="http://' + sbStr + '">'+ sbStr + '</a>';
fillsFormattedString(text,sbStr,myField);
}
}
function findPositions(myField){
var text = myField.value;
if (document.selection) {
// Internet Explorer
var range = document.selection.createRange();
var dpl = range.duplicate();
if (range.text.length > 0) {
dpl.moveToElementText(myField);
dpl.setEndPoint("EndToEnd", range);
startPosition = dpl.text.length-range.text.length;
endPosition = startPosition + range.text.length;
}
}
else {
// Mozilla Firefox
startPosition = myField.selectionStart;
endPosition = myField.selectionEnd;
}
}
function fillsFormattedString(text, selectedText, myField){
// split textarea value into three pieces: before startPosition,
// startPosition until endPosition, and after endPosition
var str1 = text.substring(0,startPosition);
var str2 = text.substring(startPosition,endPosition);
var str3 = text.substring(endPosition,text.length);
// replace str2 with formatted substring (selectedText)
str2 = selectedText;
// form the new string
formattedStrWithBrackets = str1 + '[' + str2 + ']' + str3;
formattedStrNoBrackets = str1 + str2 + str3;
myField.value = formattedStrWithBrackets;
}