// http://parentnode.org/javascript/working-with-the-cursor-position/
// http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/
function addSmileAtCursor(nBox, val){

  var cursorPos = 0;
  if (nBox.selectionStart == undefined)
  //if (document.selection)
  {
    nBox.focus();
        var range = document.selection.createRange();
        // We'll use this as a 'dummy'
        var stored_range = range.duplicate();
          // Select all text
          stored_range.moveToElementText( nBox );
          // Now move 'dummy' end point to end point of original range
          stored_range.setEndPoint( 'EndToEnd', range );
          // Now we can calculate start and end points
          nBox.selectionStartPos = stored_range.text.length - range.text.length;
          nBox.selectionEnd = nBox.selectionStartPos + range.text.length;
    var cursorPos = nBox.selectionStartPos;
    
  }
  else {
        if (nBox.selectionStart || nBox.selectionStart == '0') {
           cursorPos = nBox.selectionStart;
               var scrollTop = nBox.scrollTop; // fix scrolling issue with Firefox
      }
  }


  nBox.value = nBox.value.substring(0, cursorPos) + val + nBox.value.substring(cursorPos, nBox.value.length);

  if(nBox.createTextRange) {
      var range = nBox.createTextRange();
      range.move("character", cursorPos + val.length);
      range.select();
  } else if (nBox.selectionStart || nBox.selectionStart == '0') {
      nBox.focus();
      nBox.setSelectionRange(cursorPos + val.length, cursorPos + val.length);
      nBox.scrollTop = scrollTop;
  }
   return cursorPos;
}
