function codeSimple (txtId, code, defText) {
  codeInsert (txtId, "<" + code + ">", "</" + code + ">", defText);
}

function codeParam (txtId, code, param, defText) {
  codeInsert (txtId, "<" + (code == 'a' ? 'a href' : 'img src') + "=\"" + param + "\"" + (code == 'a' ? ' target="_blank"' : ' /') + ">", (code == 'a' ? '</a>' : null), defText);
}

function codeGetURL (txtId, code, msg) {
  var url = prompt (msg, "http://");
  if (!url) {
    document.getElementById(txtId).focus();
    return;
  }
  url = encodeURI(url).replace(/%25[0-9A-F][0-9A-F]/gi, decodeURIComponent);
  codeParam (txtId, code, url, (code == 'a' ? '[link]' : null));
}

function codeSmiley (txtId, code) {
  codeInsert (txtId, " " + code + " ", null, null);
}

function codeInsert (txtId, oTag, cTag, defText) {
  var txt = document.getElementById(txtId);
  txt.focus();
  if (txt.selectionStart != undefined) {
    // -- Firefox, Opera, Safari
    var sel_start = txt.selectionStart;
    var sel_end   = txt.selectionEnd;
    if (!cTag) {
      txt.value = txt.value.substr(0, sel_start) + oTag + txt.value.substr(sel_end);
      txt.selectionStart = sel_start + oTag.length;
      txt.selectionEnd   = sel_start + oTag.length;
    }
    else {
      var selText = txt.value.substr(sel_start, sel_end - sel_start);
      if (!selText && defText) selText = defText;

      txt.value = txt.value.substr(0, sel_start) + oTag + selText + cTag + txt.value.substr(sel_end);
      txt.selectionStart = sel_start + oTag.length;
      txt.selectionEnd   = sel_start + oTag.length + selText.length;
    }
  }
  else if (document.selection) {
    // -- IE
    var sel = document.selection.createRange();
    if (sel) {
      if (!cTag) sel.text = oTag;
      else {
        var selText = sel.text;
        if (!selText && defText) selText = defText;
        var selLength = selText.replace(/\r\n/g, "\n").length;

        sel.text = oTag + selText + cTag;
        sel.moveStart ("character", -cTag.length - selLength);
        sel.moveEnd   ("character", -cTag.length);
      }
      sel.select();
    }
  }
}