
/*以下、各種設定画面の表示オブジェクト*/
var _ =function(){
	var constructorF = function(){
		var unCommitChange = false;
		var _this = this;
		var init = function(){
			//まずはカレントの表をクリアする。
			_disp.tblId = null;
			//続いて、サーバから、ソート一覧を取得する。
			_sysData._loadChain(["tbl","col","rlt"],{ db_id : _this.dbId }, disp )
		};
		var deleteTr = function( elmTr ){
			chgBtnEnable();
			_D.rC( elmTr );
		};
		var commit = function( ){
			_prcName_="COMMIT CHANGE";
			var reqValues = { db_id : _this.dbId };
			var allValue = getAllTrValues();
			for( var i = 0 ; _U.isIdx( i , allValue ) ; i ++ ){
				for( var key in allValue[i] ){
					if( key == "cols" )continue;
					reqValues[ key + "[" + i + "]" ] = allValue[i][ key ];
				};
				for( var j = 0 ; _U.isIdx( j , allValue[i].cols ) ; j ++ ){
					for( var key in allValue[i].cols[j] ){
						reqValues[ key + "[" + i + "]["+ j +"]" ] = allValue[i].cols[j][ key ];
					};
				};
			};
			_disp.request( "php/" + _urlMap.action.chgRrt , reqValues , init );
		};
		var chgBtnEnable = function(){
			_D.g( "rmng_rollback" ).disabled = false;
			_D.g( "rmng_commit" ).disabled = false;
		};
		var checkErr ={
			none:"none",
			d:"d",
			n:"n",
			allN:"allN"
		};
		var getAllTrValues = function(){
			var ret = [];
			for( var i = 0 ; _U.isIdx( i , tbody.children ) ; i++ ){
				ret.push( getRowValues( tbody.children[ i ] ) );
			};
			return ret;
		};
		var checkTrValue = function( tr ){
			var aryTrValues = getAllTrValues();
			var trIdx = _U.find( tr , tbody.children );
			var value = aryTrValues[ trIdx ];

			var blAllError = value.table1_id == "" && value.table2_id == "";
			var blNullError = value.table1_id == "" || value.table2_id == "";
			for( var i = 0 ; ( blAllError || ! blNullError ) && _U.isIdx( i , value.cols ) ; i ++ ){
				blNullError = blNullError || value.cols[ i ].table1_columns == "" || value.cols[ i ].table2_columns == "";
				blAllError = blAllError && value.cols[ i ].table1_columns == "" && value.cols[ i ].table2_columns == "";
			};
			if( blAllError ){
				return checkErr.allN;
			};
			if( blNullError ){
				return checkErr.n;
			};

			var DupError = false;

			for( var i = 0 ; ! DupError && _U.isIdx( i , aryTrValues ) ; i ++ ){
				if( i == trIdx )continue;
				var targVal = aryTrValues[ i ];
				var blSame = null;
				if( targVal.cols.length != value.cols.length )continue;
				if( value.table1_id == targVal.table1_id &&  value.table2_id == targVal.table2_id ){
					blSame = true;
				}else if( value.table1_id == targVal.table2_id &&  value.table2_id == targVal.table1_id ){
					blSame = false;
				};
				if( blSame == null )continue;

				var wkDupErr = true;

				for( var j = 0 ; wkDupErr && _U.isIdx( j , targVal.cols ) ; j ++ ){
					var colMatch = false;
					for( var k = 0 ; ! colMatch && _U.isIdx( k , value.cols ) ; k ++ ){
						if( blSame ){
							colMatch = (
								targVal.cols[ j ].table1_columns == value.cols[ k ].table1_columns &&
								targVal.cols[ j ].table2_columns == value.cols[ k ].table2_columns
							);
						}else{
							colMatch = (
								targVal.cols[ j ].table1_columns == value.cols[ k ].table2_columns &&
								targVal.cols[ j ].table2_columns == value.cols[ k ].table1_columns
							);
						};
					};
					if( ! colMatch ){
						wkDupErr = false;
					};
				};
				if( wkDupErr ){
					DupError = true;
				};
			};

			if( DupError ){
				return checkErr.d;
			};

			return checkErr.none;
		};


		var chgEdit = function( tr ){
			var blEdit = ( tr.dataset.edit != "true" );

			var noChange4del = false;

			if( ! blEdit ){
				var err = checkTrValue( tr );
				//エラーが無ければ･･･変更チェックを行い、変更があればrollback,commitの制御を行う。
				if( err != checkErr.none && err != checkErr.allN ){

					var msg = _msg.getMessage( "rltmng_W0" );
					var mainMsgObj =  msg.main ;
					mainMsgObj.discription = msg.sub[ err ];
					_disp.showMessage( mainMsgObj );
					return;
				};

				if( ! unCommitChange ){
					var trIdx = _U.find( tr , tbody.children );
					var rltTable = _sysData._getData("rlt" , _sysData._getMode.asWTable );
					var rltDt = rltTable[ trIdx ];
					if( ! rltDt ){
						unCommitChange = ( err == checkErr.none );
						noChange4del = ( err == checkErr.allN );
					}else{
						var value = getRowValues( tr );
						unCommitChange = (
							rltDt._children.length != value.cols.length ||
							rltDt.id != value.relation_id ||
							rltDt.cTable != value.table1_id ||
							rltDt.pTable != value.table2_id
						);
					};
				};
				if( ! noChange4del ){
					for( var i = 0 ; ! unCommitChange && _U.isIdx( i , value.cols ) ; i ++ ){
						unCommitChange = (
							rltDt._children[ i ].cCol  != value.cols[ i ].table1_columns ||
							rltDt._children[ i ].pCol  != value.cols[ i ].table2_columns ||
							rltDt._children[ i ].id  != value.cols[ i ].relation_col_id
						);
					};
				};
				//ここまでで変更チェック終わり
				if( unCommitChange ){
					//変更がある場合、rollbackとcommitボタンを有効にする。
					chgBtnEnable();
				}else{
				_D.g( "rmng_rollback" ).disabled = true;
				};
			}else{
				_D.g( "rmng_commit" ).disabled = true;
				//編集中はコミットは無効とする。
			};

			tr.dataset.edit = blEdit;
			_D.fEC( tr.children[ 0 ] ).disabled = ! blEdit;
			_D.fEC( tr.children[ 2 ] ).disabled = ! blEdit;

			for( var i = 0 ; _U.isIdx( i , tr.children[ 1 ].children ) ; i++ ){
				if( tr.children[ 1 ].children[ i ].tagName == "SELECT" ){
					tr.children[ 1 ].children[ i ].disabled = ! blEdit;
				};
			};
			for( var i = 0 ; _U.isIdx( i , tr.children[ 3 ].children ) ; i++ ){
				tr.children[ 3 ].children[ i ].disabled = ! blEdit;
			};
			if( blEdit ){
				_D.fEC( tr.children[ 4 ] ).value = "commit";
			}else{
				_D.fEC( tr.children[ 4 ] ).value = "edit";
			};
			_D.lEC( tr.children[ 4 ] ).disabled = blEdit;

			for( var i = 0 ; _U.isIdx( i , tbody.children ) ; i ++ ){
				var wkTr = tbody.children[i];
				if( wkTr == tr )continue;
				_D.fEC( wkTr.children[ 4 ] ).disabled = blEdit;
				_D.lEC( wkTr.children[ 4 ] ).disabled = blEdit;
			};

			_D.g("rmng_add").disabled = blEdit;

			if( err == checkErr.allN ){
				_D.rC( tr );
			};

		};

		//selectの値をnullにする。
		var setColValueNull = function( td ){
			for( var i = 0 ; _U.isIdx( i , td.children ) ; i ++ ){
				if( td.children[ i ].tagName == "SELECT" ){
					td.children[ i ].value =null;
				};
			};
		};


		var eventFuncs = {
			rollbackOnClick:function(){
				_disp.showMessageEz( "cmmn_101" , null , function(){_prcName_="ROLL BACK"; init();} );
			},
			commitOnClick:function(){
				_disp.showMessageEz( "cmmn_100" , null , commit );
			},
			deleteOnClick:function(){
				var tr = _D.par(_D.par(this));
				var sl1 = _D.fEC( _D.fEC( tr ) );
//				var t1 = sl1.options[ sl1.selectedIndex ].innerHTML;
				var t1 = sl1.options[ sl1.selectedIndex ].label;
				var sl2 = _D.fEC( tr.children[2] );
//				var t2 = sl2.options[ sl2.selectedIndex ].innerHTML;
				var t2 = sl2.options[ sl2.selectedIndex ].label;

				_disp.showMessageEz( "rltmng_0" , [ t1 , t2 ] , function(){ 
					deleteTr(tr);}
				);
			},
			addOnClick:function(){
				chgBtnEnable();
				var tr = addTr();
				_D.fEC( tr.children[ 4 ] ).onclick();
			},
			editOnClick:function(){
				chgEdit( _D.par( _D.par( this ) ) );
			},
			slctOnChange:function(){
				var tr = _D.par( _D.par( this ) );
				var idx = _U.find( _D.par( this ) , tr.children );
				//一部でbreakせずに処理している点に注意すること。
				switch( idx ){
					case 0 :
						//col1を差し替える。
						setColOps( tr.children[ 1 ] , _D.fEC( tr.children[ 0 ] ).value );
						//table2をクリアする。
						setColValueNull( tr.children[2] );
					case 2 :
						//col2を差し替える。
						setColOps( tr.children[ 3 ] , _D.fEC( tr.children[ 2 ] ).value );
						break;
					case 1 :
						var col2 = _D.g( this.dataset.c2 );
						var opt2 = col2.options[ col2.selectedIndex ];
						var opt = this.options[ this.selectedIndex ];
						if( opt2 && opt2.dataset.type != opt.dataset.type ){
							col2.value = null;
						};
						break;
				};
			},
			addColOnClick:function(){
				var cols = addCol( _D.par(_D.par( this ) ) );
				for( var key in cols ){
					cols[key].disabled = false;
				};
			},
			delColOnClick:function(){
				var br1 = _D.nx( this );
				var c1 = _D.prE( this );
				var c2 = _D.g( c1.dataset.c2 );
				var br2 = _D.nx( c2 );
				_D.rC( c1 );
				_D.rC( c2 );
				_D.rC( br1 );
				_D.rC( br2 );
				_D.rC( this );
			}
		}

		var nodeDef ={
			mainInner :{attr:{
				tagname:"div",
				className:"_vh_sc_auto_ _rmng_"
			},children:[
				{attr:{
					tagname:"h1",
					innerHTML:"Table Relations Setting",
					className:"_titles_"
				},children:[
					{attr:{
						tagname:"input",
						type:"button",
						value:"ROLLBACK CHANGES",
						disabled:true,
						id:"rmng_rollback",
						onclick:eventFuncs.rollbackOnClick,
						className:"_btn_y_ _btn_in_title_"
					}},{attr:{
						tagname:"input",
						type:"button",
						value:"COMMIT CHANGES",
						disabled:true,
						id:"rmng_commit",
						onclick:eventFuncs.commitOnClick,
						className:"_btn_y_ _btn_in_title_"
					}}
				]},{attr:{
					tagname:"table",
					id:"tbl_rmng"
				},children:[
					{attr:{
						tagname:"thead",
						id:"thead_rmng"
					},children:[
						{attr:{
							tagname:"tr",
							id:"tr_rmng_head"
						},children:[
							{attr:{
								tagname:"th",
								className : "_thead_w_r_",
								id:"th_rmng_table1_name"
							},children:[
								{attr:{
									tagname:"span",
									innerHTML:"Table1"
								}}
							]},{attr:{
								tagname:"th",
								className : "_thead_w_r_",
								id:"th_rmng_table1_cols"
							},children:[
								{attr:{
									tagname:"span",
									innerHTML:"Table1 Columns"
								}}
							]},{attr:{
								tagname:"th",
								className : "_thead_w_y_",
								id:"th_rmng_table2_name"
							},children:[
								{attr:{
									tagname:"span",
									innerHTML:"Table2"
								}}
							]},{attr:{
								tagname:"th",
								className : "_thead_w_y_",
								id:"th_rmng_table2_cols"
							},children:[
								{attr:{
									tagname:"span",
									innerHTML:"Table2 Columns"
								}}
							]},{attr:{
								tagname:"th",
								className : "_thead_g_",
								id:"th_rmng_act"
							},children:[
								{attr:{
									tagname:"span",
									innerHTML:"manage action"
								}}
							]}
						]}
					]},{attr:{
						tagname:"tbody",
						id:"tbody_rmng"
					}},{attr:{
						tagname:"tfoot",
						id:"tfoot_rmng"
					},children:[
						{attr:{
							tagname:"tr",
							id:"tr_rmng_foot"
						},children:[
							{attr:{
								tagname:"td",
								className:"_td_dmy_"
							}},{attr:{
								tagname:"td",
								colSpan:4
							},children:[
								{attr:{
									tagname:"input",
									type:"button",
									value:"add",
									id:"rmng_add",
									onclick:eventFuncs.addOnClick,
									className:"_btn_adjust_"
								}}
							]}
						]}
					]}
				]}
			]},
			tableTr :{attr:{
				tagname:"tr",
				className:"_rmng_tr_body_"
			},children:[
				{attr:{
					tagname:"td",
					className:"_rmng_td_table1_name_"
				}},{attr:{
					tagname:"td",
					className:"_rmng_td_table1_col_"
				},children:[
					{attr:{
						tagname:"input",
						type:"button",
						value:"add column",
						onclick : eventFuncs.addColOnClick,
						name:"_rmng_btn_col_add_",
						className:"_rmng_btn_col_add_"
					}}
				]},{attr:{
					tagname:"td",
					className:"_rmng_td_table2_name_"
				}},{attr:{
					tagname:"td",
					className:"_rmng_td_table2_col_"
				}},{attr:{
					tagname:"td",
					className:"_rmng_td_act_"
				},children:[
					{attr:{
						tagname:"input",
						type:"button",
						value:"edit",
						onclick : eventFuncs.editOnClick,
						className:"_rmng_btn_edit_ _btn_w_"
					}},
					{attr:{
						tagname:"input",
						type:"button",
						onclick : eventFuncs.deleteOnClick,
						value:"delete",
						className:"_rmng_btn_del_ _btn_y_"
					}}
				]}
			]},
			
			select:{attr:{
				tagname:"select",
				className:"_not_def_",
				onchange:eventFuncs.slctOnChange,
				disabled:true
			},children:[
				{attr:{
					tagname:"option"
				}}
			]},
			option:{attr:{
				tagname:"option"
			}},
			delBtn:{attr:{
				tagname:"input",
				type:"button",
				onclick : eventFuncs.delColOnClick,
				value:"del",
				className:"_rmng_btn_del_col_ _btn_y_"
			}}
		};

		var main = _D.g("main");
		this.init = init;
		var tbody;
		var _prcName_;

		var colTable;
		var tblTable ;
		var createTableSlct = function( targ , tid ){
			//ひとまず、SELECT作成
			return createSlctCommon( targ , tblTable , tid );
		};
		var getRowValues = function( tr ){
			var ret = {
				relation_id : tr.dataset.id,
				table1_id : _D.fEC( tr.children[ 0 ] ).value,
				table2_id : _D.fEC( tr.children[ 2 ] ).value,
				cols:[]
			};
			for( var i = 0 ; _U.isIdx( i , tr.children[ 1 ].children ) ; i ++ ){
				var c1 = tr.children[ 1 ].children[ i ];
				if( c1.tagName != "SELECT" )continue;
				var c2 = _D.g( c1.dataset.c2 );
				ret.cols.push( {
					relation_col_id : c1.dataset.id,
					table1_columns : c1.value,
					table2_columns : c2.value
				});
			};
			return ret;
		};

		var ngColIds = [];
		//col1,col2の重複チェック
		var checkSlctValue = function( elm ){
			ngColIds = [];
			var td = _D.par( elm );
			for( var i = 0 ; _U.isIdx( i , td.children ) ; i ++ ){
				if( td.children[ i ] == elm )continue;
				if( td.children[ i ].tagName != elm.tagName )continue;
				if( td.children[ i ].value == "" || td.children[ i ].value == null )continue;
				ngColIds.push( td.children[ i ].value )
			};
		};
		var typeTbl;
		var targType;
		//col2で利用する型チェック
		var checkCol1Type = function( elm ){
			var col1 = _D.g( elm.dataset.c1 );
			var opt1 = col1.options[ col1.selectedIndex ];
			if( opt1 ){
				targType = opt1.dataset.type;
			}else{
				targType = null;
			}
			return targType;
		};
		//実際にcol1,col2のオプションの操作可否を設定する。
		var setOptDisable = function( elm , bl ){
			for( var i = 0 ; _U.isIdx( i , elm.options ) ; i ++ ){
				var opt = elm.options[i];
				_D.show( opt , _U.find( opt.value , ngColIds ) == -1 && ( ! bl || opt.value == "" || opt.dataset.type == targType ) );
			};
		};
		//col1で選べる対象を設定する。
		var checkAndSetOptUse = function(){
			checkSlctValue( this );
			setOptDisable( this );
		};
		//col2で選べる対象を設定する。
		var checkAndSetOptUse2 = function(){
			checkSlctValue( this );
			checkCol1Type( this );
			setOptDisable( this , true );
		};

		var setColSlctOpt = function( slct , ary , isCol ){
			slct.innerHTML ="<option></option>"
			for( var i = 0 ; _U.isIdx( i , ary ) ; i ++ ){
				var opt = _D.aCAndCN( slct , nodeDef.option );
				opt.value = ary[ i ].id;
//				opt.innerHTML = ary[ i ].name;
				opt.label = ary[ i ].name;

				if( isCol ){
					var type = _sysData._tblFind( typeTbl , [{ key : "id" , value : ary[ i ].type }] , true )[ 0 ];
					opt.dataset.type = type.inner;
				};

			};

		};
		var createSlctCommon = function( targ , ary , id , isCol ){
			var ret = _D.aCAndCN( targ , nodeDef.select );
			setColSlctOpt( ret , ary , isCol );
			ret.value = id;
			return ret;
		}

		//optionの中身を差し替える
		var setColOps = function( td ,tid ){
			//ひとまず、SELECT作成
			var myCols = [];
			if( tid !== null &&  tid !== "" ){
				var myCols = _sysData._tblFind( colTable , [{ key : "tableId" , value : tid }] );
			};
			for( var i = 0 ; _U.isIdx( i , td.children ) ; i ++ ){
				if( td.children[ i ].tagName == "SELECT" ){
					setColSlctOpt( td.children[ i ] , myCols , true );
				};
			};

		};

		var createColSlct = function( targ , tid , cid ){
			//ひとまず、SELECT作成
			var myCols = [];
			if( tid !== null &&  tid !== "" ){
				var myCols = _sysData._tblFind( colTable , [{ key : "tableId" , value : tid }] );
			};
			var slct = createSlctCommon( targ , myCols , cid , true );
			slct.onfocus = checkAndSetOptUse;
			return slct;
		};

		//table2で、table1と同じ表を選ばせない処理
		var checkAndSetOptTable = function(){
			//ひとまず、table1のvalueを取得
			var t1Value = _D.fEC( _D.fEC( _D.par(_D.par( this ) ) ) ).value;

			for( var i = 0 ; _U.isIdx( i , this.options ) ; i ++ ){
				var opt = this.options[i];
				_D.show( opt , opt.value == "" || ( t1Value && opt.value != t1Value ) );
			};
		};

		var wkIdIdx = 0;
		var disp = function( ){
			unCommitChange = false;

			//ここまででエラーがあった場合は既に画面通知済みのはず。
			main.innerHTML = "";
			wkIdIdx = 0;

			//ひとまず、基本の画面要素作成
			_D.aCAndCN( main , nodeDef.mainInner );

			var rltTable = _sysData._getData("rlt" , _sysData._getMode.asWTable );
			colTable = _sysData._getData("col" );
			tblTable = _sysData._getData("tbl" );

			typeTbl = _sysData._getData( "type" );

			//tbodyにDB毎の要素を作成する。
			tbody = _D.g("tbody_rmng");
			for( var i = 0 ; _U.isIdx( i , rltTable ) ; i ++ ){
				addTr( rltTable[ i ]);
			};

			if( _prcName_ ){
				procFin();
			};
		};
		var procFin = function(){
			_disp.showMessageEz( "cmmn_10" , [_prcName_] , null );
			_prcName_ = null;
		};
		var addCol = function( tr , rltData ){

				if( ! rltData ){
					rltData ={
						id:null,
						cCol:null,
						pCol:null
					};
				};

				var tid1 = _D.fEC( tr.children[ 0 ] ).value;
				var tid2 = _D.fEC( tr.children[ 2 ] ).value;

				var c1 = createColSlct( tr.children[ 1 ] , tid1 , rltData.cCol );
				c1.id = "c1_" + wkIdIdx;
				if( rltData.id !== null ){
					c1.dataset.id = rltData.id;
				}else{
					c1.dataset.id = "";
				};
				c1.dataset.c2 = "c2_" + wkIdIdx;
				var c2 = createColSlct( tr.children[ 3 ] , tid2 , rltData.pCol );
				c2.onfocus = checkAndSetOptUse2;
				c2.dataset.c1 = c1.id;
				c2.id = c1.dataset.c2;
				wkIdIdx ++;

				var delBtn = _D.aCAndCN( tr.children[ 1 ] , nodeDef.delBtn );
				var br1 = _D.aCAndCN( tr.children[ 1 ] , {attr:{ tagname:"br" } } );
				var br2 = _D.aCAndCN( tr.children[ 3 ] , {attr:{ tagname:"br" } } );

				for( var elm = _D.lEC( tr.children[ 1 ] ) ; elm != null ; elm = _D.prE( elm ) ){
					if( elm.name == "_rmng_btn_col_add_" ){
						_D.aC( tr.children[ 1 ] , elm );
					};
				};
				return { col1:c1,col2:c2 };
		};
		var addTr = function( rltData ){
			if( ! rltData ){
				rltData = {
					id : null,
					cTable : null,
					pTable : null,
					_children:[{
						id:null,
						cCol:null,
						pCol:null
					}]
				}
			}

			

			var tr = _D.aCAndCN( tbody , nodeDef.tableTr );
			if( rltData.id !== null ){
				tr.dataset.id = rltData.id;
			}else{
				tr.dataset.id = "";
			};
			createTableSlct( tr.children[ 0 ] , rltData.cTable );
			createTableSlct( tr.children[ 2 ] , rltData.pTable ).onfocus = checkAndSetOptTable;

			for( var j = 0 ; _U.isIdx( j , rltData._children ) ; j ++ ){
				var cols = addCol( tr , rltData._children[ j ] );
				if( j == 0 ){
					_D.nxE( cols.col1 ).disabled = true;
				};
			};
			return tr;
		};
	};
	constructorF.prototype = _protoEachDisp;
	_eachDisp.RMng = new constructorF();
}();
delete _;
