<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
%>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<jsp:include page="/jsp/common/include/css.jsp"/>
        <style>
path, .jtk-endpoint {
    cursor: pointer;
}

.mouseover-endpoint path {
    stroke : blue;
    stroke-width : 6;
    z-index : 10;
}

.mouseover-endpoint circle {
    fill: blue;
    z-index : 1000;
}

.click-endpoint path {
    stroke : blue;
    stroke-width : 6
}

.click-endpoint circle {
    fill: blue;
}

.div-hover {
    background-color: #EDD5DD
}

    </style>
<jsp:include page="/jsp/common/include/script.jsp"/>
<script language="javascript" src="<c:url value="/js/jsplumb.js"/>"></script>
<script language="javascript">
var isDetail = false;

const LAYOUT_ITEM_TYPE_GROUP = "Group";
const LAYOUT_ITEM_TYPE_GRID = "Grid";
const LAYOUT_ITEM_TYPE_FIELD = "Field";

var srcGroup;
var tgtGroup;
var srcGrid ;
var tgtGrid ;
var url 	 = '<c:url value="/onl/admin/rule/transform2/transform2Man.json" />';
var url_view = '<c:url value="/onl/admin/rule/transform2/transform2Man.view" />';

var isAdmin = "";

var returnUrl = getReturnUrlForReturn();
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";

var selectName = "functionCombo"; // selectBox Name

var isContextMenuShow = false;

var srcMappingDatas;
var tgtMappingDatas;

var mappingDialog;
var mappingDialogParent;

var LIST_TRANSFORM_ITEM;
var LIST_LAYOUT_ITEM;

var isValidMapping = true;

$(document).mousemove(function (e) {
    $('html, body').scrollTop(function(i, v) {
       var h = $(window).height();
       if (e.clientY > 0 && h - e.clientY > 0) {
           return;
       }
        
       var y = e.clientY - h/2;
       var percent = v + y * 0.03;
       return percent;
    });
});

function getSourceResult(cnvsnName){
	
	console.log("start getSourceResult : " + cnvsnName);
	
    // 기존 Connection을 모두 삭제
    jsPlumbInstance.deleteEveryConnection();
    jsPlumbInstance.deleteEveryEndpoint();
	
	var LIST_TRANSFORM_SOURCE_RESULT = $.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd : 'LIST_TRANSFORM_SOURCE_RESULT', cnvsnName : cnvsnName},
	}); 
	
	LIST_TRANSFORM_SOURCE_RESULT.done(function (json) {
        var data = json.rows;
        var src = null;
        var tgt = null;;
        var srcDesc = null;
        var tgtDesc = null;
        var srcLoutIoId = null;
        var tgtLoutIoId = null;
        var srcLoutType = null;
        var tgtLoutType = null;
        for ( var i = 0; i < data.length; i++) {
            if (data[i]['SOURCRSULTDSTCD'] == 'SRC_LAYOUT' ){
                src = data[i]['LOUTNAME'];	
                srcDesc = data[i]['LOUTDESC'];
                $("input[name=srcLayout]").val(src);
                $("input[name=srcLayoutDesc]").val(srcDesc);
                srcLoutIoId = data[i]['LOUTIOID'];
                $("input[name=srcLoutIoId]").val(srcLoutIoId);
                srcLoutType = data[i]['LOUTTYPE'];
            }else if (data[i]['SOURCRSULTDSTCD'] == 'TGT_LAYOUT' ){
                tgt = data[i]['LOUTNAME'];
                tgtDesc = data[i]['LOUTDESC'];
                $("input[name=tgtLayout]").val(tgt);
                $("input[name=tgtLayoutDesc]").val(tgtDesc);
                tgtLoutIoId = data[i]['LOUTIOID'];
                $("input[name=tgtLoutIoId]").val(tgtLoutIoId);
                tgtLoutType = data[i]['LOUTTYPE'];
            }
        }
        
        confirmLastAmnDhms();
        
        LIST_TRANSFORM_ITEM = listTransformItem(tgt, cnvsnName, tgtLoutIoId, tgtLoutType, src);
        LIST_LAYOUT_ITEM = listLayoutItem(src, srcLoutIoId, srcLoutType);
        
        $.when(LIST_TRANSFORM_ITEM, LIST_LAYOUT_ITEM).then(function (json) {
                initialConnections(json[0].rows);
        });
        
        console.log('LIST_TRANSFORM_SOURCE_RESULT done');
	}).fail(function (e) {
        alert(e.responseText);
	});
	
	console.log("end getSourceResult : " + cnvsnName);
}

function confirmLastAmnDhms () {
    var reqCnvsnLastAmnDhms = parseLastAmnDhms($('#REQ').attr('lastAmnDhms'));
    var resCnvsnLastAmnDhms = parseLastAmnDhms($('#RES').attr('lastAmnDhms'));
    
    var tgtLastAmnDhms = parseLastAmnDhms($("#tgtLastAmnDhms").val());
    var srcLastAmnDhms = parseLastAmnDhms($("#srcLastAmnDhms").val());
    
    var message = "";
    if (reqCnvsnLastAmnDhms > 0 && (reqCnvsnLastAmnDhms < tgtLastAmnDhms || reqCnvsnLastAmnDhms < srcLastAmnDhms)) {
        message = "요청"
    }
    
    if (resCnvsnLastAmnDhms > 0 && (resCnvsnLastAmnDhms < tgtLastAmnDhms || resCnvsnLastAmnDhms < srcLastAmnDhms)) {
        if (message.length > 0) {
            message = message + ", 응답"
        } else {
            message = "응답"
        }
    }
    
    if (message.length > 0) {
        if (isValidMapping) {
            isValidMapping = false;
            // alert은 1회
            alert("입출력전문이 수정 되었습니다. "+ message +" 매핑정보를 확인 후 저장하시기 바랍니다.");
        }
        return false;
    }
    
    return true;
}

function parseLastAmnDhms(lastAmnDhms) {
    try {
        return parseInt(lastAmnDhms);
    } catch (e) {
        return 0;
    }
}

function listLayoutItem(srcLayoutName, srcLoutIoId, srcLoutType) {
    // console.error("start LIST_LAYOUT_ITEM : " + srcLayoutName);
    if (srcLayoutName == null) {
        return;
    }
    
    var LIST_LAYOUT_ITEM = $.ajax({  
        type : "POST",
        url:url,
        dataType:"json",
        data:{ cmd : 'LIST_LAYOUT_ITEM', loutName: srcLayoutName, loutIoId:srcLoutIoId, loutType:srcLoutType },
    });
    LIST_LAYOUT_ITEM = LIST_LAYOUT_ITEM.done(function (json) {
        var data = json.rows;
        $("#sourceLayout").get(0).addJSONData(data);
        
        srcGroup = new Object();
        srcMappingDatas = new Object();
        for ( var i = 0; i < data.length; i++) {
			var rowData = data[i];
			if (rowData["LOUTITEMPATH"].length > 0
					&& (rowData["loutItemType"] == LAYOUT_ITEM_TYPE_GRID)
			)  {
				srcGroup[data[i]["LOUTITEMPATH"]]= data[i]["LOUTITEMPATH"];
			}
            srcMappingDatas[getLoutItemPath(data[i]["LOUTITEMPATH"])] = data[i]['id'];
        }
        
        $("div[name^=src_]").each(function(){
            var source = $(this);
            var sourceObject = jsPlumbInstance.makeSource($(this),{
                 anchor:'Right'
            });
        });
        
        $('#sourceLayout .jqgrow').mouseover(function (e) {
            var rowId = $(this).attr('id');
            var endpointElement = $('#div_src_' + rowId);
            var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
            
            if (endpoints.length > 0) {
                mouseoverEndpoint(endpoints.get(0), 'mouseover-endpoint');
            }
            
            mouseoverJqgrid(rowId, 'targetLayout');
        }).mouseout(function (e) {
            var rowId = $(this).attr('id');
            var endpointElement = $('#div_src_' + rowId);
            var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
                
            if (endpoints.length > 0) {
                mouseoutEndpoint(endpoints.get(0), 'mouseover-endpoint');
            }
            mouseoutJqgrid(rowId, 'targetLayout');
        }).contextmenu(function (e) {
            console.log('contextmenu');
            e.preventDefault();
            $('#contextMenuDiv').attr('endpointElementId', 'div_src_' + $(this).attr('id'));
            $('#contextMenuDiv').attr('sourceOrTarget', 'source');
            $('#contextMenuDiv').contextMenu();
        });
        //console.error("end LIST_LAYOUT_ITEM : " + srcLayoutName);
    });
    return LIST_LAYOUT_ITEM;
}

function listTransformItem (tgtLayoutName, cnvsnName, tgtLoutIoId, tgtLoutType, srcLayoutName) {
    //console.error("start LIST_TRANSFORM_ITEM : " + cnvsnName);
    if (tgtLayoutName == null) {
        return;
    }
    
    var LIST_TRANSFORM_ITEM = $.ajax({
        type : "POST",
        url:url,
        dataType:"json",
        data:{ cmd : 'LIST_TRANSFORM_ITEM', loutName: tgtLayoutName, cnvsnName : cnvsnName, loutIoId:tgtLoutIoId, loutType:tgtLoutType, srcLayoutName:srcLayoutName },
    });
    
    LIST_TRANSFORM_ITEM = LIST_TRANSFORM_ITEM.done(function (json) {
        var data = json.rows;
        $("#targetLayout").get(0).addJSONData(data);
        
        tgtGroup = new Object();
		for ( var i = 0; i < data.length; i++) {
			var rowData = data[i];
			if (rowData["LOUTITEMPATH"].length > 0
					&& (rowData["loutItemType"] == LAYOUT_ITEM_TYPE_GRID)
			)  {
				tgtGroup[rowData["LOUTITEMPATH"]]= rowData["LOUTITEMPATH"];
			}
		}

        $("div[name^=tgt_]").each(function(){
            jsPlumbInstance.makeTarget($(this),{anchor:'Left' 
            });
        });
        
        mappingDialog.dialog('close');
        
        $('#targetLayout .jqgrow').mouseover(function (e) {
            var rowId = $(this).attr('id');
            var endpointElement = $('#div_tgt_' + rowId);
            var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
                
            mouseoverJqgrid(rowId, 'sourceLayout');
            if (endpoints.length > 0) {
                mouseoverEndpoint(endpoints.get(0), 'mouseover-endpoint');
            }
        }).mouseout(function (e) {
            var rowId = $(this).attr('id');
            var endpointElement = $('#div_tgt_' + rowId);
            var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
                
            mouseoutJqgrid(rowId, 'sourceLayout');
            if (endpoints.length > 0) {
                mouseoutEndpoint(endpoints.get(0), 'mouseover-endpoint');
            }
        }).contextmenu(function (e) {
            console.log('contextmenu');
            e.preventDefault();
            $('#contextMenuDiv').attr('endpointElementId', 'div_tgt_' + $(this).attr('id'));
            $('#contextMenuDiv').attr('sourceOrTarget', 'target');
            $('#contextMenuDiv').contextMenu();
        });
        
        if (json.isRemappingRequired != undefined && json.isRemappingRequired == true) {
            if (isValidMapping) {
                isValidMapping = false;
                // alert은 1회
                alert('매핑 정보가 올바르지 않습니다. 매핑정보를 확인 후 저장하시기 바랍니다.');
            }
        }
        
        console.log('isRemappingRequired : ' + json.isRemappingRequired);
        // console.error("end LIST_TRANSFORM_ITEM : " + cnvsnName);
        
    });
    return LIST_TRANSFORM_ITEM;
}


function addGroupTag(group,data){
    // group 일 경우 
	var result = data;
	var datas = data.split(".");
    var comp = datas[0];
    var arr = new Array();

	for(var i=1;i<datas.length;i++){
		comp = comp +"." +datas[i];
		if (group[comp] != undefined){
			//값이 있음
			arr.push(comp);
		}
	}
	for(var i=arr.length;i > 0;i--){
		var a =  arr.pop();
		result = result.substr(0,result.indexOf(a)+a.length) + "[*]"+ result.substring(result.indexOf(a)+a.length);
	}
	return result;
}

//변환명에 있는 서비스코드와 if서비스 코드 매칭
function validation(){
    if ($('input[name=cnvsnName]').val() == '') {
    	$('#dialog').dialog('open');
    	return false;
    }
	return true;
}

function initialConnection(rowData) {
    var cnvsnSrcItems = $.trim(rowData['CNVSNSRCITEMS']);
    console.log("CNVSNSRCITEMS");
    console.log(cnvsnSrcItems);
    
    if (cnvsnSrcItems != "") {
        var cnvsnSrcItems = cnvsnSrcItems.split(',');
        $.each(cnvsnSrcItems, function (k, srcItem) {
            var loutItemPath = getLoutItemPath(srcItem);
            console.log('initialConnection loutItemPath : ' + loutItemPath);
            
            const connectSourceDiv = "div_src_" + srcMappingDatas[loutItemPath];
            const connectTargetDiv = "div_tgt_" + rowData['id'];
            
            if ($('#' + connectSourceDiv).length == 0 || $('#' + connectTargetDiv).length == 0 ) {
                
                if (isValidMapping) {
                	isValidMapping = false;
                    // alert은 1회
                    alert('매핑 정보가 올바르지 않습니다. 매핑정보를 확인 후 저장하시기 바랍니다.');
                }
                
                jqGridOnConnectionDetached('', rowData['id'], '');
                
                // ConnectionDetached 후 매핑 정보를 설정 한다. 
                tgtGrid.jqGrid('setCell', rowData['id'], 'ISVALIDMAPPING', false);
                tgtGrid.jqGrid('setCell', rowData['id'], 'loutItemName', '', {color:'red'});
                isValidMapping = false;
                return;
            }
            tgtGrid.jqGrid('setCell', rowData['id'], 'ISVALIDMAPPING', true);
            jsPlumbConnect(connectSourceDiv, connectTargetDiv);
        });
    }
}

function asyncConnection(data) {
    // 100 개씩 잘라서 넣어 준다. 
    // 이렇게 넣으면 100개씩 화면에 그려주기 때문에 좀더 빠르게 뜬 것처럼 느껴진다.  
	setTimeout(function () {
	    for ( var j = 0; j < data.length; j++) {
	        // target row loop
	        var rowData = data[j];
	        console.log("start call connect div_tgt_" + rowData['id'])
	        initialConnection(rowData);
	        console.log("end call connect div_tgt_" + rowData['id']);
	    }
	}, 1000); 
    
}

function initialConnections(data) {
	console.log(data);
    if (data.length <= 100) {
        for ( var j = 0; j < data.length; j++) {
            // target row loop
            var rowData = data[j];
            console.log("start call connect div_tgt_" + rowData['id'])
            initialConnection(rowData);
            console.log("end call connect div_tgt_" + rowData['id']);
        }
    } else {
        do {
            var spliceData = data.splice(0, 99);
            asyncConnection(spliceData);
        } while (data.length > 0);
    }
}

function getLoutItemPath(loutitempath){
	loutitempath = loutitempath.replace(/[\[\*\]]/g,"");
	return loutitempath;
}

function initDialog() {
    $('#dialog').dialog({
        autoOpen : false,
        modal : true, 
        buttons : {
            "추가" : function () {
                var tab = $('#' + $("#createReqResSelect").val());
                
                var insertCnvsnType = $.ajax({  
                    type : "POST",
                    url:url,
                    dataType:"json",
                    data:{
                        cmd : 'INSERT_CNVSN_TYPE',
                        eaiSvcName: '${param.eaiSvcName}', 
                        cnvsnName : tab.attr('cnvsnName'), 
                        cnvsnDesc : tab.attr('cnvsnDesc')
                    }
                });
                insertCnvsnType.fail(function(e){
                    alert('error : ' + e.responseText);
                });
                insertCnvsnType.done(function (json) {
                    initTabs(tab);
                    $('#dialog').dialog("close");
                });
            },
            "취소" : function () {
                $('#dialog').dialog("close");
            },
        }, 
        open : function () {
            var tabs = $('#tabs ul li');
            
            var options = new Array();
            for (var i = 0; i < tabs.length; i++) {
                var tab = $(tabs[i]);
                var option = new Object();
                var nameText;
                if (tab.attr('id') == 'PLUS') {
                    continue;
                } else if (tab.attr('id') == 'REQ') {
                    nameText = '요청'
                } else if (tab.attr('id') == 'RES') {
                    nameText = '응답'
                } else if (tab.attr('id') == 'ERR') {
                    nameText = '에러'
                }
                
                if (!tab.is(':visible') && tab.attr('EXISTS') == 'false') {
                    option.CODE = tab.attr('id');
                    option.NAME = nameText;
                    options.push(option);
                }
            }
            
            $("#createReqResSelect").children('option').remove();
            new makeOptions("CODE","NAME").setObj($("#createReqResSelect"))
                .setData(options).setNoValueInclude(false).rendering();
        }
    });
}

function clearThisPage() {
    $("input[name=transformForEaiSvcNameCombo]").val('');
    $("input[name=cnvsnDesc]").val('');
    $("input[name=cnvsnTypeCombo]").val('');
    srcGrid.jqGrid('clearGridData');
    tgtGrid.jqGrid('clearGridData');
    $('input[name=srcLayout]').val('');
    $('input[name=srcLayoutDesc]').val('');
    $('input[name=tgtLayout]').val('');
    $('input[name=tgtLayoutDesc]').val('');
}

var jsPlumbInstance;
var transformRows;
jsPlumb.ready(function() {
    
    jsPlumbInstance = jsPlumb.getInstance({
        DragOptions: { cursor: 'pointer', zIndex: 2000 },
        PaintStyle : { stroke : "palevioletred", strokeWidth :4}, 
        HoverPaintStyle : { stroke:"blue", strokeWidth:6},
        EndpointStyle : { radius:8, fill:"palevioletred",  },
        EndpointHoverStyle : { radius:12, fill:"blue" },
        Connector : [ "Bezier", { curviness:50 } ],
        Container : "right_box", 
    });
    
    jsPlumbInstance.batch(batchJsPlumbInstance);
    
    mappingDialog = $('#mappingDialog').dialog({
        autoOpen : false,
        modal : false, 
        buttons : {
            "저장" : mappingDialogSave,
            "닫기" : function () {
                mappingDialog.dialog('close');
            }, 
        },
        beforeClose : mappingDialogBeforeClose
    });
    mappingDialogParent = mappingDialog.parent('.ui-dialog');
    
	var verInfo = "${param.verInfo}";
	if (verInfo == "" || verInfo == "null") {
		verInfo = "0";
	}
	
	$("input[name=verInfo]").val(verInfo);
	
	var key = '${param.eaiSvcName}';
    if (key != "" && key != "null") {
        isDetail = true;
    }
	
	//combo
	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd : 'LIST_INIT_COMBO', eaiSvcName: '${param.eaiSvcName}'},
		success:function(json){
			isAdmin = json.isAdmin;
			var interfaceMap = json.interfaceMap;
			transformRows = json.transformRows;
			//eaiSvcName combo
			$("input[name=eaiSvcName]").val('${param.eaiSvcName }');
			$("input[name=eaiSvcDesc]").val('${param.eaiSvcDesc }');
			//$("input[name=cnvsnDesc]").val('${param.cnvsnDesc }');

			new makeOptions("CODE","NAME").setObj($("#functionCombo")).setData(json.functionRows).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("transformManDetail.none")%>").setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("#functionComboDialog")).setData(json.functionRows).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("transformManDetail.none")%>").setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("#transformForEaiSvcNameCombo")).setData(transformRows).setFormat(codeOptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("#eaiSevrDStcd")).setData(json.svrDstcd).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("#useYn")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();
			
			$("select[name=useYn]").val('${param.useYn }');
			$("select[name=eaiSevrDStcd]").val('${param.eaiSevrDStcd }').attr("disabled",true);
			
			// dialog 구성
            initDialog();
			
            reloadSourceTargetGrid('${param.cnvsnName}');
            reloadCnvsnDesc();
            
		},
		error:function(e){
			alert(e.responseText);
		}
	}); 

	srcGrid = $("#sourceLayout");
	srcGrid.jqGrid({
	    datatype:'json',
	    loadui: "disable",
	    mtype: 'POST',
	    colNames: [
	    	"id",
	    	'<%=localeMessage.getString("tran2ManDt.engNm")%>',
	    	'<%=localeMessage.getString("tran2ManDt.korNm")%>',
	    	'<%=localeMessage.getString("transformManDetail.num")%>',
	    	'<%=localeMessage.getString("tran2ManDt.itTp")%>',
	    	'<%=localeMessage.getString("tran2ManDt.dtTp")%>',
	    	"->",
	    	"LOUTITEMNODEPTRNIDDESC",
	    	"LOUTITEMPTRNIDNAME",
	    	"LOUTITEMPATH",
	    	"LOUTNAME",
	    	"LOUTITEMMAXOCCURNOITM",
	    	"LOUTITEMREFINFO2",
	    	],
		colModel: [
			{name: "id"                     , hidden:true,key:true},
			{name: "loutItemName"           , width:"150"},
			{name: "loutItemDesc"                      },
			{name: "loutItemSerno"          , width:"20", align : 'center' },
			{name: "loutItemType" , width:"35"},
			{name: "loutItemDataType"     , width:"40"},
			{name: "CONNECT"                , width:"17", align : 'center', unformat : srcunformatterFunction, formatter: srcformatterFunction},
			{name: "loutItemType" , hidden:true},
			{name: "loutItemDataType"     , hidden:true},
			{name: "LOUTITEMPATH"           , hidden:true},
			{name: "loutName"               , hidden:true},
			{name: "loutItemOccCnt"  , hidden:true},
			{name: "loutItemOccRef"       , hidden:true}
		],
	    treeGrid: true,
	    treeGridModel: "adjacency",
	    ExpandColumn: "loutItemName",
	    height:"100%",
	    width: "660",
	    rowNum: 10000,
	    treeIcons: {leaf:'ui-icon-document-b'},
	    jsonReader: {
	        repeatitems: false
	    },
        loadError: function (jqXHR, textStatus, errorThrown) {
        	 if(jqXHR.status == 401) {
 	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
 	                    '에러:  세션이 종료되었습니다. ');
 	    		parent.location.href='<%=request.getContextPath()%>/';	
 	    	}
	    }
	});
	
	tgtGrid = $("#targetLayout");
	tgtGrid.jqGrid({
		//url: '<c:url value="/iim/transform/transformMan.json" />',
		//postData : { cmd : 'LAYOUT_ITEM', loutName: 'LAC_BBSA311_ORGS'},			    
	    datatype:'json',
	    loadui: "disable",
	    mtype: 'POST',
	    colNames: [
	    	"id",
	    	"<-",
            '<%=localeMessage.getString("tran2ManDt.tgetItem")%>',
            '<%=localeMessage.getString("tran2ManDt.tgetItemDesc")%>',
            '<%=localeMessage.getString("transformManDetail.num")%>',
            '<%=localeMessage.getString("tran2ManDt.itTp")%>',
            '<%=localeMessage.getString("tran2ManDt.dtTp")%>',
	    	"LOUTITEMNODEPTRNIDDESC",
	    	"LOUTITEMPTRNIDNAME",
	    	"LOUTITEMPATH",
	    	"LOUTNAME",
	    	"CNVSNNAME",
	    	"CNVSNRSULTITEMPATHNAME" ,
	    	'<%=localeMessage.getString("transformManDetail.transCmdName")%>',
	    	"CNVSNITEMBASCVAL",
	    	"CNVSNITEMSERNO",
	    	"CNVSNSRCITEMS",
	    	"ISVALIDMAPPING"
	              ],
		colModel: [
			{name: "id"                     , hidden:true,key:true},
			{name: "CONNECT"                , width:"20", align : 'center' , unformat : tgtunformatterFunction, formatter: tgtformatterFunction},
			{name: "loutItemName"           , width:"100" },
			{name: "loutItemDesc"           , width:"100"},
			{name: "loutItemSerno"          , width:"20", align : 'center' },
			{name: "loutItemType" , width:"35" },
			{name: "loutItemDataType"     , width:"40" },

			{name: "loutItemType" , hidden:true},
			{name: "loutItemDataType"     , hidden:true},
			{name: "LOUTITEMPATH"           , hidden:true},
			{name: "loutName"               , hidden:true},

			{name: "CNVSNNAME"              , hidden:true}, //변환 명
			{name: "CNVSNRSULTITEMPATHNAME" , hidden:true}, //타겟 항목명
			{name: "CNVSNCMDNAME"           }, //변환 명령
			{name: "CNVSNITEMBASCVAL"       , hidden:true}, //기본값
			{name: "CNVSNITEMSERNO"         , hidden:true},  //매핑순서
			{name: "CNVSNSRCITEMS"          , hidden:true},
			{name: "ISVALIDMAPPING"         , hidden:true}
		],
	    treeGrid: true,
		treeIcons : {
			plus: "ui-icon-circlesmall-plus",
			minus: "ui-icon-circlesmall-minus",
			leaf : "ui-icon-document"
		},		    
	    treeGridModel: "adjacency",
	    ExpandColumn: "loutItemName",
	    height:"100%",
	    width: "860",
	    rowNum: 10000,
	    //ExpandColClick: true,
	    treeIcons: {leaf:'ui-icon-document-b'},
	    jsonReader: {
	        repeatitems: false
	    },
        loadError: function (jqXHR, textStatus, errorThrown) {
            if(jqXHR.status == 401) {
               alert('HTTP status code: ' + jqXHR.status + '\n' +
                       '에러:  세션이 종료되었습니다. ');
               parent.location.href='<%=request.getContextPath()%>/';
           }
       }
	});
	
	$("input[name=auto]").click(function(){
		
	    jsPlumbInstance.deleteEveryConnection();
		
	    var sourceData = srcGrid.getRowData();
	    var targetData = tgtGrid.getRowData();

		var selectValue = "";
		var targetValue = "";
		for ( var i = 0; i < sourceData.length; i++) {
			if (sourceData[i]['loutItemType'] != "Field" && sourceData[i]['loutItemType'] != "Attr") continue;
			selectValue = (sourceData[i]['LOUTITEMPATH']).substr(sourceData[i]['loutName'].length+1);
			for (var j = 0; j <targetData.length; j++) {
				if (targetData[j]['loutItemType'] != "Field" && targetData[j]['loutItemType'] != "Attr") continue;
				targetValue = (targetData[j]['LOUTITEMPATH']).substr(targetData[j]['loutName'].length+1);
				if (targetValue == selectValue ) {
					var data = sourceData[i]['LOUTITEMPATH'];
					var tgtRowId = targetData[j]['id'];
					
					var cnvsnCmdName = addGroupTag(srcGroup,data);
					
					// function까지 처리되도록 수정했으나, parameter가 하나인 경우에만 정상처리됨
					if($('#functionCombo').val() != "") { 
					    cnvsnCmdName = $('#functionCombo').val() + "(" + cnvsnCmdName + ")";
					}
					
					tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNCMDNAME',cnvsnCmdName);
					
					tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNRSULTITEMPATHNAME',addGroupTag(tgtGroup,targetData[j]['LOUTITEMPATH']));
					tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNITEMSERNO',targetData[j]['loutItemSerno']);
					
					try {
						jsPlumbConnect("div_src_" + sourceData[i]['id'], "div_tgt_" + tgtRowId);
					} catch (e) {console.log(e);}
					break;
				}
			}
		}
	});

	$("input[name=addAll]").click(function() {
	    console.log('addAll');
	 	var srcRowId = srcGrid.getGridParam( "selrow" );
	 	var tgtRowId = tgtGrid.getGridParam( "selrow" );
	 	if (srcRowId == null) {alert('<%=localeMessage.getString("transformManDetail.alert1")%>');return;}
	 	if (tgtRowId == null) {alert('<%=localeMessage.getString("transformManDetail.alert2")%>');return;}
	 	
	 	
	 	//field, ATTR 여부 판단
	 	var sourceRow = srcGrid.getRowData( srcRowId );
	 	var targetRow = tgtGrid.getRowData( tgtRowId );
		if ( (sourceRow["loutItemType"] == 'Field' || sourceRow["loutItemType"] == 'Attr') &&
				(targetRow["loutItemType"] == 'Field' || targetRow["loutItemType"] == 'Attr')  ){
	 		;
	 	}else{
	 		alert('<%=localeMessage.getString("transformManDetail.alert3")%>');
	 		return ;
		}	 	
	 	//grid data
	    var sourceData = srcGrid.getRowData();
	    var targetData = tgtGrid.getRowData();
	 	
	 	
	 	//grid index
		var srcIndex = srcGrid.jqGrid('getInd',srcRowId);
		var tgtIndex = tgtGrid.jqGrid('getInd',tgtRowId);

	 	
	 	var selectValue = "";
		var targetValue = "";
		var j=tgtIndex-1-1;
		for ( var i = srcIndex-1; i < sourceData.length; i++) {
			if (sourceData[i]['loutItemType'] != LAYOUT_ITEM_TYPE_FIELD) continue;
			j++;
			while (targetData.length -1 >= j &&targetData[j]["loutItemType"] != LAYOUT_ITEM_TYPE_FIELD){
				j++;
			}
			if (targetData.length -1 < j) break;
			var rowId = targetData[j]['id'];
			
			var cnvsnCmdName = addGroupTag(srcGroup,sourceData[i]['LOUTITEMPATH']);
			
            // function까지 처리되도록 수정했으나, parameter가 하나인 경우에만 정상처리됨
            if($('#functionCombo').val() != "") { 
                cnvsnCmdName = $('#functionCombo').val() + "(" + cnvsnCmdName + ")";
            }
            
			tgtGrid.jqGrid('setCell',rowId,'CNVSNCMDNAME', cnvsnCmdName);
			tgtGrid.jqGrid('setCell',rowId,'CNVSNRSULTITEMPATHNAME',addGroupTag(tgtGroup,targetData[j]['LOUTITEMPATH']));
			tgtGrid.jqGrid('setCell',rowId,'CNVSNITEMSERNO',targetData[j]['loutItemSerno']);
			
            jsPlumbInstance.deleteConnectionsForElement(document.getElementById("div_src_" + sourceData[i]['id']));
            jsPlumbInstance.deleteConnectionsForElement(document.getElementById("div_tgt_" + rowId));
			
			jsPlumbConnect("div_src_" + sourceData[i]['id'], "div_tgt_" + rowId);
	 	}
	});

	$("input[name=removeAll]").click(function(){
		
	 	var tgtRowId = tgtGrid.getGridParam( "selrow" );
	 	if (tgtRowId == null) {alert('<%=localeMessage.getString("transformManDetail.alert2")%>');return;}
		//grid data
		var targetData = tgtGrid.getRowData();
		//grid index
		var tgtIndex = tgtGrid.jqGrid('getInd',tgtRowId);

		for ( var i = tgtIndex-1; i < targetData.length; i++) {
			var rowId = targetData[i]['id'];
			tgtGrid.jqGrid('setCell',rowId,'CNVSNCMDNAME',null);
			tgtGrid.jqGrid('setCell',rowId,'CNVSNRSULTITEMPATHNAME',null);
		 	tgtGrid.jqGrid('setCell',rowId,'CNVSNITEMSERNO',null);
		 	tgtGrid.jqGrid('setCell',rowId,'CNVSNITEMBASCVAL',null);
		 	
		 	jsPlumbInstance.deleteConnectionsForElement(document.getElementById("div_tgt_" + rowId));
		}
	});	

	$("textarea[name=CNVSNRSULTITEMPATHNAME],textarea[name=CNVSNCMDNAME],input[name=CNVSNITEMBASCVAL],input[name=CNVSNITEMSERNO]").blur(function(){
		var rowId = tgtGrid.getGridParam( "selrow" );
		if (isNull(rowId)) return;
	});	

	$("#btn_close").click(function() {
		isValidMapping = true;
		if (confirmLastAmnDhms()) {
			window.close();	
		}
	});	
	
	$("#btn_previous").click(function(){
		goNav(returnUrl);//LIST로 이동
	});	
	
	$("#btn_modify").click(function(){
		
		var cmd;
		if (isDetail) {
			cmd = "UPDATE";
		} else {
			cmd = "INSERT";
		}
		
		//disabled 해제
		$("select[name=eaiSevrDStcd]").attr("disabled",false);
		
		if(!validation()) return;
		
	    var targetData = tgtGrid.getRowData();
		var gridData                = new Array();
		for (var i = 0; i <targetData.length; i++) {
			if ((targetData[i]['loutItemType'] != "Field")) continue;
			if (targetData[i]['CNVSNCMDNAME']==null 
					|| targetData[i]['CNVSNCMDNAME']== undefined 
					|| targetData[i]['CNVSNCMDNAME'].trim() =="" 
					) continue;
			
			gridData.push(tgtGrid.jqGrid('getRowData', targetData[i]['id']));
			
		}
		var postData = [];
		postData.push({ name: "cmd"           , value:cmd});
		postData.push({ name: "cnvsnName"     , value:$("#transformForEaiSvcNameCombo").val()});
		postData.push({ name: "cnvsnDesc"     , value:$("input[name=cnvsnDesc]").val()});
		postData.push({ name: "cnvsnType"     , value:$("input[name=cnvsnTypeCombo]").val()});
		postData.push({ name: "eaiSevrDStcd"  , value:$("select[name=eaiSevrDStcd]").val()});
		postData.push({ name: "chkForce"      , value:$("input:checkbox[name=chk_eaiSvcName]").is(":checked")});
		postData.push({ name: "srcLayoutName" , value:$("input[name=srcLayout]").val()});
		postData.push({ name: "tgtLayoutName" , value:$("input[name=tgtLayout]").val()});
		postData.push({ name: "useYn" 		  , value:$("select[name=useYn]").val()});
		postData.push({ name: "verInfo" 	  , value:$("input[name=verInfo]").val()});
		postData.push({ name: "gridData"      , value:JSON.stringify(gridData)});
		postData.push({ name: "eaiSvcName"      	  , value:$("input[name=eaiSvcName]").val()});
		$("#ajax_wait_modal").show();
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				$("#ajax_wait_modal").hide();
				alert('<%=localeMessage.getString("common.saveMsg")%>');
				
				var transform = args;
				
				var lastAmnDhms = transform['LASTAMNDHMS'];
                $('#cnvsnlastAmnDhms').val(transform['LASTAMNDHMS']);
                $("#displayCnvsnlastAmnDhms").val(formatDate(transform['LASTAMNDHMS']));
                
                var cnvsnType = $("input[name=cnvsnTypeCombo]").val();
                $('#' + cnvsnType).attr('lastAmnDhms', lastAmnDhms);
			},
			error:function(e){
				$("#ajax_wait_modal").hide();
				alert(e.responseText);
			}
		});
	});

	$("input[name=addCmd]").click(function(){
		var rowId = tgtGrid.getGridParam( "selrow" );
		var targetRow = "";
		var cnvsnCmdName = "";
		
		if (isNull(rowId)){
			alert('<%=localeMessage.getString("transformManDetail.alert4")%>');
			return;
		}
		
		targetRow = tgtGrid.getRowData( rowId );	// 타겟 그리드에서 선택된 ROW 값
		rowId = srcGrid.getGridParam( "selrow" );
		if (isNull(rowId)){
			alert('<%=localeMessage.getString("transformManDetail.alert5")%>');
			return;
		}
		
	});	
	
	$("#btn_initialize").click(function(){
		$.ajax({  
			type : "POST",
			url:url,
			dataType:"json",
			data:{cmd: 'INITIALIZE',cnvsnName:$("input[name=transformForEaiSvcNameCombo]").val()},
			success:function(json){
				alert(json.message);
			},
			error:function(e){
				alert(e.responseText);
			}
		});		
		
	});
	
	buttonControl();
	// setBtnHide(roleString, "admin", "btn_initialize");
});

function srcformatterFunction(cellvalue,options,rowObject){
	var rowId = options["rowId"];
	var loutItemType = rowObject["loutItemType"];
	if (loutItemType == 'Field' || loutItemType == 'Attr'){
		return "<div id='div_src_"+rowId+"' name='src_"+rowId+"' style='width:28px;height:17px;background-color: #D12F35; border-color: #ab1717; border-style: solid; border-width: 1px; border-radius: 3px;' />";
	}else{
		return "";
	}
}
function srcunformatterFunction(cellvalue,options, rowObject){
	return cellvalue;
}
function tgtformatterFunction(cellvalue,options,rowObject){
	var rowId = options["rowId"];
	var loutItemType = rowObject["loutItemType"];
	if (loutItemType == 'Field' || loutItemType == 'Attr'){
		return "<div id='div_tgt_"+rowId+"_base' name='div_tgt_"+rowId+"_base' style='width:30px;height:20px; background-color:gray;' >"
				+ "<div id='div_tgt_"+rowId+"' name='tgt_"+rowId+"' style='width:28px;height:17px; background-color: #3E7E9C;  border-color: #217ca7; border-style: solid; border-width: 1px; border-radius: 3px;' onclick='jqGridOnTargetGridEndpointClick(this)'>"
				+ "</div></div>";
	}else{
		return "";
	}
}
function tgtunformatterFunction(cellvalue,options, rowObject){
	return cellvalue;
}

function batchJsPlumbInstance() {
    
    $(window).on('resize',function(){
        jsPlumbInstance.repaintEverything();
        
        if (mappingDialog.dialog('isOpen')) {
            moveDialogPosition(false);
        }
    });
    
    $(window).scroll(function(){
         if (mappingDialog.dialog('isOpen')) {
             moveDialogPosition(true);
         }
    });
    
    jsPlumbInstance.bind("endpointClick", jsPlumbOnEndpointClick);
    jsPlumbInstance.bind("connection", jsPlumbOnConnection);
    jsPlumbInstance.bind("connectionDetached", jsPlumbOnConnectionDetached);
    jsPlumbInstance.bind("connectionMoved", jsPlumbOnConnectionMoved);
    jsPlumbInstance.bind("beforeDrop", jsPlumbOnBeforeDrop);
    jsPlumbInstance.bind("connectionDrag", jsPlumbOnConnectionDrag);
    jsPlumbInstance.bind("connectionDragStop", jsPlumbOnConnectionDragStop);
    
}

function jsPlumbOnConnectionDrag(conn) {
    console.log('connectionDrag');
    console.log(conn);
    
    var sourceJqgridRowId = conn.sourceId.substring(8);
    
    var sourceJqgridTrId = sourceJqgridRowId;
    // var targetJqgridTrId = sourceJqgridTrId.replace(/[0-9]+$/, ""); for eims
    var targetJqgridTrId = sourceJqgridTrId;
    
    var endpoints = conn.endpoints;
    if (endpoints.length > 0) {
        mouseoverEndpoint(endpoints[0], 'mouseover-endpoint');
    }
    
    $("#sourceLayout tr[id="+sourceJqgridTrId+"]").addClass('ui-state-hover');
    $("#targetLayout tr[id*="+targetJqgridTrId+"]").filter(function (index) {
        // return this.id.replace(/[0-9]+$/, "") == targetJqgridTrId; for eims
    	return this.id == targetJqgridTrId;
    }).addClass('div-hover');
    
}

function jsPlumbOnConnectionDragStop(conn) {
    
    var sourceJqgridRowId = conn.sourceId.substring(8);
    
    var sourceJqgridTrId = sourceJqgridRowId;
    // var targetJqgridTrId = sourceJqgridTrId.replace(/[0-9]+$/, ""); for eims
    var targetJqgridTrId = sourceJqgridTrId;
    
    var endpoints = conn.endpoints;
    if (endpoints.length > 0) {
        mouseoutEndpoint(endpoints[0], 'mouseover-endpoint');
    }
    
    $("#sourceLayout tr[id="+sourceJqgridTrId+"]").removeClass('ui-state-hover');
    $("#targetLayout tr[id*="+targetJqgridTrId+"]").filter(function (index) {
        // return this.id.replace(/[0-9]+$/, "") == targetJqgridTrId; for eims
        return this.id == targetJqgridTrId;
    }).removeClass('div-hover');
}

function jsPlumbOnBeforeDrop(info) {
    console.log('jsPlumbOnBeforeDrop');
    var connections = jsPlumbInstance.getConnections({source:info.sourceId, target:info.targetId});
    
    console.log(info);
    console.log(connections)
    
    var isConnected = false;
    
    if (connections.length == 0) {
        return true;
    }
    
    $.each(connections, function (i, conn) {
        // connection id가 다른 connection이 존재 한다. 
        if (conn.id != info.connection.id && !conn.isSuspendEvents()) {
            isConnected = true;
            return false;
        }
    });
    
    if (isConnected) {
        alert('동일한 매핑이 존재 합니다.');
    }
    
    // 기존의 연결이 존재 할 경우 연결을 
    var isConnectionAborted = !isConnected;
    return isConnectionAborted;
}

function jsPlumbOnEndpointClick (endpoint, originalEvent) {
    console.log('jsPlumbOnEndpointClick');
    openFunctionDialog(endpoint);
}

function jqGridOnEndpointClick (endpointElement) {
    var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
    console.log(endpoints);
    if (endpoints.length > 0) {
        openFunctionDialog(endpoints.get(0));
    }
}

function openFunctionDialog(endpoint) {
    if (!jsPlumbInstance.isTarget(endpoint.getElement())) {
        return;
    }
    
    if (!mappingDialog.dialog('isOpen')) {
        var targetRowId = endpoint.elementId.substring(8);
        
        console.log("id : " + endpoint.elementId);
        setDialogValues(targetRowId);
        
        mappingDialog.dialog({
            width:$('#targetLayoutTd').width() * 0.9, 
            open : function () {
                console.log('dialog open');
                
                $('#functionComboDialog').val($('#functionCombo').val());
                
                mouseoverEndpoint(endpoint, 'click-endpoint');
                moveDialogPosition(false);
            },
            drag : function () {
                console.log('dialog drag');
                moveDialogEndpointPosition();
            }, 
            close : function () {
                console.log('dialog close');
                returnDialogEndpointPosition(endpoint);
                return;
            }
        }).dialog('open');
    }
}

function mappingDialogSave() {
    var targetRowId = $('#targetRowId').val();
    console.log('targetRowId : ' + targetRowId);
    tgtGrid.jqGrid('setCell',targetRowId,'CNVSNRSULTITEMPATHNAME',$('textarea[name=CNVSNRSULTITEMPATHNAME]').val());
    tgtGrid.jqGrid('setCell',targetRowId,'CNVSNCMDNAME',$('textarea[name=CNVSNCMDNAME]').val());
    tgtGrid.jqGrid('setCell',targetRowId,'CNVSNITEMBASCVAL',$('input[name=CNVSNITEMBASCVAL]').val() == "" ? null : $('input[name=CNVSNITEMBASCVAL]').val());
    tgtGrid.jqGrid('setCell',targetRowId,'CNVSNITEMSERNO',$('input[name=CNVSNITEMSERNO]').val());
    
    mappingDialog.dialog('close');
}

function mappingDialogBeforeClose() {
    console.log('mappingDialogBeforeClose')
    // 사용하지 않는 변환 전 항목 체크
    var targetRowId = $('#targetRowId').val();
    var targetRowData = tgtGrid.getRowData(targetRowId);
    
    var cnvsnCmdName = targetRowData['CNVSNCMDNAME'];
    var cnvsnSrcItems = $.trim(targetRowData['CNVSNSRCITEMS']).split(',');
    
    console.log('targetRowId : ' + targetRowId);
    console.log('cnvsnCmdName : ' + cnvsnCmdName);
    console.log('cnvsnSrcItems : ' + cnvsnSrcItems);
    
    for (var i = 0; i < cnvsnSrcItems.length; i++) {
        var srcItem = cnvsnSrcItems[i];
        if (cnvsnCmdName != undefined && cnvsnCmdName.indexOf(srcItem) == -1) {
            alert('사용하지 않는 변환 전 항목이 존재합니다.');
            return true; 
        }
    }
    
    return true;
}

function mappingDialogCancle() {
    // dialog 열기 전 상태로 cancle
    var targetRowId = $('#targetRowId').val();
    var targetRowData = tgtGrid.getRowData(targetRowId);
    
    tgtGrid.jqGrid('setCell', targetRowId, 'CNVSNCMDNAME', $('#cancleCnvsnCmdName').val());
    tgtGrid.jqGrid('setCell', targetRowId, 'CNVSNSRCITEMS', $('#cancleSrcItems').val());
    
    mappingDialog.dialog('close');
}

function mouseoverEndpoint(endpoint, cssClass) {
    console.log('mouseoverEndpoint');
    var sourceElementId = jsPlumbInstance.isSource(endpoint.element) ? endpoint.elementId : '';
    var targetElementId = jsPlumbInstance.isTarget(endpoint.element) ? endpoint.elementId : '';
    
    var filter = {source:sourceElementId, target:targetElementId};
    
    var endpointConnection = jsPlumbInstance.getConnections(filter);
    
    $.each(endpointConnection, function(i, conn) {
        conn.addClass(cssClass);
        $.each(conn.endpoints, function (j, endpoint) {
            endpoint.addClass(cssClass)            
        });
    });
}

function mouseoutEndpoint(endpoint, cssClass) {
    console.log('mouseoutEndpoint');
    
    if (isContextMenuShow) {
        return;
    }
    
    var sourceElementId = jsPlumbInstance.isSource(endpoint.element) ? endpoint.elementId : '';
    var targetElementId = jsPlumbInstance.isTarget(endpoint.element) ? endpoint.elementId : '';
    
    var filter = {source:sourceElementId, target:targetElementId};
    
    var endpointConnection = jsPlumbInstance.getConnections(filter);
    
    $.each(endpointConnection, function(i, conn) {
        conn.removeClass(cssClass);
        $.each(conn.endpoints, function (j, endpoint) {
            endpoint.removeClass(cssClass)            
        });
    });
}

function mouseoverJqgrid(jqgridRowId, gridTableId) {
    console.log('mouseoverJqgrid');
    console.log(jqgridRowId);
    console.log(gridTableId);
    //var rowId = jqgridRowId.replace(/[0-9]+$/, ""); for eims
    var rowId = jqgridRowId;
    $("#"+gridTableId+" tr[id*="+rowId+"]").filter(function (index) {
        //console.log(this.id.replace(/[0-9]+$/, "")) for eims
        console.log(this.id)
        console.log(rowId)
        //return this.id.replace(/[0-9]+$/, "") == rowId; for eims
        return this.id == rowId;
    }).addClass('div-hover');
}

function mouseoutJqgrid(jqgridRowId, gridTableId) {
    console.log('mouseoutJqgrid');
    if (!isContextMenuShow) {
        // context menu 가 열려 있을 경우 
        console.log(jqgridRowId);
        //var rowId = jqgridRowId.replace(/[0-9]+$/, "");
        var rowId = jqgridRowId;
        $("#"+gridTableId+" tr[id*="+rowId+"]").filter(function (index) {
            // return this.id.replace(/[0-9]+$/, "") == rowId; for eims
        	return this.id == rowId;
        }).removeClass('div-hover');
    }
}


function jsPlumbOnConnection (info, originalEvent) {
    console.log("jsPlumbOnConnection start");
    
    $.each(info.connection.endpoints, function (index, endpoint) {
        // mouseover event bind
        endpoint.bind('mouseover', function () {
            mouseoverEndpoint(endpoint, 'mouseover-endpoint');
        });
        // mouseout event bind
        endpoint.bind('mouseout', function () {
            mouseoutEndpoint(endpoint, 'mouseover-endpoint');
        });
        
        // dialog 가 열려있을 때 connection 연결 connection style 적용 한다. 
        if (mappingDialog.dialog('isOpen') 
                && jsPlumbInstance.isTarget(endpoint.element)
                && endpoint.elementId.substring(8) == $('#targetRowId').val()) {
            
            mouseoverEndpoint(endpoint, 'click-endpoint');
        }
    });
    
    var sourceId = info.sourceId.substring(8);
    var targetId = info.targetId.substring(8);
    var targetConnections = jsPlumbInstance.getConnections({target:info.targetId});
    
    var sourceIds = $.map(targetConnections, function(conn) {
        return conn.sourceId.substring(8);
    })
    
    jqGridOnConnection(sourceId, targetId, sourceIds);
}

function jsPlumbOnConnectionDetached (info, originalEvent) {
    console.log("jsPlumbOnConnectionDetached start");
    var targetConnections = jsPlumbInstance.getConnections({target:info.targetId})
    if (targetConnections != null) {
        var targetRowId = info.targetId.substring(8);
        var sourceRowId = info.sourceId.substring(8);
        
        var sourceIds = $.map(targetConnections, function(conn) {
            if (conn.sourceId == info.sourceId) {
                return;
            } else {
                return conn.sourceId.substring(8);
            }
        });
        
        jqGridOnConnectionDetached(sourceRowId, targetRowId, sourceIds);
    }
}

function jsPlumbOnConnectionMoved (info, originalEvent) {
    console.log("connectionMoved start");
    var originalTargetConnections = jsPlumbInstance.getConnections({target:info.originalTargetId});
    
    var originalSourceId = info.originalSourceId.substring(8);
    var originalTargetId = info.originalTargetId.substring(8);
    
    var originalSourceIds = $.map(originalTargetConnections, function(conn) {
        return conn.sourceId.substring(8);
    });
    
    // 변경 전 타겟의 소스 정보 수정
    jqGridOnConnectionDetached(originalSourceId, originalTargetId, originalSourceIds);
    
};

function setDialogValues(targetRowId) {
    var rowData = tgtGrid.getRowData(targetRowId); 
    $('textarea[name=CNVSNRSULTITEMPATHNAME]').val(rowData['CNVSNRSULTITEMPATHNAME']);//
    $('textarea[name=CNVSNCMDNAME]').val(rowData['CNVSNCMDNAME']);
    $('input[name=CNVSNITEMBASCVAL]').val(rowData['CNVSNITEMBASCVAL']);
    $('input[name=CNVSNITEMSERNO]').val(rowData['CNVSNITEMSERNO']);
    
    // dialog open 시 cancle 정보 입력
    // var targetRowData = tgtGrid.getRowData(targetRowId);
    
    if (!mappingDialog.dialog('isOpen')) {
        $('#targetRowId').val(targetRowId);
        $('#cancleCnvsnCmdName').val(rowData['CNVSNCMDNAME']);
        $('#cancleSrcItems').val(rowData['CNVSNSRCITEMS']);
    }
    
    updateSourceItem(targetRowId);
}

function updateSourceItem(targetRowId) {
    console.log('updateSourceItem');

    var targetRowData = tgtGrid.getRowData(targetRowId); 
    var cnvsnSrcItems = $.trim(targetRowData['CNVSNSRCITEMS']).split(',');
    
    $('#mappingDialog table tr').each(function () {
        var thisTr = $(this);
        if (thisTr.attr('isSrcItem') == 'true') {
            console.log('updateSourceItem remove : ' + this);
            thisTr.remove();
        }
    });
    
    // table row 추가
    
    $.each(cnvsnSrcItems, function (index, srcLoutItemPath) {
        if (srcLoutItemPath == '') {
            return;
        }
        
        var row = '<tr isSrcItem="true"><th style="width:130px;">변환 전 항목</th><td>' 
            + srcLoutItemPath 
            + ' <input type="button" onclick="addSrcLoutItemPath( \'' 
                    + srcLoutItemPath + '\', \'' 
                    + targetRowId + '\' )" class="btn_img btn_pop_add" /> '
            +'</td></tr>';
        console.log('updateSourceItem addItemBeforeTr : ' + srcLoutItemPath);
        $('#addItemBeforeTr').before(row);
    });
}

function addSrcLoutItemPath (srcLoutItemPath, targetRowId) {
    console.log('addSrcLoutItemPath');
    var cnvsnCmdName = srcLoutItemPath;
    var targetRowData = tgtGrid.getRowData(targetRowId);    // 타겟 그리드에서 선택된 ROW 값
    
	if($('#functionComboDialog').val() != "") {
	    cnvsnCmdName = $('#functionComboDialog').val() + "(" + cnvsnCmdName + ")";
	} 

	$('textarea[name=CNVSNCMDNAME]').val($('textarea[name=CNVSNCMDNAME]').val() + ' ' +  cnvsnCmdName);
	$('textarea[name=CNVSNRSULTITEMPATHNAME]').val(addGroupTag(tgtGroup,targetRowData["LOUTITEMPATH"]));
	$('input[name=CNVSNITEMSERNO]').val(targetRowData['loutItemSerno']);
	   
	// setTgtCell();
}

function moveDialogPosition(isScroll) {
    console.log('moveDialogPosition : ' + isScroll);
    if (!mappingDialog.dialog('isOpen')) {
        console.log('dialog closed');
        return;
    }
    
    var autoOffset = $('#auto').offset();
    // scroll 한 값
    var winY = window.pageYOffset;
    
    mappingDialogParent.css('position', "absolute");
    // scroll 한 만큼 추가로 내려 준다
    mappingDialogParent.css('top', autoOffset.top + 40 + winY);
    if (!isScroll) {
      // scroll 할 때는 좌우 포지션은 변경 하지 않는다. 
      mappingDialogParent.css('left', autoOffset.left + 40);
    }
    
    moveDialogEndpointPosition();
}

function moveDialogEndpointPosition() {
    var targetEndpointDiv = $("#div_tgt_" + $('#targetRowId').val());
    
    mappingDialogParent.before(targetEndpointDiv);
    
    targetEndpointDiv.css({width:'20px', height:'20px' });
    targetEndpointDiv.position({
        my : 'right', at : 'left', of:mappingDialogParent
    });

    jsPlumbInstance.revalidate(targetEndpointDiv.attr('id'));
}

function returnDialogEndpointPosition(endpoint) {
    var targetEndpointDiv = $('#' + endpoint.elementId);
    $('#' + endpoint.elementId + "_base").append(targetEndpointDiv);
    
    mouseoutEndpoint(endpoint, 'click-endpoint');
    mouseoutEndpoint(endpoint, 'mouseover-endpoint');
    
    targetEndpointDiv.css({position:'relative', top:'', left:'', width:'100%', height:'100%' });
    jsPlumbInstance.revalidate(endpoint.elementId);
} 

function jsPlumbConnect(src, tgt) {
	var connection = jsPlumbInstance.connect({
	    source:src, 
	    target:tgt, 
    });
}

function jqGridOnConnection(newSourceRowId, tgtRowId, srcRowIds) {
    console.log('jqGridOnConnection');
    console.log('newSourceRowId : ' + newSourceRowId);
    console.log('tgtRowId : ' + tgtRowId);
    console.log('srcRowIds : ' + srcRowIds);
    
    if (newSourceRowId == undefined || srcRowIds.length == 0) {
        // 연결 정보가 없음
        tgtGrid.jqGrid('setCell', tgtRowId,'CNVSNCMDNAME',null);
        tgtGrid.jqGrid('setCell', tgtRowId,'CNVSNRSULTITEMPATHNAME',null);
        tgtGrid.jqGrid('setCell', tgtRowId,'CNVSNITEMSERNO',null);
        tgtGrid.jqGrid('setCell', tgtRowId,'CNVSNITEMBASCVAL',null);
        tgtGrid.jqGrid('setCell', tgtRowId,'CNVSNSRCITEMS', null);
        
        setDialogValues(tgtRowId);
        updateSourceItem(tgtRowId);
        return;
    }
    
 	//field, ATTR 여부 판단
 	var sourceRow = srcGrid.getRowData( newSourceRowId );
 	var targetRow = tgtGrid.getRowData( tgtRowId );
 	
 	if (sourceRow["LOUTITEMNODEPTRNIDDESC"] == undefined) {
 	    // tab을 변경 했을 경우 source row가 존재 하지 않을 수 있다.
 	    return;
 	}
 	
 	if (sourceRow["LOUTITEMNODEPTRNIDDESC"] != 'FIELD' || targetRow["LOUTITEMNODEPTRNIDDESC"] != 'FIELD') {
        alert('<%=localeMessage.getString("transformManDetail.alert3")%>');
        return ;
 	}
 	
 	var cnvsnSrcItems = $.map(srcRowIds, function (rowId) {
 	   var rowData = srcGrid.getRowData(rowId);
 	   return addGroupTag(srcGroup, rowData["LOUTITEMPATH"]);
 	});
 	
    console.log(targetRow['CNVSNCMDNAME'] == '');
    
 	if (targetRow['CNVSNCMDNAME'] == '') {
 	    // 변환 명령 값이 한번 설정 되면 변경 되지 않게 함.
 	    var cnvsnCmdName = addGroupTag(srcGroup,sourceRow["LOUTITEMPATH"]);
 	    // function까지 처리되도록 수정했으나, parameter가 하나인 경우에만 정상처리됨
        if($('#functionCombo').val() != "") { 
            cnvsnCmdName = $('#functionCombo').val() + "(" + cnvsnCmdName + ")";
        }
 	    
 	   tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNCMDNAME', cnvsnCmdName);
 	}
 	
 	tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNRSULTITEMPATHNAME',addGroupTag(tgtGroup,targetRow["LOUTITEMPATH"]));
	tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNITEMSERNO',targetRow['loutItemSerno']);
	tgtGrid.jqGrid('setCell',tgtRowId,'CNVSNSRCITEMS', cnvsnSrcItems);
	tgtGrid.jqGrid('setCell',tgtRowId,'ISVALIDMAPPING', true);
	
 	// dialog 가 열려있을 때 connection 연결
    if (mappingDialog.dialog('isOpen')) {
        setDialogValues(tgtRowId);
    }
}

function jqGridOnConnectionDetached(detachedSourceRowId, tgtRowId, srcRowIds) {
    console.log('jqGridOnConnectionDetached');
    console.log('srcRowIds : ' + srcRowIds);
    console.log('detachedSourceRowId : ' + detachedSourceRowId);
    
    jqGridOnConnection(srcRowIds[0], tgtRowId, srcRowIds);
}

function reloadSourceTargetGrid(cnvsnName) {
	
	var conversionName = cnvsnName;
	
	if(conversionName == undefined) {
		conversionName = $("#transformForEaiSvcNameCombo").val();
	} else {
		$("#transformForEaiSvcNameCombo").val(cnvsnName).prop("selected", true);
	}
	
	getSourceResult(conversionName);
}

$(document).ready(function () {
    
    var createItems = function (endpointElementId, sourceOrTarget) {

        var otherGrid = sourceOrTarget == 'source' ? srcGrid : tgtGrid;
        var otherGridId = sourceOrTarget == 'source' ? 'targetLayout' : 'sourceLayout';
        var sourceElementId = sourceOrTarget == 'source' ? endpointElementId : '';
        var targetElementId = sourceOrTarget == 'target' ? endpointElementId : '';
        var filter = {source:sourceElementId, target:targetElementId};
        var endpointConnections = jsPlumbInstance.getConnections(filter);
        
        var items = {
                connectByName : {
                    name : "(+)같은이름으로 매핑", 
                    callback : function () {
                        // 같은 이름의로 연결을 시도
                        console.log('connectByName : ' + endpointElementId);
                        // var rowId = endpointElementId.substring(8).replace(/[0-9]+$/, ""); for eims
                        var rowId = endpointElementId.substring(8);
                        
                        var otherRowId = $("#"+otherGridId+" tr[id*="+rowId+"]").filter(function (index) {
                            // return this.id.replace(/[0-9]+$/, "") == rowId; for eims
                        	return this.id == rowId;
                        }).first().attr('id');
                        
                        console.log('otherRowId : ' + otherRowId);
                        
                        var connectSourceDiv;
                        var connecttargetDiv;
                        
                        if (sourceOrTarget == 'source') {
                            connectSourceDiv = endpointElementId;
                            connecttargetDiv = "div_tgt_" + otherRowId;
                        } else {
                            connectSourceDiv = "div_src_" + otherRowId;
                            connecttargetDiv = endpointElementId;
                        }
                        
                        // 연결이 존재 하는 지 확인 
                        if (jsPlumbInstance.getConnections({source:connectSourceDiv, target:connecttargetDiv}).length > 0) {
                            alert('동일한 매핑이 존재 합니다.');
                            return;
                        }
                        
                        if ($('#' + connectSourceDiv).length == 0 || $('#' + connecttargetDiv).length == 0 ) {
                            alert('동일한 항목이 존재 하지 않습니다.');
                            return;
                        }
                        
                        jsPlumbConnect(connectSourceDiv, connecttargetDiv);
                    }
                }, 
                sep1 : "----------------",
            };
        
        var sortedItems = [];
        $.each(endpointConnections, function(i, conn) {
            var otherEndpointId;
            var _otherGrid;
            if (sourceOrTarget == 'source') {
                otherEndpointId = conn.targetId;
                _otherGrid = tgtGrid;
            } else {
                otherEndpointId = conn.sourceId;
                _otherGrid = srcGrid;
            }
            
            var otherRowId = otherEndpointId.substring(8);
            var rowData = _otherGrid.getRowData(otherRowId);
            
            var item = {
	            rowId : otherRowId,
	            name : '(-)' + rowData['loutItemName'],
	            order : rowData['loutItemSerno'],
	            callback : function () {
	                // 매핑을 삭제
	                jsPlumbInstance.deleteConnection(conn);
                }
            };
            
            sortedItems.push(item);
        });
        
        sortedItems = sortedItems.sort(function (itemA, itemB) {
           return itemA.order - itemB.order; 
        });
        
        $.each(sortedItems, function(i, item) {
           items[item.rowId] = item;
           console.log(item.rowId + '=' + item.order);
        });
        
	    return items;
    }

    $.contextMenu({
        selector : '#contextMenuDiv',
        trigger : 'none',
        build: function ($trigger, e) {
            console.log('build');
            
            var endpointElementId = $trigger.attr('endpointElementId');
            var sourceOrTarget =  $trigger.attr('sourceOrTarget');
            var endpointRowId = endpointElementId.substring(8);
            var endpointElement = $('#' + endpointElementId);
            var endpoints = jsPlumbInstance.selectEndpoints({element:endpointElement});
            var otherGrid;
            var my;
            var at;
            if (sourceOrTarget == 'source') {
                my = 'left';
                at = 'right';
                otherGrid = 'targetLayout';
            } else if (sourceOrTarget == 'target') {
                my = 'right';
                at = 'left';
                otherGrid = 'sourceLayout';
            }
            
            var options = {
                    callback : function (key, options) {
                    },
            };
            var items = createItems(endpointElementId, sourceOrTarget);
            options.items = items;
            options.determinePosition = function ($menu) {
                $menu.position({my: my, at: at, of:$('#' + endpointElementId)});
            };
            options.events = {
                show : function () {
                    console.log('show');
                    isContextMenuShow = true;
                }, 
                hide : function () {
                    console.log('hide');
                    isContextMenuShow = false;
                    
                    if (endpoints.length > 0) {
                     mouseoutJqgrid(endpointRowId, otherGrid);
                     mouseoutEndpoint(endpoints.get(0), 'mouseover-endpoint');
                    }
                }
            }
            return options;
        }
    });
    
    $("#transformForEaiSvcNameCombo").change(function() {
    	reloadSourceTargetGrid();
    });
    
    $("#btn_searchSrcLout").click(function(){
		layoutListPop("srcLayout", "srcLayoutDesc", srcGrid);
	});
	$("#btn_searchTgtLout").click(function(){
		layoutListPop("tgtLayout", "tgtLayoutDesc", tgtGrid);
	});
	
	$("input[name=srcLayout],[name=tgtLayout]").dblclick(function(){
		//debugger;
		var layoutName = $(this).val();
		if($.trim(layoutName) =="") return;

		var args = new Object();
		var url = '<c:url value="/onl/admin/rule/layoutMan.view" />';
		url += "?cmd=DETAILPOPUP";
        url += '&loutName='+layoutName;
        url += '&pop=true';
	    
	    showModal2(url,args,890,940,'','scroll:on'); 
	});
	
	$("#btn_close").click(function(){
		window.close();
	});
	
});

	function layoutListPop(loutName, loutDesc, gridObj) {
		
		var key = "";
		var args = new Object();
	    args['loutName'] = $('input[name=' + loutName + ']').val();
	    args['selLoutName'] = loutName;
		var urlLayout = url_view;
	    urlLayout = urlLayout + "?cmd=LAYOUT";
	
	    var result = showModal(urlLayout,args,800,708, function(arg){
	    	var args = null;
	        if(arg == null || arg == undefined ) {//chrome
	            args = this.dialogArguments;
	            args.returnValue = this.returnValue;
	        } else {//ie
	            args = arg;
	        }
	        
	        if( !args || !args.returnValue ) return;
	        
	        var result = args.returnValue;
	        
	        if( result ) {
	        	$("input[name=" + loutName + "]").val(result.key);
	        	$("input[name=" + loutDesc + "]").val(result.loutDesc);
	        	
	        	gridObj.setGridParam( {url :url ,postData: { cmd : 'LIST_LAYOUT_ITEM', loutName: result.key } }).trigger("reloadGrid");
	        }
	    	
	    });
	}
	
	function reloadCnvsnDesc() {
		var selectedCnvsnCode = $("#transformForEaiSvcNameCombo option:selected").val();
		var cnvsnObj = transformRows.find(function (rows) {
			return rows.CODE == selectedCnvsnCode;
		});
		console.log(cnvsnObj);
		$("#cnvsnDesc").val(cnvsnObj.NAME);
	}
	
	</script>
</head>
	<body>
		<div class="right_box" id="right_box">
			<div class="popup_scrollbox" id="dropArea" style="width: 98%;">
				<div class="search_wrap">
					<!-- <img src="<c:url value="/img/btn_modify.png"/>" alt="" id="btn_modify" level="W" status="DETAIL,NEW" />  -->				
					<!-- <img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW" />  -->
<%-- 					<img src="<c:url value="/img/btn_close.png"/>" alt="" id="btn_close" level="R" /> --%>
					<button type="button" class="cssbtn" id="btn_close" level="R" status="DETAIL,NEW" style="min-width:75px;"><i class="material-icons">close</i> <%= localeMessage.getString("button.close") %></button>
				</div>
				<div class="title"><%=localeMessage.getString("tran2ManDt.title")%></div>
				<input type="hidden" name="cnvsnTypeCombo">
				<table class="search_condition" cellspacing="0">
				<!-- 
					<tr>
						<th style="width:180px;">인터페이스ID</th>
						<td style="width: *">
							<input type="text" name="eaiSvcName" style="width:100%;" readonly>
						</td>
                        <th style="width:180px">버전정보</th>
                        <td style="width: 30%">
                            <input type="text" name="verInfo" value="0" readonly>
                        </td>
					</tr>
					<tr>
						<th style="width:180px;">인터페이스명</th>
						<td>
							<input type="text" name="eaiSvcDesc" readonly="readonly">
						</td>
                        <th style="width:180px;">서버구분코드</th>
                        <td> 
                            <div class="select-style">
                            	<select id="eaiSevrDStcd" name="eaiSevrDStcd"></select>
                            </div>
                        </td>
					</tr>
					 -->
					<tr>
						<th style="width:13%; min-width:130px;"><%=localeMessage.getString("tran2ManDt.conRlCd")%></th>
						<td style="width:37%;">
							<div class="select-style">
								<select id="transformForEaiSvcNameCombo"></select>
							</div>
						</td>
                        <th style="width:13%; min-width:130px;"><%=localeMessage.getString("tran2ManDt.conRlDesc")%></th>
						<td style="width:37%;">
							<input type="text" id="cnvsnDesc" name="cnvsnDesc">
						</td>
					</tr>
				</table>
				<!-- tree -->
				<table style="width:100%; " >
				<tr>					
					<td style="width:40%; vertical-align:top;">
						<table class="table_row" cellspacing="0">
							<tr>
								<th style="width:130px;"><%=localeMessage.getString("tran2ManDt.ioMsgIdBfCon")%></th>
								<td>
									<input type="text" name="srcLayout" style="width:100%;" readonly="readonly" />
									<!-- <img id="btn_searchSrcLout" src="/monitoring/img/btn_pop_search.png" level="R" class="btn_img" style="display: inline;">  -->
									<input type="hidden" name="srcLoutIoId" />
								</td>
							</tr>
							<tr>
								<th><%=localeMessage.getString("tran2ManDt.ioMsgIdNmBfCon")%></th>
								<td>
									<input type="text" name="srcLayoutDesc" readonly="readonly">
								</td>
							</tr>
						</table>
						
						<div id="sourceLayoutTd" style="margin-bottom:15px;">
							<table id="sourceLayout"></table>
							<div id="sourcePage"></div>
						</div>
					</td>
					<td style="width:30%; text-align:center; vertical-align: top;">
					
                <br /><!-- 이 br 이 없을 때 버튼이 제대로 동작 하지 않는다. -->
                <!-- 
				<input type=button id="removeAll" name="removeAll" class="btn_img btn_removeAll"/><br />
				<input type=button id="addAll" name="addAll" class="btn_img btn_addAll"/><br />
				<input type=button id="auto" name="auto" class="btn_img btn_auto" />
				 -->
					</td>
					<td style="vertical-align:top;">
						<table class="table_row" cellspacing="0">
							<tr>
								<th style="width:130px;"><%=localeMessage.getString("tran2ManDt.ioMsgIdAtCon")%></th>
								<td>
									<input type="text" name="tgtLayout" style="width:100%;" readonly="readonly" >
									<!-- <img id="btn_searchTgtLout" src="/monitoring/img/btn_pop_search.png" level="R" class="btn_img" style="display: inline;">  -->
									<input type="hidden" name="tgtLoutIoId" value=""/>
								</td>
							</tr>
							<tr>
								<th><%=localeMessage.getString("tran2ManDt.ioMsgIdNmAtCon")%></th>
								<td>
									<input type="text" name="tgtLayoutDesc" readonly="readonly">									
								</td>
							</tr>
						</table>
						<div id="targetLayoutTd" style="margin-bottom:15px;">
							<table id="targetLayout"></table>
							<div id="targetPage"></div>
						</div>
					</td>
				</tr>	
				</table>	
	        <div id="dialog" title="전문변환규칙 추가" style="display: none">
	          <form>
	              <fieldset class="ui-helper-reset">
	              <br />
	                  추가할 전문변환규칙을 선택 하세요 <br /><br />
	                  <select id="createReqResSelect">
	                  </select>
	              </fieldset>
	          </form>
	        </div>
            <div id="mappingDialog" title="<%=localeMessage.getString("transformManDetail.title2")%>" >
	            <input type="hidden" id="targetRowId"  name="targetRowId" />
	            <input type="hidden" id="cancleCnvsnCmdName"  name="cancleCnvsnCmdName" />
	            <input type="hidden" id="cancleSrcItems"  name="cancleSrcItems" />
	            <table class="table_row" cellspacing="0">
	                <tr>
	                    <th style="width:130px;">
	                    <%=localeMessage.getString("transformManDetail.transCmdName")%></th>
	                    <td>
	                        <div class="select-style" style="display:inline-block; width:calc((100%)*0.7);">
	                            <select id="functionComboDialog" name="functionComboDialog" style="width:120%;"></select>
	                        </div>
	                    </td>
	                </tr>
	                <tr id="addItemBeforeTr" height="80px">
	                    <td colspan="2"><textarea  name="CNVSNCMDNAME" style="height: 100%" ></textarea></td>
	                </tr>
	                <tr>
	                    <th><%=localeMessage.getString("transformManDetail.default")%></th><td><input type="text" name="CNVSNITEMBASCVAL"/></td>
	                </tr>
                    <tr height="75px">
                        <th style="width:130px;"><%=localeMessage.getString("transformManDetail.tgtItemName")%></th>
                        <td><textarea  name="CNVSNRSULTITEMPATHNAME" readonly="readonly"></textarea></td>
                    </tr>
                    <tr>
                        <th><%=localeMessage.getString("transformManDetail.mappSerNo")%></th>
                        <td><input type="text"  name="CNVSNITEMSERNO" readonly="readonly"/></td>
                    </tr>
	            </table>
			</div>
			<div id="contextMenuDiv" style="position:relative;"></div>
		  </div><!-- end right_box -->
		</div>
		<div id="ajax_wait_modal" class="ajax_wait_modal">
			
		</div>
	</body>
</html>