package com.smartgwt.sample.client;

import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.events.DrawEvent;
import com.smartgwt.client.widgets.events.DrawHandler;

public class CKEditor extends Canvas {
	{
		setOverflow(Overflow.VISIBLE);
		setCanDragResize(false);
		setRedrawOnResize(false);
		setZIndex(0);
	}

	private boolean initialised = false;

	public CKEditor(String id) {
		super(id);

		addDrawHandler(new DrawHandler() {
			@Override
			public void onDraw(DrawEvent event) {
				loadCKEditor();
			}
		});
		
	}

	

    
	@Override
	public String getInnerHTML() {
		if (this.getContents() != null) {
			return "<textarea style='width=100%;height=100%' id="
					+ this.getID() + "_ta>" + getContents() + "</textarea>";
		}
		return "<textarea style='width=100%;height=100%' id=" + this.getID()
				+ "_ta></textarea>";
	}

	// @Override
	// public void draw() {
	// super.draw();
	// loadCKEditor();
	// }
	
	/**
			var me = this;
			$wnd.CKEDITOR.instances[ editorId ].on( 'blur', function(ev){
				me.@com.smartgwt.sample.client.CKEditor::dispatchBlur()();
			}); 
	 */
	protected native void loadCKEditor() /*-{
		if (!this.@com.smartgwt.sample.client.CKEditor::initialised) {
			var editorId = this.@com.smartgwt.sample.client.CKEditor::getID()() + "_ta";
			$wnd.CKEDITOR.replace(editorId);
			this.@com.smartgwt.sample.client.CKEditor::initialised = true;
			var _this = this;
			
			$wnd.CKEDITOR.instances[ editorId ].on( 'change', function( env ) {
				_this.@com.smartgwt.sample.client.CKEditor::change()();
			});
		}
	}-*/;
	
	
	
	public void change() {
		// some code.
		if ( null != cKEditorItem ) {
			System.out.println( "change store value: ");
			cKEditorItem.storeValue();
		}
	}
	

	public boolean isLoaded() {
		return initialised;
	}

	private CKEditorItem cKEditorItem;

	public void setCKEditorItem(CKEditorItem cKEditorItem) {
		this.cKEditorItem = cKEditorItem;
	}
    
}