package com.hexa.client.ui;

import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.FontStyle;
import com.google.gwt.dom.client.Style.FontWeight;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.TextArea;

public class GrowingTextArea extends TextArea implements KeyDownHandler, KeyUpHandler
{
	Element fakeDiv = null;

	public GrowingTextArea()
	{
		addKeyDownHandler( this );
		addKeyUpHandler( this );

		// getElement().getStyle().setOverflow( Overflow.HIDDEN );
		applyStyle( getElement() );
	}

	void applyStyle( Element element )
	{
		element.getStyle().setPadding( 5, Unit.PX );
		element.getStyle().setBorderColor( "black" );
		element.getStyle().setBorderStyle( BorderStyle.SOLID );
		element.getStyle().setBorderWidth( 1, Unit.PX );

		element.getStyle().setProperty( "fontFamily", "Arial Unicode MS,Arial,sans-serif" );

		element.getStyle().setFontSize( 12, Unit.PT );
		element.getStyle().setFontStyle( FontStyle.NORMAL );
		element.getStyle().setFontWeight( FontWeight.NORMAL );
	}

	void resize()
	{
		if( fakeDiv == null )
		{
			fakeDiv = DOM.createDiv();
			fakeDiv.getStyle().setPosition( Position.FIXED );
			fakeDiv.getStyle().setLeft( -10000, Unit.PX );
			getElement().getParentElement().insertAfter( fakeDiv, getElement() );
			applyStyle( fakeDiv );
		}

		int width = getElement().getAbsoluteRight() - getElement().getAbsoluteLeft();
		fakeDiv.getStyle().setWidth( width - 10 - 2, Unit.PX );

		fakeDiv.setInnerText( getText() );

		int height = getHeightImpl( getElement() );
		int newHeight = getHeightImpl( fakeDiv ) + 25;
		if( height < newHeight )
			getElement().getStyle().setHeight( newHeight, Unit.PX );
	}

	private native int getHeightImpl( Element e )
	/*-{
		return $wnd.$( e ).height();
	}-*/;

	@Override
	public void onKeyUp( KeyUpEvent event )
	{
		resize();
	}

	@Override
	public void onKeyDown( KeyDownEvent event )
	{
		resize();
	}
}

@@ -1885,77 +1885,79 @@
  get
-HeightImpl( getElement() );%0A%09%09int newHeight = getHeightImpl( fakeDiv 
+Element().getClientHeight();%0A%09%09int newHeight = fakeDiv.getClientHeight(
 ) + 
@@ -2051,104 +2051,12 @@
  );%0A
+
 %09%7D%0A%0A
-%09private native int getHeightImpl( Element e )%0A%09/*-%7B%0A%09%09return $wnd.$( e ).height();%0A%09%7D-*/;%0A%0A
 %09@Ov

use not jquery where not extremely inevitable