// IE only - wraps selected text with lft and rgt
  function WrapIE(lft, rgt) {
    strSelection = document.selection.createRange().text;
    if (strSelection!="") {
      document.selection.createRange().text = lft + strSelection + rgt;
    }
  }

// Moz only - wraps selected text with lft and rgt
  function wrapMoz(txtarea, lft, rgt) {
    var selLength = txtarea.textLength;
    var selStart = txtarea.selectionStart;
    var selEnd = txtarea.selectionEnd;
    if (selEnd==1 || selEnd==2) selEnd=selLength;
    var s1 = (txtarea.value).substring(0,selStart);
    var s2 = (txtarea.value).substring(selStart, selEnd)
    var s3 = (txtarea.value).substring(selEnd, selLength);
    txtarea.value = s1 + lft + s2 + rgt + s3;
  }
  
// Chooses technique based on browser
  function wrapTag(txtarea, lft, rgt) {
    lft = unescape(lft);
    rgt = unescape(rgt);
    if (document.all) {
      WrapIE(lft, rgt);
    }
    else if (document.getElementById) {
      wrapMoz(txtarea, lft, rgt);
    }
  }  
  
// IE only - Insert text at caret position or at start of selected text
  function insertIE (txtarea, text) {
    if (txtarea.createTextRange && txtarea.caretPos) { 
      var caretPos = txtarea.caretPos; 
      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text+caretPos.text + ' ' : text+caretPos.text;
    } else {
      txtarea.value = txtarea.value + text; 
    }
    return;
  } 

// Moz only - Insert text at caret position or at start of selected text
  function insertMoz(txtarea , lft) {
    var rgt="";
    wrapTag(txtarea, lft, rgt);
    return;
  }

// Switch function based on browser - Insert text at caret position or at start of selected text
  function insertTag(txtarea , lft) {
    if (document.all) {
      insertIE(txtarea, lft);
    }
    else if (document.getElementById) {
      insertMoz(txtarea, lft);
    }
  }

// IE only - stores the current cursor position on any textarea activity
  function storeCaret (txtarea) { 
    if (txtarea.createTextRange) { 
      txtarea.caretPos = document.selection.createRange().duplicate();
    } 
  }