var bbcode_images = [
 "bbcode_b.gif", "bbcode_b-over.gif",
 "bbcode_i.gif", "bbcode_i-over.gif",
 "bbcode_u.gif", "bbcode_u-over.gif",
 "bbcode_url.gif", "bbcode_url-over.gif",
 "bbcode_img.gif", "bbcode_img-over.gif"
];

function preloadImages(dir, imgArr) {
 var imgs = new Array();
 for (i=0; i<imgArr.length; i++) {
  imgs[i] = new Image();
  imgs[i].src = dir + imgArr[i];
 }
}

function bbcode(txtA, txtB, mid) {
 if (!txtB) txtB = txtA;
 d = document.postmsg.post;
 d.focus();
 if (document.selection) {
  sel = document.selection.createRange();
  old = sel.text;
  if (mid) old = mid;
  sel.text = "[" + txtA + "]" + old + "[/" + txtB + "]";
 }
 else if (d.selectionStart && d.selectionEnd) {
  sPos = d.value.substring(0, d.selectionStart);
  ePos = d.value.substring(d.selectionEnd, d.value.length);
  val = d.value.substring(d.selectionStart, d.selectionEnd);
  if (mid) val = mid;
  newValue = "[" + txtA + "]" + val + "[/" + txtB + "]";
  d.value = sPos + newValue + ePos;
 }
 d.focus();
}

function insertLink() {
 d = document.postmsg.post;
 d.focus();
 if (document.selection) {
  sel = document.selection.createRange();
  len = sel.text.length;
 }
 else if (d.selectionStart && d.selectionEnd) {
  sPos = d.selectionStart;
  ePos = d.selectionEnd;
  len = d.value.substring(sPos, ePos).length;
 }
 if (len > 0) {
  var url = prompt("Enter the URL (press cancel to use the\ncurrently selected text as the title and URL):", "http://");
  if (!url) bbcode("url");
  else {
   bbcode("url=" + url, "url");
  }
 }
 else {
  var title = prompt("Enter the title:", "");
  if (title) {
   var url = prompt("Enter the URL:", "http://");
   if (url) {
    bbcode("url=" + url, "url", title);
   }
  }
 }
}

function linkImage(id,src) {
 var img = id.getElementsByTagName("img")[0];
 img.src = templateDir + "/images/" + src;
}

function dropSmileys(id) {
 var smMenu = document.getElementById("smileysMenu");
 if (smMenu.style.visibility == "visible") {
  smMenu.style.visibility = "hidden";
  linkImage(id, "smileys.gif");
 }
 else {
  smMenu.style.visibility = "visible";
  linkImage(id, "smileys-over.gif");
 }
}

function insertSmiley(keyVal) {
 d = document.postmsg.post;
 d.focus();
 if (document.selection) {
  sel = document.selection.createRange();
  sel.text = keyVal;
 }
 else if (d.selectionStart && d.selectionEnd) {
  sPos = d.value.substring(0, d.selectionStart);
  ePos = d.value.substring(d.selectionEnd, d.value.length);
  d.value = sPos + keyVal + ePos;
 }
 d.focus();
}

preloadImages(templateDir + "/images/", bbcode_images);