/* 
 * Auto Expanding Text Area
 * by Chrys Bader (www.chrysbader.com)
 *  modified by jake@hybridstudio.com
 *
 * Version 1.0
 * 01/10/2008
 *
 * NOTE: This script requires jQuery to work.  Download jQuery at www.jquery.com
 *
 */

$(function() {
    $.expandingTA($('textarea.expanding')); // initial call to all elems of textarea.expanding                  
});

$.expandingTA = function(elems) 
{
    // turn each element into an expanding text area
    elems.each( function()  
    {       
        var _interval = null;
        var _dummy = null;
        var _self = this;
        var _prevHeight = 0;
        var _min_height;

        // magically expand the textarea
        $(_self).bind('focus', __checkExpand)
            .bind('blur', __stopExpand)
            .css('overflow', 'hidden');

        function __checkExpand()
        {
            _min_height = $(_self).height();

            _interval = setInterval(function() { 
                __expandUpdate(); 
            }, 150);
        }

        function __stopExpand()
        {
            clearInterval(_interval);   
        }

        function __expandUpdate()
        {
            var line_height = 16;   // 16px assumed

            if ( _dummy == null ) { // create dummy

                _dummy = $('<div></div>')
                _dummy.css( {
                                'font-size':    $(_self).css('font-size'),
                                'font-family':  $(_self).css('font-family'),
                                'width':        $(_self).css('width'),
                                'padding':      $(_self).css('padding'),
                                'xline-height':  line_height,
                                'overflow-x':   'hidden',
                                'display':      'none'
                            }).appendTo('body');
            }

            // update html in dummy div
            var newHtml = $(_self).val().replace(/\n/g, '<br>new');

            if( _dummy.html() != newHtml ) {

                _dummy.html( newHtml );
                var newHeight = Math.max(_min_height, _dummy.height() + line_height);

                if (_prevHeight != newHeight) {

                    //$(_self).height(newHeight);
                    $(_self).animate({height:(newHeight)}, 100);    // animate?

                    _prevHeight = newHeight;
                }
            }
        }
    });
}