<?xml version="1.0" encoding="utf-8"?>
<!--
////////////////////////////////////////////////////////////////////////////////
// 株式会社　アイエルエス
// Copyright 2008 ILS
// All Rights Reserved.
//
// NOTICE:  田中センイ共通伝票グリッド
////////////////////////////////////////////////////////////////////////////////
-->
<IlsDataGrid xmlns="cls.com.ils.common.component.*" xmlns:mx="http://www.adobe.com/2006/mxml"
	sortableColumns="false"
	draggableColumns="false" 
	creationComplete="onCreationComplete()"
	change="changeRow(event)"
	>
	<mx:Script>
		<![CDATA[
			import commonLibrary.sharedComponent.*;
			import mx.collections.ArrayCollection;
			import mx.controls.dataGridClasses.DataGridColumn;
			import mx.core.SpriteAsset;
			import mx.core.FlexSprite;
			import mx.validators.Validator;
			import mx.controls.listClasses.IListItemRenderer;
			import mx.controls.Button;
			import mx.controls.dataGridClasses.DataGridItemRenderer;
			import mx.events.CloseEvent;
			import mx.controls.Alert;
			import mx.events.ValidationResultEvent;
			import mx.events.DataGridEventReason;
			import mx.events.ListEvent;
			import cls.com.ils.biz.utility.logging.AppLoggingTool;
			import mx.managers.IFocusManagerComplexComponent;
			import mx.managers.IFocusManagerComponent;
			import mx.controls.DataGrid;
			import cls.com.ils.biz.model.SharedPlace;
			import mx.events.DataGridEvent;
			import cls.com.ils.common.model.MsgMgr;
			import mx.collections.XMLListCollection;
			
		    //----------------------------------
		    //  addRowFunction
		    //----------------------------------
		
		    /**
		     *  @private
		     *  Storage for the addRowFunction property.
		     */
		    private var _addRowFunction:Function;
		
		    [Bindable("addRowFunctionChanged")]
		    [Inspectable(category="General")]
		    
		    /**
		     *  @inheritDoc
		     *
		     *  @see #refresh()
		     */
		    public function get addRowFunction():Function
		    {
		        return _addRowFunction;
		    }
		
		    /**
		     *  @private
		     */
		    public function set addRowFunction(f:Function):void
		    {
		        _addRowFunction = f;
		        dispatchEvent(new Event("addRowFunctionChanged"));
		    }

		    //----------------------------------
		    //  delRowFunction
		    //----------------------------------
		
		    /**
		     *  @private
		     *  Storage for the delRowFunction property.
		     */
		    private var _delRowFunction:Function;
		
		    [Bindable("delRowFunctionChanged")]
		    [Inspectable(category="General")]
		    
		    /**
		     *  @inheritDoc
		     *
		     *  @see #refresh()
		     */
		    public function get delRowFunction():Function
		    {
		        return _delRowFunction;
		    }
		
		    /**
		     *  @private
		     */
		    public function set delRowFunction(f:Function):void
		    {
		        _delRowFunction = f;
		        dispatchEvent(new Event("delRowFunctionChanged"));
		    }

		    //----------------------------------
		    //  rsFunction
		    //----------------------------------
		
		    /**
		     *  @private
		     *  Storage for the rsFunction property.
		     */
		    private var _rsFunction:Function;
		
		    [Bindable("rsFunctionChanged")]
		    [Inspectable(category="General")]
		    
		    /**
		     *  @inheritDoc
		     *
		     *  @see #refresh()
		     */
		    public function get rsFunction():Function
		    {
		        return _rsFunction;
		    }
		
		    /**
		     *  @private
		     */
		    public function set rsFunction(f:Function):void
		    {
		        _rsFunction = f;
		        dispatchEvent(new Event("rsFunctionChanged"));
		    }
		    
		    //----------------------------------
		    //  defaultColumn
		    //----------------------------------
		
		    /**
		     *  @private
		     */
		    private var _defaultColumn:int = 0;
				
		    /**
		     *  @default 0
		     */
		    public function get defaultColumn():int
		    {
		        return _defaultColumn;
		    }
		    
		    /**
		     *  @private
		     */
		    public function set defaultColumn(value:int):void
		    {
		        _defaultColumn = value;
		    }

	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        // ErrorList
	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        private var _errorList:ArrayCollection = new ArrayCollection();
	        /**
	         * エラーオブジェクトが格納されるリスト。
	         * このリストをDataGridにBind設定する。
	         */        
	        public function get errorList():ArrayCollection
	        {
	        	return this._errorList;
	        }
	        /**
	         * 
	         * @private
	         * 
	         */        
	        [Bindable]
	        public function set errorList(value:ArrayCollection):void
	        {
	        	this._errorList = value;
	        }

	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        // addError
	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        /**
	         * エラーリストにエラーを追加
	         * @param error:ErrorModel
	         */        
	        public function addError(error:String,index:int):void
	        {
	        	this.errorList.addItemAt(error,index);
	        }
	
	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        // removeError
	        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	        /**
	         * エラーリストから指定indexのエラーを削除
	         * @param index:int
	         */        
	        public function removeError(index:int):void
	        {
	        	this.errorList.removeItemAt(index);
	        }

			private function onCreationComplete():void
			{
				addEventListener(KeyboardEvent.KEY_DOWN,onKeyDownHandler);
	            addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler);
	            addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler);
	            addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
	            addEventListener(DataGridEvent.ITEM_EDIT_END, itemEditEndHandler);
	            addEventListener(DataGridEvent.ITEM_EDIT_BEGINNING, itemEditBeginningHandler);
			}

	        private function changeRow(event:ListEvent): void 
	        {
	        	
	        }

		    override protected function mouseDownHandler(event:MouseEvent):void
		    {
		        var r:IListItemRenderer;
		        var s:Sprite;
				var lastItemDown:IListItemRenderer;
			
		        r = mouseEventToItemRenderer(event);
		
		        lastItemDown = null;
						
		        var isItemEditor:Boolean = itemRendererContains(itemEditorInstance, DisplayObject(event.target));
		
		        // If it isn't an item renderer, or an item editor do default behavior
		        if (!isItemEditor)
		        {
		            var pos:Point;
		            if (r)
		            {
		                lastItemDown = r;
		
		                pos = itemRendererToIndices(r);
		
		                var bEndedEdit:Boolean = true;
		
		                if (itemEditorInstance)
		                {
		                    if (columns[pos.x].editable == false)
			                    return;
		                }
		
		            }
		            else
		            {
		                // trace("end edit?");
		                if (itemEditorInstance)
		                    return;
		            }
		
		            super.mouseDownHandler(event);
		
		        }
		    }

		    /**
		     *  @private
		     */
		    private function itemEditBeginningHandler(event:DataGridEvent):void
		    {
				AppLoggingTool.logger.debug("itemEditBeginningHandler=======================");
	            if(itemEditorInstance && event.reason != DataGridEventReason.CANCELLED){
	                var property:String = columns[event.columnIndex].dataField;	   
	                //アイテムエディタの値を更新する         	
					itemEditorInstance[columns[event.columnIndex].editorDataField] = selectedItem[property];
	            }
		    }

		    /**
		     *  @private
		     */
		    private function itemEditEndHandler(event:DataGridEvent):void
		    {
		    	if(event.isDefaultPrevented()){
		    		//グリッド内のアイテムエディタ以外にマウスを移動した際に編集を終了させたくない為に
		    		//動作を制御する
		    		event.stopPropagation();
//					event.stopImmediatePropagation();	
		    	}else{
					AppLoggingTool.logger.debug(event.reason);
					if(event.reason != DataGridEventReason.NEW_COLUMN){
				        var parent:Object = event.currentTarget.parentDocument;
				        if (parent is AppPanel)
				        {
				            if (dataProvider[event.rowIndex].errFlg == 1){
				            	//相関チェック
				            	parent.lblErrMsg.text = this.dataProvider[event.rowIndex].errMsg;
					        	event.preventDefault();
					        	return;
							}
							if(parent.validatorBody){
								//行チェック
								var err_ary:Array = Validator.validateAll(parent.validatorBody);
					            if (err_ary.length > 0) {
					            	parent.lblErrMsg.text = columns[err_ary[0].field].headerText +"：" + err_ary[0].message;
//				            		var value:Array = [{columnIndex: err_ary[0].field, rowIndex: event.rowIndex}];
//				            		callLater(setEditedItemPosition,value);
						        	event.preventDefault();
									event.stopImmediatePropagation();	
						        	return;
					            }else{
					            	parent.lblErrMsg.text = "";
					            }
							}
				        }
						//編集できない状態になった場合または新しい行にフォーカスが移動した場合
						//レコード後処理
			            if (rsFunction != null)
			            {
			            	//レコード後処理
			            	rsFunction(event);
			            }						
					}
		    	}
		    }
		    
		    /**
		     *  @private
		     */
		    private function onKeyDownHandler(event:KeyboardEvent):void
		    {
	            //下向き矢印キーに対するイベントの場合
	            if(event.keyCode == Keyboard.DOWN)
	            {
	                //０行の場合
	                if(dataProvider.length == 0)
	                {
	                    //行追加
	                    addRow();
	                }
	            }
	                //Enterキーに対するイベントの場合
                if(event.keyCode == Keyboard.ENTER)
                {
					var focusEvent:FocusEvent = new FocusEvent(FocusEvent.KEY_FOCUS_CHANGE, true, true, null, event.shiftKey, Keyboard.TAB);
                    dispatchEvent(focusEvent);
//					//TABキーの機能を変更する場合は下記を使用
//					var focusEvent:FocusEvent = new FocusEvent(FocusEvent.KEY_FOCUS_CHANGE, false, false, null, event.shiftKey, Keyboard.TAB);
//					dispatchEvent(focusEvent);                	
                }
		    }

		    private function keyFocusChangeHandler(event:FocusEvent):void
		    {		    	
//		    	if(editedItemPosition){
//			        var rowIndex:int = editedItemPosition.rowIndex;
//	//		        var columnIndex:int = editedItemPosition.columnIndex;
//	
//			        var index:int = editedItemPosition.rowIndex;
//			        var colIndex:int = editedItemPosition.columnIndex;
//			
//			        var found:Boolean = false;
//			        var incr:int = event.shiftKey ? -1 : 1;
//			        var maxIndex:int = collection.length - 1;
//			
//			        //有効なフォーカスを見つけるまで、またはグリッドの最後までループさせる
//			        while (!found)
//			        {
//			            // go to next column
//			            colIndex += incr;
//			            if (colIndex >= columns.length || colIndex < 0)
//			            {
//			                // 列の最初または最後の場合
//			                colIndex = (colIndex < 0) ? columns.length - 1 : 0;
//			                // and increment/decrement the row index
//			                index += incr;
//					        if(this.dataProvider[rowIndex].errFlg == 1)
//					        {
//								MsgMgr.dispServerMsgAndCallEvent("",this.dataProvider[rowIndex].errMsg,TsPanel(this.parentDocument).title,Alert.OK,setErrFocus);
//					        	event.preventDefault();
//					        }	
//			            }
//			            if (columns[colIndex].editable && columns[colIndex].visible)
//			            {
//				            // 編集可能で非表示でない場合
//			                found = true;
//			            }
//			        }
//		        }
//
//		        if (event.keyCode == Keyboard.TAB)
//		        {
////			        var dataGridEvent:DataGridEvent =
////			            new DataGridEvent(DataGridEvent.ITEM_EDIT_END, false, false);
////			            // ITEM_EDIT events are cancelable
////			        dataGridEvent.columnIndex = editedItemPosition.columnIndex;
////			        dataGridEvent.dataField = columns[editedItemPosition.columnIndex].dataField;
////			        dataGridEvent.rowIndex = editedItemPosition.rowIndex;
////			        dataGridEvent.itemRenderer = editedItemRenderer;
////			        dataGridEvent.reason = DataGridEventReason.OTHER;
////			        dispatchEvent(dataGridEvent);
////					var o:IFocusManagerComponent = focusManager.getNextFocusManagerComponent(event.shiftKey);
////					
////					if (o)
////					{
////						if (o is IFocusManagerComplexComponent)
////							IFocusManagerComplexComponent(o).assignFocus(event.shiftKey ? "bottom" : "top");
////						else
////							focusManager.setFocus(o);
////					}
////		            event.preventDefault();
//		        }
		    }
		    
			//NG
			private function setErrFocus(e:CloseEvent):void{				
//				setFocus();								
			}
			
		    private function mouseFocusChangeHandler(event:FocusEvent):void
		    {
		    	//itemEditorの場合、itemEditEndより先にこのイベントが発生する	    	
		    	if(editedItemPosition){
			        var rowIndex:int = editedItemPosition.rowIndex;
			        var colIndex:int = editedItemPosition.columnIndex;

			        var parent:Object = event.currentTarget.parentDocument;
//	                var property:String = columns[colIndex].dataField;	   

//					selectedItem[property] = event.target.text;

			    	if(event.relatedObject is DataGridItemRenderer
			    		|| event.relatedObject is CheckBoxEditor
			    		|| event.relatedObject is ComboBoxEditor
			    		|| event.relatedObject is ZoomButton
			    		|| event.relatedObject is CloseButton){			    			
			    		//入力チェックを行わない
			    		
			    	}else if((event.relatedObject is SpriteAsset || event.relatedObject is FlexSprite)
						&& event.relatedObject.name != "btnRegi"){
//			        	event.preventDefault();
			    	}else{
			    		var resultEvent:ValidationResultEvent;
			    		//閉じるボタン、ズームボタン、DataGrid以外にマウスが移動した場合
						if(itemEditorInstance && itemEditorInstance is TextInputEditor){
							var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
							if (editor.getValidator() != null && editor.getValidator().enabled == true){
								//データ検証結果
					            resultEvent = editor.getValidator().validate();
					            if (resultEvent.type == ValidationResultEvent.INVALID || this.dataProvider[rowIndex].errFlg == 1){
					            	if(resultEvent.results){
						            	parent.lblErrMsg.text = columns[colIndex].headerText +"：" + resultEvent.message;
					            	}else{
						            	parent.lblErrMsg.text = this.dataProvider[rowIndex].errMsg;
					            	}
					            	setFocus();
						        	event.preventDefault();
								}else{
					            	parent.lblErrMsg.text = ""								
								}
							}else{
				            	parent.lblErrMsg.text = ""
							}
						}else if(itemEditorInstance && itemEditorInstance is DateFieldEditor){
							var dateEditor:DateFieldEditor = itemEditorInstance as DateFieldEditor;
							if (dateEditor.getValidator() != null && dateEditor.getValidator().enabled == true){
								//データ検証結果
					            resultEvent = dateEditor.getValidator().validate();
					            if (resultEvent.type == ValidationResultEvent.INVALID || this.dataProvider[rowIndex].errFlg == 1){
					            	if(resultEvent.results){
						            	parent.lblErrMsg.text = columns[colIndex].headerText +"：" + resultEvent.message;
					            	}else{
						            	parent.lblErrMsg.text = this.dataProvider[rowIndex].errMsg;
					            	}
					            	setFocus();
						        	event.preventDefault();
								}else{
					            	parent.lblErrMsg.text = ""								
								}
							}else{
				            	parent.lblErrMsg.text = ""
							}
						}	    					    					    		
			    	}
		    	}
				AppLoggingTool.logger.debug("mouseFocusChangeHandler=======================");
		    }
		    			
		    private function onMouseDownHandler(event:MouseEvent):void
		    {
				AppLoggingTool.logger.debug("onMouseDownHandler=======================");
				event.stopPropagation();    	
		    }

			/**
			 * 行追加
			 */		
			public function addRow(defaultFlg:Boolean = false):void{
				
				var addXml:String = new String();
				
				if(this.dataProvider.length > 0){
					if(!parentDocument.validate()){
						return;
					}
				}

				if(parentDocument.validatorBody){
					if(selectedItem && selectedIndex > -1){
						//行チェック
						var err_ary:Array = Validator.validateAll(parentDocument.validatorBody);
			            if (err_ary.length > 0) {
			            	parentDocument.lblErrMsg.text = columns[err_ary[0].field].headerText +"：" + err_ary[0].message;
							editedItemPosition = {columnIndex: err_ary[0].field, rowIndex: selectedIndex};
				        	return;
			            }else{
			            	if(parentDocument.lblErrMsg.text != ""){
//			            	if(this.dataProvider[selectedIndex].errFlg == 1){
								editedItemPosition = {columnIndex: 0, rowIndex: selectedIndex};
								return
			            	}else{
			            		parentDocument.lblErrMsg.text = "";
		            		}
			            }
					}
				}

				addXml = "<line></line>" ;

				this.dataProvider.addItem(new XML(addXml));
																	
				this.dataProvider.refresh();
				this.selectedIndex = this.dataProvider.length;
				
	            if (addRowFunction != null)
	            {
	            	//行追加時の初期設定
	            	addRowFunction();
	            }

				if(!defaultFlg){
					//新規の行の2列目にフォーカスを移す
					this.editedItemPosition = {columnIndex: defaultColumn, rowIndex: this.dataProvider.length - 1};					
				}
			}
			
			// 行削除
			public function delRow():void{			
				var sel:int = selectedIndex;

	            if (delRowFunction != null)
	            {
	            	//行削除時の前処理
	            	delRowFunction();
	            }

				if(sel>=0){
					if(itemEditorInstance && itemEditorInstance is TextInputEditor){
						var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
						if(editor.getValidator() != null){
							editor.getValidator().enabled = false;
						}
					}else if(itemEditorInstance && itemEditorInstance is DateFieldEditor){
						var dateEditor:DateFieldEditor = itemEditorInstance as DateFieldEditor;
						if(dateEditor.getValidator() != null){
							dateEditor.getValidator().enabled = false;
						}
					}
					if(this.dataProvider[sel].newFlg == 1){						
						this.dataProvider.removeItemAt(sel);
						if(sel>0){					
							//デフォルトの列ににフォーカスを移す
							editedItemPosition = {columnIndex: defaultColumn, rowIndex: sel - 1};
						}
					}else{
						this.dataProvider[sel].delFlg = 1;							
					}
				}

			}

			override public function rowValidate(event:KeyboardEvent):Boolean{
		    	if(editedItemPosition)
		    	{
			        var rowIndex:int = editedItemPosition.rowIndex;
			        var colIndex:int = editedItemPosition.columnIndex;
			        var parent:Object = event.currentTarget.parentDocument;
			        var resultEvent:ValidationResultEvent;
					if(itemEditorInstance && itemEditorInstance is TextInputEditor){
						var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
						if (editor.getValidator() != null && editor.getValidator().enabled == true){
							//データ検証結果
				            resultEvent = editor.getValidator().validate();
				            if (resultEvent.type == ValidationResultEvent.INVALID || this.dataProvider[rowIndex].errFlg == 1){
				            	if(resultEvent.results){
						            parent.lblErrMsg.text = columns[colIndex].headerText +"：" + resultEvent.message;
				            	}else{
				            		parent.lblErrMsg.text = this.dataProvider[rowIndex].errMsg;
				            	}
					        	event.preventDefault();
					        	return false;
							}else{
			            		parent.lblErrMsg.text = "";
							}
						}
					}else if(itemEditorInstance && itemEditorInstance is DateFieldEditor){
						var dateEditor:DateFieldEditor = itemEditorInstance as DateFieldEditor;
						if (dateEditor.getValidator() != null && dateEditor.getValidator().enabled == true){
							//データ検証結果
				            resultEvent = dateEditor.getValidator().validate();
				            if (resultEvent.type == ValidationResultEvent.INVALID || this.dataProvider[rowIndex].errFlg == 1){
				            	if(resultEvent.results){
						            parent.lblErrMsg.text = columns[colIndex].headerText +"：" + resultEvent.message;
				            	}else{
				            		parent.lblErrMsg.text = this.dataProvider[rowIndex].errMsg;
				            	}
					        	event.preventDefault();
					        	return false;
							}else{
			            		parent.lblErrMsg.text = "";
							}
						}
					}		    	
		    	}
		    	return true;
			}
			
		]]>
	</mx:Script>
</IlsDataGrid>
