function bbcode(tag) {
   if(tag == "bold") {
      insert("[b]","[/b]");
   }
   if(tag == "italic") {
      insert("[i]","[/i]");
   }
   if(tag == "underline") {
      insert("[u]","[/u]");
   }
   if(tag == "center") {
      insert("[center]","[/center]");
   }
   if(tag == "url") {
      insert("[url]","[/url]");
   }
   if(tag == "mail") {
      insert("[mail]","[/mail]");
   }
   if(tag == "image") {
      insert("[img]","[/img]");
   }
   if(tag == "quote") {
      insert("[quote]","[/quote]");
   }
   if(tag == "php") {
      insert("[php]","[/php]");
   }
}

function changecolor() {
   color_select = document.getElementById("color");
   color = color_select.options[color_select.selectedIndex].value;
   insert("[color="+color+"]","[/color]");
   color_select.selectedIndex = 0;
}

function changesize() {
   size_select = document.getElementById("size");
   size = size_select.options[size_select.selectedIndex].value;
   insert("[size="+size+"]","[/size]");
   size_select.selectedIndex = 0;
}

function smilie(smilie) {
   insert(" "+smilie+" ","");
}

/* Quelle: http://aktuell.de.selfhtml.org/tippstricks/javascript/bbcode/ */
function insert(aTag, eTag) {
  var input = document.getElementById('bbcode');
  input.focus();
  /* für Internet Explorer */
  if(typeof document.selection != 'undefined') {
    /* Einfügen des Formatierungscodes */
    var range = document.selection.createRange();
    var insText = range.text;
    range.text = aTag + insText + eTag;
    /* Anpassen der Cursorposition */
    range = document.selection.createRange();
    if (insText.length == 0) {
      range.move('character', -eTag.length);
    } else {
      range.moveStart('character', aTag.length + insText.length + eTag.length);      
    }
    range.select();
  }
  /* für neuere auf Gecko basierende Browser */
  else if(typeof input.selectionStart != 'undefined')
  {
    /* Einfügen des Formatierungscodes */
    var start = input.selectionStart;
    var end = input.selectionEnd;
    var insText = input.value.substring(start, end);
    input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    /* Anpassen der Cursorposition */
    var pos;
    if (insText.length == 0) {
      pos = start + aTag.length;
    } else {
      pos = start + aTag.length + insText.length + eTag.length;
    }
    input.selectionStart = pos;
    input.selectionEnd = pos;
  }
  /* für die übrigen Browser */
  else
  {
    /* Abfrage der Einfügeposition */
    var pos;
    var re = new RegExp('^[0-9]{0,3}$');
    while(!re.test(pos)) {
      pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
    }
    if(pos > input.value.length) {
      pos = input.value.length;
    }
    /* Einfügen des Formatierungscodes */
    var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  }
}
