﻿package TableWidget{
	
	import adobe.utils.CustomActions;
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import fl.managers.FocusManager;
	
	
	
	public class CellEditor extends EventDispatcher
	{
		
		private static var instance:CellEditor;
		private var cellText:TextField;
		private var rootRef;
		public const KILLFOCUS:String = "killFocus";
		public const UPDATEHEIGHT:String = "updateHeight";
		private var fm:FocusManager;
		
		public function CellEditor()
		{
			
		}
		
		/**
		* This function initializes the cell editor.
		*
		*/
		public function init(inTargetRef:MovieClip)
		{
			cellText = inTargetRef.cellText;
			
		}
		
		
		public function enableEditor(inRootRef, index)
		{
			rootRef = inRootRef;
			fm = new FocusManager(rootRef);
			
			cellText.type = "input";
			cellText.selectable = true;
			if(index == -1){
				cellText.setSelection(cellText.text.length, cellText.text.length)
			}else{
				cellText.setSelection(index, index);
			}
			fm.setFocus(cellText);
			cellText.addEventListener(KeyboardEvent.KEY_DOWN, onKey)
			cellText.addEventListener(KeyboardEvent.KEY_UP, onKey)
		}
		
		
		private function onKey(evt:KeyboardEvent)
		{
			var selectionMC = rootRef.getChildByName("selectionMC");
			if (evt.keyCode != 13)
			{
				dispatchEvent(new Event(UPDATEHEIGHT));
			}
			else
			{
				dispatchEvent(new Event(KILLFOCUS));
				cellText.removeEventListener(KeyboardEvent.KEY_DOWN, onKey)
				cellText.removeEventListener(KeyboardEvent.KEY_UP, onKey)
			}
		}
		
		
	}
}