var expand_min_height = 50;

function expand_resize(obj) {
	$(obj).siblings('div.expand_div').html(expand_escaped_text_value(obj));
	var local_expand_min = $(obj).attr('expand_min_height');
	if(local_expand_min === undefined) {
		local_expand_min = expand_min_height;
	} else {
		local_expand_min = parseInt(local_expand_min, 10);
	}
	var new_height = Math.max($(obj).siblings('div.expand_div').outerHeight(), local_expand_min);
	if($(this).attr('last_height') != new_height)
	{
	  $(obj).css("height", new_height + "px");
	}
	last_height = new_height;
}

function expand_escaped_text_value(obj) {
	var value = $(obj).val();
	value = value.replace(/&/g, "&#38;");
	value = value.replace(/</g, "&#60;");
	value = value.replace(/\n/g, "<br/>");
	value = value + "&nbsp;";
	return value;
}

function expand(textarea) {
	var last_height = 0;
	
	var textarea = $(textarea);
	if (textarea == undefined || textarea.length == 0)
		throw "Invalid textarea given to expand.";
	
	// Unbind resize events
	$(textarea).unbind('change', expand_resize);
	$(textarea).unbind('keyup', expand_resize);
	
	//$(this).attr('last_height', 0);
	$('<div class="expand_div"></div>').insertAfter($(textarea));
	
	var textarea_div = $(textarea).next('div.expand_div');
	textarea_div.css({
		'line-height': $(textarea).css('line-height'),
		'width': (parseFloat($(textarea).css('width')) - 6) + 'px',
		'font-size': $(textarea).css('font-size'),
		'font-family': $(textarea).css('font-family'),
		'font-weight': $(textarea).css('font-weight'),
		//'padding': $(textarea).css('padding'),
		'letter-spacing': $(textarea).css('letter-spacing'),
		'position': 'absolute',
		'left': '-9999px',
		'top': '0px'
	});
	
	$(textarea).change(function() {
		expand_resize(textarea);
	});
	$(textarea).keyup(function() {
		expand_resize(textarea);
	});
}
