/**
 * all these functions might depend on some global vars with content generated by php!
 *
 * they are in this external file to enable js caching by browsers and reduce code duplication
 */

/**
 * simple yet effective - replaces all keys of vars inside template with their value
 *
 * the keys have to be enclosed with {%...%} in template
 *
 * @example: var = {foo: "bar"}, template = "{%foo%}" => returns "bar"
 */
function prepare_template(vars, template) {
  for (var key in vars) {
    template = template.replace(new RegExp("\{%" + key + "%\}", "g"), vars[key]);
  }
  return template;
}

/** from post.inc.php **/

// If this is a poll - use some javascript to ensure the user doesn't create a poll with illegal option combinations.
function pollOptions() {
  var expireTime = document.getElementById("poll_expire");

  if (isEmptyText(expireTime) || expireTime.value == 0) {
    document.forms.postmodify.poll_hide[2].disabled = true;
    if (document.forms.postmodify.poll_hide[2].checked) {
      document.forms.postmodify.poll_hide[1].checked = true;
    }
  } else {
    document.forms.postmodify.poll_hide[2].disabled = false;
  }
}
function addPollOption(id) {
  // get current pollOptionNum
  if (pollOptionNum == 0) {
    for (var i = 0; i < document.forms.postmodify.elements.length; i++) {
      if (document.forms.postmodify.elements[i].id.substr(0, 8) == "options-") {
        pollOptionNum++;
        pollTabIndex = document.forms.postmodify.elements[i].tabIndex;
      }
    }
    pollTemplate = prepare_template({pollTabIndex: pollTabIndex}, pollTemplate);
  }
  pollOptionNum++

  document.getElementById(id).innerHTML += prepare_template({pollOptionNum: pollOptionNum}, pollTemplate);
}

// Code for showing and hiding additional options.
function swapOptions() {
  document.getElementById("postMoreExpand").src = smf_images_url + "/" + (currentSwap ? "collapse.png" : "expand.png");
  document.getElementById("postMoreExpand").alt = currentSwap ? "-" : "+";

  document.getElementById("postMoreOptions").style.display = currentSwap ? "" : "none";

  if (document.getElementById("postAttachment")) {
    document.getElementById("postAttachment").style.display = currentSwap ? "" : "none";
  }
  if (document.getElementById("postAttachment2")) {
    document.getElementById("postAttachment2").style.display = currentSwap ? "" : "none";
  }

  if (typeof(document.forms.postmodify) != "undefined") {
    document.forms.postmodify.additional_options.value = currentSwap ? "1" : "0";
  }

  currentSwap = !currentSwap;
}
// The actual message icon selector.
function showimage() {
  document.getElementById("message_icon").src = icon_urls[document.forms.postmodify.icon.options[document.forms.postmodify.icon.selectedIndex].value];
}
// A function needed to discern HTML entities from non-western characters.
function saveEntities() {
  var textFields = ["subject", "message", "guestname", "evtitle", "question"];
  for (i in textFields) {
    if (document.forms.postmodify.elements[textFields[i]]) {
      document.forms.postmodify[textFields[i]].value = document.forms.postmodify[textFields[i]].value.replace(/&#/g, "&#38;#");
    }
  }
  for (var i = document.forms.postmodify.elements.length - 1; i >= 0; i--) {
    if (document.forms.postmodify.elements[i].name && document.forms.postmodify.elements[i].name.indexOf("options") == 0) {
      document.forms.postmodify.elements[i].value = document.forms.postmodify.elements[i].value.replace(/&#/g, "&#38;#");
    }
  }
}

function previewPost() {
  if (window.XMLHttpRequest) {
    if (browser_is_firefox) {
      // Firefox doesn't render <marquee> that have been put in using javascript
      if (document.forms.postmodify.elements["message"].value.indexOf("[move]") != -1) {
        return submitThisOnce(document.forms.postmodify);
      }
    }
    // Opera didn't support setRequestHeader() before 8.01.
    if (typeof(window.opera) != "undefined") {
      var test = new XMLHttpRequest();
      if (typeof(test.setRequestHeader) != "function") {
        return submitThisOnce(document.forms.postmodify);
      }
    }
    // !!! Currently not sending poll options and option checkboxes.
    var i, x = new Array();
    var textFields = ["subject", "message", "icon", "guestname", "email", "evtitle", "question", "topic"];
    var numericFields = [
        "board", "topic", "num_replies",
        "eventid", "calendar", "year", "month", "day",
        "poll_max_votes", "poll_expire", "poll_change_vote", "poll_hide"
    ];
    var checkboxFields = [
        "ns",
    ];

    for (i in textFields) {
      if (document.forms.postmodify.elements[textFields[i]]) {
        x[x.length] = textFields[i] + "=" + escape(textToEntities(document.forms.postmodify[textFields[i]].value.replace(/&#/g, "&#38;#"))).replace(/\+/g, "%2B");
      }
    }
    for (i in numericFields) {
      if (document.forms.postmodify.elements[numericFields[i]]
          && typeof(document.forms.postmodify[numericFields[i]].value) != "undefined") {
        x[x.length] = numericFields[i] + "=" + parseInt(document.forms.postmodify.elements[numericFields[i]].value);
      }
    }
    for (i in checkboxFields) {
      if (document.forms.postmodify.elements[checkboxFields[i]]
          && document.forms.postmodify.elements[checkboxFields[i]].checked) {
        x[x.length] = checkboxFields[i] + "=" + document.forms.postmodify.elements[checkboxFields[i]].value;
      }
    }
    sendXMLDocument(smf_scripturl + "?action=post2" + (current_board ? ";board=" + current_board : "") + (make_poll ? ";poll" : "") + ";preview;xml", x.join("&"), onDocSent);

    document.getElementById("preview_section").style.display = "";
    setInnerHTML(document.getElementById("preview_subject"), txt_preview_title);
    setInnerHTML(document.getElementById("preview_body"), txt_preview_fetch);

    return false;
  } else {
    return submitThisOnce(document.forms.postmodify);
  }
}
function onDocSent(XMLDoc) {
  if (!XMLDoc) {
    document.forms.postmodify.preview.onclick = new function () {
      return true;
    }
    document.forms.postmodify.preview.click();
  }

  // Show the preview section.
  var i, preview = XMLDoc.getElementsByTagName("smf")[0].getElementsByTagName("preview")[0];
  setInnerHTML(document.getElementById("preview_subject"), preview.getElementsByTagName("subject")[0].firstChild.nodeValue);

  var bodyText = "";
  for (i = 0; i < preview.getElementsByTagName("body")[0].childNodes.length; i++) {
    bodyText += preview.getElementsByTagName("body")[0].childNodes[i].nodeValue;
  }

  setInnerHTML(document.getElementById("preview_body"), bodyText);
  document.getElementById("preview_body").className = "post";

  // Show a list of errors (if any).
  var errors = XMLDoc.getElementsByTagName("smf")[0].getElementsByTagName("errors")[0];
  var numErrors = errors.getElementsByTagName("error").length, errorList = new Array();
  for (i = 0; i < numErrors; i++) {
    errorList[errorList.length] = errors.getElementsByTagName("error")[i].firstChild.nodeValue;
  }
  document.getElementById("errors").style.display = numErrors == 0 ? "none" : "";
  document.getElementById("error_serious").style.display = errors.getAttribute("serious") == 1 ? "" : "none";
  setInnerHTML(document.getElementById("error_list"), numErrors == 0 ? "" : errorList.join("<br />"));

  // Show a warning if the topic has been locked.
  document.getElementById("lock_warning").style.display = errors.getAttribute("topic_locked") == 1 ? "" : "none";

  // Adjust the color of captions if the given data is erroneous.
  var captions = errors.getElementsByTagName("caption"), numCaptions = errors.getElementsByTagName("caption").length;
  for (i = 0; i < numCaptions; i++) {
    if (document.getElementById("caption_" + captions[i].getAttribute("name"))) {
      document.getElementById("caption_" + captions[i].getAttribute("name")).style.color = captions[i].getAttribute("color");
    }
  }

  if (errors.getElementsByTagName("post_error").length == 1) {
    document.forms.postmodify.message.style.border = "1px solid red";
  } else if (document.forms.postmodify.message.style.borderColor == "red"
              || document.forms.postmodify.message.style.borderColor == "red red red red") {
    if (typeof(document.forms.postmodify.message.runtimeStyle) == "undefined") {
      document.forms.postmodify.message.style.border = null;
    } else {
      document.forms.postmodify.message.style.borderColor = "";
    }
  }

  // Set the new number of replies.
  if (document.forms.postmodify.elements["num_replies"]) {
    document.forms.postmodify.num_replies.value = XMLDoc.getElementsByTagName("smf")[0].getElementsByTagName("num_replies")[0].firstChild.nodeValue;
  }

  var newPosts = XMLDoc.getElementsByTagName("smf")[0].getElementsByTagName("new_posts")[0] ? XMLDoc.getElementsByTagName("smf")[0].getElementsByTagName("new_posts")[0].getElementsByTagName("post") : {length: 0};
  var numNewPosts = newPosts.length;
  if (numNewPosts != 0) {
    var parent = document.getElementById("replies_parent");
    for (i = 0; i < numNewPosts; i++) {
      parent.insertHTML += prepare_template({
        poster: newPosts[i].getElementsByTagName("poster")[0].firstChild.nodeValue,
        time: newPosts[i].getElementsByTagName("time")[0].firstChild.nodeValue,
        id: newPosts[i].getAttribute("id"),
        post: newPosts[i].getElementsByTagName("message")[0].firstChild.nodeValue
      }, replyTemplate);
    }
  }

  if (typeof(smf_codeFix) != "undefined") {
    smf_codeFix();
  }
}

function generateDays() {
  var dayElement = document.getElementById("day"), yearElement = document.getElementById("year"), monthElement = document.getElementById("month");
  var days, selected = dayElement.selectedIndex;

  monthLength[1] = yearElement.options[yearElement.selectedIndex].value % 4 == 0 ? 29 : 28;
  days = monthLength[monthElement.value - 1];

  // was a while below -.-
  if (dayElement.options.length) {
    dayElement.options[0] = null;
  }

  for (i = 1; i <= days; i++) {
    dayElement.options[dayElement.length] = new Option(i, i);
  }

  if (selected < days) {
    dayElement.selectedIndex = selected;
  }
}

function insertQuoteFast(messageid) {
  if (window.XMLHttpRequest) {
    getXMLDocument(smf_scripturl + "?action=quotefast;quote=" + messageid + ";sesc=" + session_id + ";xml", onDocReceived);
  } else {
    reqWin(smf_scripturl + "?action=quotefast;quote=" + messageid + ";sesc=" + session_id, 240, 90);
  }

  return true;
}
function onDocReceived(XMLDoc) {
  var text = "";
  for (var i = 0; i < XMLDoc.getElementsByTagName("quote")[0].childNodes.length; i++) {
    text += XMLDoc.getElementsByTagName("quote")[0].childNodes[i].nodeValue;
  }

  replaceText(text, document.forms.postmodify.message);
}


/** from topicindex.inc.php **/

var mouse_on_div;
function mouse_down(e) {
  if (in_edit_mode == 1 && mouse_on_div == 0) {
    modify_topic_save(session_id);
  }
}

// For templating, shown when an inline edit is made.
function modify_topic_show_edit(subject) {
  // Just template the subject.
  setInnerHTML(cur_subject_div, '<input type="text" name="subject" value="' + subject + '" size="60" style="width: 99%;"  maxlength="80" /><input type="hidden" name="topic" value="' + cur_topic_id + '" /><input type="hidden" name="msg" value="' + cur_msg_id.substr(4) + '" />');
}

// And the reverse for hiding it.
function modify_topic_hide_edit(subject) {
  // Re-template the subject!
  setInnerHTML(cur_subject_div, '<a href="' + smf_scripturl + '?topic=' + cur_topic_id + '.0">' + subject + '</a>');
}

/** from header.inc.php **/

function shrinkHeaderIC(mode) {
  if (user_is_guest) {
    document.cookie = "upshrinkIC=" + (mode ? 1 : 0);
  } else {
    smf_setThemeOption("collapse_header_ic", mode ? 1 : 0, null, session_id);
  }

  document.getElementById("upshrink_ic").src = smf_images_url + (mode ? "/expand.png" : "/collapse.png");

  document.getElementById("upshrinkHeaderIC").style.display = mode ? "none" : "";

  current_header_ic = mode;
}

/***********************************************
* Drop Down/ Overlapping Content-  Dynamic Drive (www.dynamicdrive.com)
* This notice must stay intact for legal use.
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function getposOffset(overlay, offsettype) {
  var totaloffset = (offsettype == "left") ? overlay.offsetLeft : overlay.offsetTop;
  var parentEl = overlay.offsetParent;
  while (parentEl != null) {
    totaloffset = (offsettype=="left") ? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
    parentEl = parentEl.offsetParent;
  }
  return totaloffset;
}

function overlay(curobj, subobjstr, opt_position) {
  if (document.getElementById) {
    var subobj = document.getElementById(subobjstr);
    subobj.style.display = (subobj.style.display != "block") ? "block" : "none";

    var xpos = getposOffset(curobj, "left");
    if (typeof opt_position != "undefined" && opt_position.indexOf("right") != -1) {
      xpos -= subobj.offsetWidth-curobj.offsetWidth;
    }

    var ypos = getposOffset(curobj, "top");
    if (typeof opt_position != "undefined" && opt_position.indexOf("bottom") != -1) {
      ypos += curobj.offsetHeight;
    }

    subobj.style.left = xpos + "px";
    subobj.style.top = ypos + "px";
    return false;
  } else {
    return true;
  }
}

function overlayclose(subobj) {
    document.getElementById(subobj).style.display = "none";
}

/** from register_before.inc.php **/
function verifyAgree() {
  if (document.forms.creator.passwrd1.value != document.forms.creator.passwrd2.value) {
    alert(register_passwords_differ_js);
    return false;
  }

// If they haven't checked the "I agree" box, tell them and don't submit.
  if (require_agreement && !document.forms.creator.regagree.checked) {
    alert(register_agree);
    return false;
  }

  // Otherwise, let it through.
  return true;
}

function checkAgree() {
  document.forms.creator.regSubmit.disabled = isEmptyText(document.forms.creator.user) || isEmptyText(document.forms.creator.email) || isEmptyText(document.forms.creator.passwrd1) || !document.forms.creator.regagree.checked;

  setTimeout("checkAgree();", 1000);
}

function refreshImages() {
  // Make sure we are using a new rand code.
  var new_url = new String(verificiation_image_href);
  new_url = new_url.substr(0, new_url.indexOf("rand=") + 5);

  // Quick and dirty way of converting decimal to hex
  var hexstr = "0123456789abcdef";
  for (var i=0; i < 32; i++) {
    new_url = new_url + hexstr.substr(Math.floor(Math.random() * 16), 1);
  }

  if (use_graphic_library) {
    document.getElementById("verificiation_image").src = new_url;
  } else {
    document.getElementById("verificiation_image_1").src = new_url + ";letter=1";
    document.getElementById("verificiation_image_2").src = new_url + ";letter=2";
    document.getElementById("verificiation_image_3").src = new_url + ";letter=3";
    document.getElementById("verificiation_image_4").src = new_url + ";letter=4";
    document.getElementById("verificiation_image_5").src = new_url + ";letter=5";
  }
}

/** from search.inc.php **/

function selectBoards(ids) {
  var toggle = true;

  for (i = 0; i < ids.length; i++) {
    toggle = toggle & document.forms.searchform["brd" + ids[i]].checked;
  }

  for (i = 0; i < ids.length; i++) {
    document.forms.searchform["brd" + ids[i]].checked = !toggle;
  }
}

function expandCollapseBoards() {
  var current = document.getElementById("searchBoardsExpand").style.display != "none";

  document.getElementById("searchBoardsExpand").style.display = current ? "none" : "";
  document.getElementById("exandBoardsIcon").src = smf_images_url + (current ? "/expand.gif" : "/collapse.gif");
}


function initSearch() {
  if (document.forms.searchform.search.value.indexOf("%u") != -1) {
    document.forms.searchform.search.value = unescape(document.forms.searchform.search.value);
  }
}

/** from profile_edit_theme.inc.php **/
function autoDetectTimeOffset() {
  // Get the difference between the two, set it up so that the sign will tell us who is ahead of who
  var diff = Math.round((localTime.getTime() - serverTime.getTime())/3600000);

  // Make sure we are limiting this to one day's difference
  diff %= 24;

  document.forms.creator.timeOffset.value = diff;
}

/** from profile_edit_forumprofile.inc.php **/
function tick() {
  if (typeof(document.forms.creator) != "undefined") {
    calcCharLeft();
    setTimeout("tick()", 1000);
  }
  else {
    setTimeout("tick()", 800);
  }
}

function calcCharLeft() {
  var oldSignature = "", currentSignature = document.forms.creator.signature.value;

  if (!document.getElementById("signatureLeft")) {
    return;
  }

  if (oldSignature != currentSignature) {
    oldSignature = currentSignature;

    if (currentSignature.replace(/\r/, "").length > maxLength) {
      document.forms.creator.signature.value = currentSignature.replace(/\r/, "").substring(0, maxLength);
    }
    currentSignature = document.forms.creator.signature.value.replace(/\r/, "");
  }

  setInnerHTML(document.getElementById("signatureLeft"), maxLength - currentSignature.length);
}

function changeSel(selected) {
  if (cat.selectedIndex == -1) {
    return;
  }

  if (cat.options[cat.selectedIndex].value.indexOf("/") > 0) {
    var i;
    var count = 0;

    file.style.display = "inline";
    file.disabled = false;

    for (i = file.length; i >= 0; i = i - 1) {
      file.options[i] = null;
    }

    for (i = 0; i < files.length; i++) {
      if (files[i].indexOf(cat.options[cat.selectedIndex].value) == 0) {
        var filename = files[i].substr(files[i].indexOf("/") + 1);
        var showFilename = filename.substr(0, filename.lastIndexOf("."));
        showFilename = showFilename.replace(/[_]/g, " ");

        file.options[count] = new Option(showFilename, files[i]);

        if (filename == selected) {
          if (file.options.defaultSelected) {
            file.options[count].defaultSelected = true;
          }
          else {
            file.options[count].selected = true;
          }
        }

        count++;
      }
    }

    if (file.selectedIndex == -1 && file.options[0]) {
      file.options[0].selected = true;
    }

    showAvatar();
  }
  else {
    file.style.display = "none";
    file.disabled = true;
    document.getElementById("avatar").src = avatardir + cat.options[cat.selectedIndex].value;
    document.getElementById("avatar").style.width = "";
    document.getElementById("avatar").style.height = "";
  }
}

function showAvatar() {
  if (file.selectedIndex == -1) {
    return;
  }

  document.getElementById("avatar").src = avatardir + file.options[file.selectedIndex].value;
  document.getElementById("avatar").alt = file.options[file.selectedIndex].text;
  document.getElementById("avatar").alt += file.options[file.selectedIndex].text == size ? "!" : "";
  document.getElementById("avatar").style.width = "";
  document.getElementById("avatar").style.height = "";
}

function previewExternalAvatar(src) {
  if (!document.getElementById("avatar")) {
    return;
  }
  var tempImage = new Image();

  tempImage.src = src;
  if (maxWidth != 0 && tempImage.width > maxWidth) {
    document.getElementById("avatar").style.height = parseInt((maxWidth * tempImage.height) / tempImage.width) + "px";
    document.getElementById("avatar").style.width = maxWidth + "px";
  }
  else if (maxHeight != 0 && tempImage.height > maxHeight) {
    document.getElementById("avatar").style.width = parseInt((maxHeight * tempImage.width) / tempImage.height) + "px";
    document.getElementById("avatar").style.height = maxHeight + "px";
  }
  document.getElementById("avatar").src = src;
}

/** from pm_folder.inc.php **/
var allLabels = {};
var currentLabels = {};
function loadLabelChoices()
{
  var listing = document.forms.pmFolder.elements;
  var theSelect = document.forms.pmFolder.pm_action;
  var add, remove, toAdd = {length: 0}, toRemove = {length: 0};

  if (theSelect.childNodes.length == 0)
    return;

  // This is done this way for internationalization reasons.
  if (typeof(allLabels[-1]) == "undefined")
  {
    for (var o = 0; o < theSelect.options.length; o++)
      if (theSelect.options[o].value.substr(0, 4) == "rem_")
        allLabels[theSelect.options[o].value.substr(4)] = theSelect.options[o].text;
  }

  for (var i = 0; i < listing.length; i++)
  {
    if (listing[i].name != "pms[]" || !listing[i].checked)
      continue;

    var alreadyThere = [], x;
    for (x in currentLabels[listing[i].value])
    {
      if (typeof(toRemove[x]) == "undefined")
      {
        toRemove[x] = allLabels[x];
        toRemove.length++;
      }
      alreadyThere[x] = allLabels[x];
    }

    for (x in allLabels)
    {
      if (typeof(alreadyThere[x]) == "undefined")
      {
        toAdd[x] = allLabels[x];
        toAdd.length++;
      }
    }
  }

  while (theSelect.options.length > 2)
    theSelect.options[2] = null;

  if (toAdd.length != 0)
  {
    theSelect.options[theSelect.options.length] = new Option(pm_msg_label_apply, "");
    setInnerHTML(theSelect.options[theSelect.options.length - 1], pm_msg_label_apply);
    theSelect.options[theSelect.options.length - 1].disabled = true;

    for (i in toAdd)
    {
      if (i != "length")
        theSelect.options[theSelect.options.length] = new Option(toAdd[i], "add_" + i);
    }
  }

  if (toRemove.length != 0)
  {
    theSelect.options[theSelect.options.length] = new Option(pm_msg_label_remove, "");
    setInnerHTML(theSelect.options[theSelect.options.length - 1], pm_msg_label_remove);
    theSelect.options[theSelect.options.length - 1].disabled = true;

    for (i in toRemove)
    {
      if (i != "length")
        theSelect.options[theSelect.options.length] = new Option(toRemove[i], "rem_" + i);
    }
  }
}

// from pm_send.inc.php
function autocompleter(element) {
  if (typeof(element) != "object")
    element = document.getElementById(element);

  this.element = element;
  this.key = null;
  this.request = null;
  this.source = null;
  this.lastSearch = "";
  this.oldValue = "";
  this.cache = [];

  this.change = function (ev, force) {
    if (window.event)
      this.key = window.event.keyCode + 0;
    else
      this.key = ev.keyCode + 0;
    if (this.key == 27)
      return true;
    if (this.key == 34 || this.key == 8 || this.key == 13 || (this.key >= 37 && this.key <= 40))
      force = false;

    if (isEmptyText(this.element))
      return true;

    if (this.request != null && typeof(this.request) == "object")
      this.request.abort();

    var element = this.element, search = this.element.value.replace(/^("[^"]+",[ ]*)+/, "").replace(/^([^,]+,[ ]*)+/, "");
    this.oldValue = this.element.value.substr(0, this.element.value.length - search.length);
    if (search.substr(0, 1) == '"')
      search = search.substr(1);

    if (search == "" || search.substr(search.length - 1) == '"')
      return true;

    if (this.lastSearch == search)
    {
      if (force)
        this.select(this.cache[0]);

      return true;
    } else if (search.substr(0, this.lastSearch.length) == this.lastSearch && this.cache.length != 100) {
      // Instead of hitting the server again, just narrow down the results...
      var newcache = [], j = 0;
      for (var k = 0; k < this.cache.length; k++) {
        if (this.cache[k].substr(0, search.length) == search)
          newcache[j++] = this.cache[k];
      }

      if (newcache.length != 0) {
        this.lastSearch = search;
        this.cache = newcache;

        if (force)
          this.select(newcache[0]);

        return true;
      }
    }

    this.request = new XMLHttpRequest();
    this.request.onreadystatechange = function () {
      element.autocompleter.handler(force);
    }

    this.request.open("GET", this.source + escape(textToEntities(search).replace(/&#(\d+);/g, "%#$1%")).replace(/%26/g, "%25%23038%25") + ";" + (new Date().getTime()), true);
    this.request.send(null);

    return true;
  }
  
  
  this.keyup = function (ev) {
    this.change(ev, true);

    return true;
  }
  this.keydown = function () {
    if (this.request != null && typeof(this.request) == "object")
      this.request.abort();
  }
  this.handler = function (force) {
    if (this.request.readyState != 4)
      return true;

    var response = this.request.responseText.split("\n");
    this.lastSearch = this.element.value;
    this.cache = response;

    if (response.length < 2)
      return true;

    if (force)
      this.select(response[0]);

    return true;
  }
  this.select = function (value) {
    if (value == "")
      return;

    var i = this.element.value.length + (this.element.value.substr(this.oldValue.length, 1) == '"' ? 0 : 1);
    this.element.value = this.oldValue + '"' + value + '"';

    if (typeof(this.element.createTextRange) != "undefined")
    {
      var d = this.element.createTextRange();
      d.moveStart("character", i);
      d.select();
    }
    else if (this.element.setSelectionRange)
    {
      this.element.focus();
      this.element.setSelectionRange(i, this.element.value.length);
    }
  }

  this.element.autocompleter = this;
  this.element.setAttribute("autocomplete", "off");

  this.element.onchange = function (ev) {
    this.autocompleter.change(ev);
  }
  this.element.onkeyup = function (ev) {
    this.autocompleter.keyup(ev);
  }
  this.element.onkeydown = function (ev) {
    this.autocompleter.keydown(ev);
  }
}


// from pm_search.inc.php
function expandCollapseLabels() {
  var current = document.getElementById("searchLabelsExpand").style.display != "none";

  document.getElementById("searchLabelsExpand").style.display = current ? "none" : "";
  document.getElementById("expandLabelsIcon").src = smf_images_url + (current ? "/expand.png" : "/collapse.png");
}