// Textarea Expander v1.2
// Copyright (C) 2005 Digital Routes, Scotland
// http://digitalroutes.co.uk/library
// This code is licensed under the GPL, see www.gnu.org for details.

// Automatically expands all textareas in a web page so that they
// are slightly longer than their contents (no vertical scrollbar)

// Include at the bottom of your page:
// <SCRIPT LANGUAGE='JavaScript1.2' SRC='expand.js'></SCRIPT>


// Locate all the document's textareas.
// Adds "onkeypress='expand_soon()'" to each textarea.
// Existing onkeypress code is preserved.
function expand_init() {
  expand_textareas = document.getElementsByTagName('TEXTAREA');
  var ta;
  for (var z=0;z<expand_textareas.length;z++) {
    expand_pids[z]=0;
    ta = expand_textareas[z];
    if (ta.onkeypress) {
      expand_oldkeypress[expand_oldkeypress.length] = ta.onresize;
      ta.onkeypress = new Function("expand_soon("+z+");expand_oldkeypress["+z+"]()");
    } else
      ta.onkeypress = new Function("expand_soon("+z+")");
    expand_soon(z);
  }
}

// Increase the height of each textarea if needed.
function expand_now(z) {
  expand_pids[z] = 0;
  var textarea = expand_textareas[z];
  var lines = textarea.value.split('\n');
  var rows = expand_free;
  for (var x=0;x<lines.length;x++) {
    rows += Math.ceil((1+lines[x].length)/textarea.cols);
  }
  if (rows>textarea.rows || (expand_contract && rows<textarea.rows)) {
    textarea.rows=rows;
    if (window.onresize)
      window.onresize();
  }
}

// Schedule a vertical expansion in half a second.
function expand_soon(z) {
  if (expand_pids[z] != 0)
    clearTimeout(expand_pids[z]);
  expand_pid = setTimeout("expand_now("+z+")", 500);
}

var expand_textareas = [];   // List of textarea objects
var expand_oldkeypress = []; // List of existing onkeypress functions for each box
var expand_pids = [];        // Task IDs of the queued expansion threads
var expand_free = 5;         // Number of lines to be kept free
var expand_contract = false; // Contract as well as expand.


