/*
 * TBAutoSize
 *
 * automatic resizing of textboxes depending on their content
 */

function TBAutoSize(textbox, emptylines)
{
  if (emptylines == undefined) { emptylines = 2; }
  var focus = false;

  function adjust()
  {
    var content = textbox.value.replace(/\r\n|\r|\n/g, "\n");
    if (focus)
    {
      textbox.className = "focus";
    }
    else
    {
      textbox.className = undefined;
    }
    if (content.length == 0)
    {
      textbox.rows = emptylines;
      if (!focus)
      {
        textbox.className = "empty";
      }
      return;
    }
    var count = emptylines;
    var tmp = 0;
    for (var i = 0; i < content.length; i++)
    {
      tmp++;
      if ( (content.charCodeAt(i) == 10)
	  || (tmp == textbox.cols) )
      {
	count++;
	tmp = 0;
      }
    }
    textbox.rows = count;
  }

  textbox.onkeyup = function() { adjust(); };
  textbox.onkeypress = function() { adjust(); };
  textbox.onkeydown = function() { adjust(); };
  textbox.onchange = function() { adjust(); };
  textbox.onclick = function() { adjust(); };
  textbox.onpaste = function() { adjust(); };
  textbox.onfocus = function() { focus = true; adjust(); };
  textbox.onblur = function () { focus = false; adjust(); };

  adjust();
}

