/*
 Const Variables
*/
var jSelTLst;
var jDivTbl;
var jDivDisp;
var jDivJoin;

var outType_JOIN = 0;
var outType_DISP = 1;

/*
 Grobal Variables
*/
var init = true;

/*
 SystemId,Pgid and Local Variables ( needs initialize when SystemId or Pgid is changed
*/
var systemId;
var pgId;

var outType = -1;
var selJoinId = -1;

var handleAjaxError = function( XMLHttpRequest, textStatus, errorThrown ) {
	alert("Ajax処理中にエラーが発生しました。");
}

$(function(){
	jDivTLst = $("#divTableListArea");
	jDivTbl = $("#divTablesArea");
	jDivDisp = $("#divDispColumnsArea");
	jDivJoin = $("#divJoinColumnsArea");

	$("#divDispColumns").click( function(){
		selectOutDiv( outType_DISP );
	});
	$("#divJoinColumns").click( function(){
		selectOutDiv( outType_JOIN );
	});

	$("#newJoin").click( function(){
		selJoinId = -1;
		hilightJoinCols();
	});

	divColInitHeight = jDivDisp.height();
	divJoinInitHeight = jDivJoin.height();

	initialize();
});

function initialize() {
	init = true;

	systemId = $("#systemId").val();
	pgId = $("#pgId").val();

	showTableList();
	showDefs();

	selectOutDiv( outType_DISP );

	init = false;
}

function showTableList() {
	$.ajax({
		type		: "GET"
		,url		: "selectTableList.jsp"
		,data		: getParam()
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var jTbl = $( selTag2TblItem( msg, "tableId" ) );
				jTbl.find("div table td")
					.dblclick( function(){ selectTable( $(this).attr("tableId"), null ); });
				jDivTLst.append( jTbl );
			}
	});
}

function showDefs() {
	$.ajax({
		type		: "GET"
		,url		: "selectTableDefs.jsp"
		,data		: getParam()
		,dataType	: "text"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var data = responce2Json( msg );
				if( !data ) { return; }
				for( var i=0; i<data.length; i++ ) {
					selectTable( data[i]["tableId"], data[i]["asTable"], data[i]["seq"] );
				}
			}
	});

	$.ajax({
		type		: "GET"
		,url		: "selectDispColumnDefs.jsp"
		,data		: getParam()
		,dataType	: "text"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var data = responce2Json( msg );
				if( !data ) { return; }
				for( var i=0; i<data.length; i++ ) {
					if( data[i]["group"] == "RESULT" ) {
						selectDispColumn( data[i]["tableId"], data[i]["asTable"], data[i]["column"], data[i]["seq"] );
					}
					jDivDisp.find("div[asTable="+data[i]["asTable"]+"][column="+data[i]["column"]+"] *[group="+data[i]["group"]+"]").each( function(j) {
						var attr = $(this).attr("attrcol");
						if( data[i][attr] || ( $(this).attr("group") == "RESULT" && attr == "ZOKUSEI" ) ) {
							if( $(this).attr("type") == "checkbox" ) {
								if( data[i][attr] == "1" ) {
									$(this).attr("checked", "true" );
								}
							}
							else {
								$(this).val( data[i][attr] );
							}
						}
					});
				}
			}
	});

	$.ajax({
		type		: "GET"
		,url		: "selectJoinColumnDefs.jsp"
		,data		: getParam()
		,dataType	: "text"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var data = responce2Json( msg );
				if( !data ) { return; }
				for( var i=0; i<data.length; i++ ) {
					var joinId = data[i]["zokusei"].split("__")[0];
					var otherTableId = data[i]["zokusei"].split("__")[1];
					var otherAsTableColumn = data[i]["zokusei"].split("__")[2];
					if( data[i]["column"] != '**' ) {
						selectJoinColumn( data[i]["tableId"], data[i]["asTable"], data[i]["column"], joinId, data[i]["seq"] );
					}
					if( otherTableId ) {
						var otherAsTable = otherAsTableColumn.split(".")[0];
						var otherColumn = otherAsTableColumn.split(".")[1];
						selectJoinColumn( otherTableId, otherAsTable, otherColumn, joinId, data[i]["seq"] );
					}
				}
				var jFirstJoinDiv = jDivJoin.find("div");
				if( jFirstJoinDiv.length > 0 ) {
					selJoinId = jFirstJoinDiv[0].attr("joinId");
				}
				else {
					selJoinId = -1;
				}
			}
	});
}

function selectOutDiv( ot ) {
	if( ot != outType ) {
		outType = ot;
		if( outType == 0 ) {
			$("#divJoinColumns").removeClass("unselArea").addClass("selArea");
			$("#divDispColumns").removeClass("selArea").addClass("unselArea");
			hilightJoinCols();
		}
		else {
			$("#divDispColumns").removeClass("unselArea").addClass("selArea");
			$("#divJoinColumns").removeClass("selArea").addClass("unselArea");
			hilightDispCols();
		}
	}
}

function hilightDispCols() {
	jDivTbl.find(".selCol").removeClass("selCol");
	var jCols = jDivDisp.find(".divColumn");
	$.each( jCols, function(i) {
		var asTable = $(this).attr("asTable");
		var column = $(this).attr("column");
		jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").addClass("selCol");
	});

	jDivDisp.find(".ptitle").removeClass("unselTitle").addClass("selTitle");
	jDivJoin.find(".selTitle").removeClass("selTitle").addClass("unselTitle");
}

function hilightJoinCols() {
	jDivTbl.find(".selCol").removeClass("selCol");
	jDivDisp.find(".selTitle").removeClass("selTitle").addClass("unselTitle");
	jDivJoin.find(".selTitle").removeClass("selTitle").addClass("unselTitle");

	var joinId = selJoinId;

	var jJoinTbls = jDivJoin.find("div[joinId="+joinId+"] table[joinId="+joinId+"]");
	$.each( jJoinTbls, function(i) {
		var asTable = $(this).attr("asTable");
		var jCols = $(this).find("td");
		$.each( jCols, function(j) {
			var column = $(this).attr("column");
			jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").addClass("selCol");
		});
	});

	jDivJoin.find("div[joinId="+joinId+"]").find(".ptitle").removeClass("unselTitle").addClass("selTitle");
}

function selectTable( tableId, asTable, seq ) {
	$.ajax({
		type		: "GET"
		,url		: "selectTable.jsp"
		,data		: getParam( tableId, asTable, null, "execType: '0'", seq ) // 0:add
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var jTbl = $( selTag2TblItem( msg, "column" ) );
				jTbl.find("div table td")
					.dblclick( function(){ selectColumn( tableId, jTbl.attr("asTable"), $(this).attr("column" ) ); } );
				jTbl.find(".close")
					.click( function(){ unselTable( tableId, jTbl.attr("asTable") ); } );
				jDivTbl.append( jTbl );
			}
	});

	jDivTbl.sortable({
		items		: ".divTable"
		,stop		:
			function() {
				var orderList = "";
				var tbls = $(".divTable");
				$.each( tbls, function( idx ) {
					var seq = ( idx + 1 ) * 10;
					if( $(this).attr("seq") != seq ) {
						if( orderList != "" ) { orderList += ',' }
						orderList += $(this).attr("tableId") + "__" + $(this).attr("asTable") + "=" + seq;
						$(this).attr("seq",seq );
					};
				});

				if( orderList != "" ) {
					$.ajax({
						type		: "GET"
						,url		: "updateTableOrder.jsp"
						,data		: getParam( null, null, null, "orderList:'" + orderList + "'" )
						,dataType	: "html"
						,async		: true
						,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
						,error		: handleAjaxError
						,success	:
							function(msg){
							}
					});
				}
			}
	});

	jDivTLst.find("td[tableId="+tableId+"]").addClass("selCol");
}

function unselTable( tableId, asTable ) {
	$.ajax({
		type		: "GET"
		,url		: "selectTable.jsp"
		,data		: getParam( tableId, asTable, null, "execType: '9'" ) // 9:remove
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
	});

	jDivTbl.find("div[asTable="+asTable+"]").remove();
	jDivDisp.find("div[asTable="+asTable+"]").remove();
	jDivJoin.find("table[asTable="+asTable+"]").each( function(i){
		jDivJoin.find("div[joinId="+$(this).attr("joinId")+"]").remove();
	});

	if( jDivTbl.find("div[tableId="+tableId+"]").length == 0 ) {
		jDivTLst.find("td[tableId="+tableId+"]").removeClass("selCol");
	}
}

function selectColumn( tableId, asTable, column ) {
	if( outType == 0 ) {
		selectJoinColumn( tableId, asTable, column );
	}
	else {
		selectDispColumn( tableId, asTable, column );
	}
}

function selectDispColumn( tableId, asTable, column, seq ) {
	if( jDivDisp.find("div[asTable="+asTable+"][column="+column+"]").length > 0 ) {
		alret("この項目は既に選択されています。");
		return false;
	}

	$.ajax({
		type		: "GET"
		,url		: "selectDispColumn.jsp"
		,data		: getParam( tableId, asTable, column, "execType: '0'", seq ) // 0:add
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				var jCol = $(msg);
				jCol.find("input,select")
					.blur( function(){
						var val = null;
						if( $(this).attr("type") == "checkbox" ) {
							val = $(this).attr("checked") ? "1" : ""
						}
						else {
							val = $(this).val();
						}
						updateColumnAttr( tableId, asTable, column, $(this).attr("group"), $(this).attr("attrcol"), val )
					}); // To Live Event ??
				jCol.find(".close")
					.click( function(){ unselDispColumn( tableId, asTable, column ); } );
				jDivDisp.append( jCol );
			}
	});

	jDivDisp.sortable({
		items		: ".divColumn"
		,stop		:
			function() {
				var orderList = "";
				var cols = $(".divColumn");
				$.each( cols, function( idx ) {
					var seq = ( idx + 1 ) * 10;
					if( $(this).attr("seq") != seq ) {
						if( orderList != "" ) { orderList += ',' }
						orderList += $(this).attr("tableId") + "__" + $(this).attr("asTable") + "__" + $(this).attr("column") + "=" + seq;
						$(this).attr("seq",seq );
					};
				});

				if( orderList != "" ) {
					$.ajax({
						type		: "GET"
						,url		: "updateColumnOrder.jsp"
						,data		: getParam( null, null, null, "orderList:'" + orderList + "'" )
						,dataType	: "html"
						,async		: true
						,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
						,error		: handleAjaxError
						,success	:
							function(msg){
							}
					});
				}
			}
	});

	jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").addClass("selCol");
}

function unselDispColumn( tableId, asTable, column ) {
	$.ajax({
		type		: "GET"
		,url		: "selectDispColumn.jsp"
		,data		: getParam( tableId, asTable, column, "execType: '9'" ) // 9:remove
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
	});

	jDivDisp.find("div[asTable="+asTable+"][column="+column+"]").remove();
	jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").removeClass("selCol");
}

function selectJoinColumn( tableId, asTable, column, joinId, seq ) {
	var execType = -1 // 0:newDiv 1:newTable 2:newClm 9:remove

	var jJoin = null;
	var jTbl = null;

	var position = null;
	var otherTableId = null;
	var otherAsTable = null;
	var otherColumn = null;

	if( !joinId ) {
		joinId = selJoinId;
		if( joinId == -1 ) {
			joinId = (new Date()).getTime();
		}
	}

	jJoin = $("div[joinId="+joinId+"]");
	// create new join
	if( jJoin.length == 0 ) {
		execType = 0; // 0:newDiv
	}
	else {

		jTbl = jJoin.find("table[joinId="+joinId+"][asTable="+asTable+"]");
		if( jTbl.length == 0 && jJoin.find("table[joinId="+joinId+"]").length >= 2 ) {
			alert("3テーブル以上を1つのJOIN条件に定義することはできません。");
			return false;
		}
		else if( jTbl.find("td[column="+column+"]").length > 0 ) {
			alert("この項目は既に選択されています。");
			return false;
		}

		position = ( jTbl.length == 0 ? "right" : jTbl.parent().attr("position") );

		var thisColLen = jTbl.find("td").length;
		var otherPos = ( position == "left" ? "right" : "left" );
		var jOtherTbl = jJoin.find("td[position="+otherPos+"] table");
		var otherColLen = jOtherTbl.find("td").length;

		if( position == "right" && otherColLen <= thisColLen ) {
			alert("左側のテーブルから先に結合するカラムを登録して下さい。");
			return false;
		}

		otherTableId = jOtherTbl.attr("tableId");
		otherAsTable = jOtherTbl.attr("asTable");
		otherColumn = jOtherTbl.find("td:eq("+thisColLen+")").attr("column");

		if( !seq ) {
			seq = jOtherTbl.find("td:eq("+thisColLen+")").attr("seq");
		}

		if( thisColLen == 0 ) {
			execType = 1; // 1:newTable
		}
		else if( !otherColumn ) {
			execType = 2; // 2:newRow (left)
		}
		else {
			execType = 3; // 3;updateRow( right )
		}
	}

	$.ajax({
		type		: "GET"
		,url		: "selectJoinColumn.jsp"
		,data		: getParam( tableId, asTable, column,
						"joinId:'" + joinId + "',otherTableId:'" + otherTableId + "',otherAsTable:'" + otherAsTable
						+ "',otherColumn:'" + otherColumn + "',position:'" + position + "',execType:'" + execType + "'",
						seq )
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
				jRtn = $(msg);
				if( execType == 0 ) {
					jRtn.click( function() {
						selJoinId = joinId;
						hilightJoinCols();
					});
					jRtn.find(".close").click( function(){ removeJoin( joinId ); } );
					selJoinId = joinId;
					jDivJoin.append( jRtn );
					hilightJoinCols();

					jDivJoin.sortable({
						items		: ".divJoin"
						,handle		: ".ptitle"
						,stop		:
							function() {
								var orderList = "";
								var joins = $(".divJoin");
								$.each( joins, function( idx ) {
									var divseq = ( idx + 1 ) * 100;
									if( $(this).attr("seq") != divseq ) {
										var joinId = $(this).attr("joinId");
										var seqplus = divseq - parseInt( $(this).attr("seq") );

										var jTbl = $(this).find("td[position=left] table");
										var tableId = jTbl.attr("tableId");
										var asTable = jTbl.attr("asTable");
										var cols = jTbl.find("td");
										$.each( cols, function( idx ) {
											var colseq = parseInt( $(this).attr("seq") ) + seqplus;
											if( orderList != "" ) { orderList += ',' }
											orderList +=  tableId + "__" + asTable + "__" + $(this).attr("column") + "__" + joinId + "=" + colseq;
											$(this).attr("seq",colseq );
										});
										$(this).attr("seq",divseq );
									}
							});

							if( orderList != "" ) {
								$.ajax({
									type		: "GET"
									,url		: "updateJoinOrder.jsp"
									,data		: getParam( null, null, null, "orderList:'" + orderList + "'" )
									,dataType	: "html"
									,async		: true
									,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
									,error		: handleAjaxError
									,success	:
										function(msg){
										}
								});
							}
						}
					});
				}
				else if( execType == 1 ) {
					jJoin.find("td[position=right]").append( jRtn );
				}
				else if( execType == 2 || execType == 3 ) {
					jTbl.append( jRtn );
					jTbl.sortable({
						items:	 "tr"
						,stop	:
							function() {
								var tableId = $(this).attr("tableId");
								var asTable = $(this).attr("asTable");
								var joinId = $(this).attr("joinId");
								var position = $(this).parent().attr("position");
								var divSeq = $(this).parents("div[joinId="+joinId+"]").attr("seq");

								var orderList = "";
								var jTds = jTbl.find("td");
								jTds.each(function(idx){
									var seq = parseInt( divSeq ) + ( idx + 1 ) * 10;
									if( $(this).attr("seq") != seq ) {
										if( orderList != "" ) {
											orderList += ",";
										}
										orderList += seq + "=" + $(this).attr("column");
										$(this).attr("seq",seq );
									}
								});

								if( orderList != "" ) {
									$.ajax({
										type		: "GET"
										,url		: "updateJoinColOrder.jsp"
										,data		: getParam( tableId, asTable, null, "joinId:'" + joinId + "',position:'" + position + "',orderList:'" + orderList + "'" )
										,dataType	: "html"
										,async		: true
										,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
										,error		: handleAjaxError
										,success	:
											function(msg){
											}
									});
								}

							}
					});
				}
			}
	});

	jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").addClass("selCol");
}

function removeJoin( joinId ) {
	$.ajax({
		type		: "GET"
		,url		: "selectJoinColumn.jsp"
		,data		: getParam( null, null, null, "joinId: '" + joinId + "',execType: '9'" ) // 9:remove
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
	});

	jDivJoin.find("div[joinId="+joinId+"]").remove();
	selJoinId = -1;
	hilightJoinCols();
}

function updateColumnAttr( tableId, asTable, column, group, attrcol, value ) {
	$.ajax({
		type		: "GET"
		,url		: "updateColumnAttr.jsp"
		,data		: getParam( tableId, asTable, column, "group:'" + group + "',attrcol:'" + attrcol + "',value:'" + value + "'" )
		,dataType	: "html"
		,async		: false
		,contentType: "application/x-www-form-urlencoded; charset=UTF-8"
		,error		: handleAjaxError
		,success	:
			function(msg){
			}
	});
}

function getParam( tableId, asTable, column, etc, seq ) {
	var rtn = "{ init: '" + init + "', systemId: '" + systemId + "', pgId: '" + pgId + "'";
	if( tableId ) { rtn += ", tableId: '" + tableId + "', tableName : '" + getTableName( tableId ) + "'" }
	if( asTable ) { rtn += ", asTable: '" + asTable + "'" }
	if( column )  { rtn += ", column : '" + column  + "', columnName: '" + getColumnName( asTable, column ) + "'" }
	if( etc )     { rtn += ", " + etc }
	if( seq )     { rtn += ", seq: '" + seq + "'" }
	rtn += "}";
	return eval( "(" + rtn + ")" );
}

function getTableName( tableId ) {
	return jDivTLst.find("td[tableId="+tableId+"]").text();
}

function getColumnName( asTable, column ) {
	return jDivTbl.find("div[asTable="+asTable+"] td[column="+column+"]").text();
}

function selTag2TblItem( selTag, name ) {
	return selTag
			.replace(/<select[^>]*>/,"<div><table>")
			.replace("</select>","</table></div>")
			.replace(/<option value="(.*)" +>(.*)<\/option>/g,"<tr><td "+name+"=\"$1\" title=\"$2\">$2</tr></td>");
}

function responce2Json( response ) {
	return eval( "(" + response.match(/\[\{.*/) + ")" );
}

