<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ 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"/>
<jsp:include page="/jsp/common/include/script.jsp"/>

<script language="javascript" >
var url      ='<c:url value="/onl/admin/adapter/adapterMan.json" />';
var url_view ='<c:url value="/onl/admin/adapter/adapterMan.view" />';
var url_popup ='<c:url value="/onl/admin/authserver/clientMan.view"/>';

var selectName = "EAIBZWKDSTCD";	// selectBox Name
var prptyDomain =[];		//도메인 정보를 전역변수로 선언함
var isDetail = false;
var lastRadioVal = {};		//라디오박스의 최종값 저장(네임:값)

var validateNameResult = -1;

//어댑터 갯수
var adaptersCnt = 0;


function isValid(){
	if($('input[name=ADPTRBZWKGROUPNAME]').val() == ""){
		alert("<%=localeMessage.getString("adapterDetail.checkRequierd1")%>");
		$('input[name=ADPTRBZWKGROUPNAME]').focus();
		return false;
	}
	
	// 기존등록된 어댑터는 표준에 맞지 않을 수 있으므로, 검증로직을 SKIP한다.
	if(!isDetail) {
		if(validateNameResult < 0) {
			validateName();
		}
		if(validateNameResult > 0) {
			var r = confirm("어댑터 그룹명이 표준에 맞지 않습니다.\n그래도 저장하시겠습니까 ?");
			if (r == false) {
				$('input[name=ADPTRBZWKGROUPNAME]').focus();
				return;		
			}
		}
	}
	
	if($('select[name=ADPTRCD]').val() == ""){
		alert("<%=localeMessage.getString("adapterDetail.checkRequierd2")%>");
		$('select[name=ADPTRCD]').focus();
		return false;
	}
	
	return true;
}

function extractNickNamePrefix() {
	var adapterName = $('input[name=ADPTRBZWKGROUPNAME]').val();
	var eaiBzwkDstCd = $('select[name=EAIBZWKDSTCD]').val().trim();
	//var adapterIoCode = $('select[name=ADPTRIODSTCD]').val();
	var adapterIoCode =adapterName.substring(5,7);
	
		
	
	if(adapterName.length > 0)  {
		adapterName = adapterName.trim();
	}
	
	if(adapterName.length == 0 ) {
		return "";	
	}
	
	if(adapterName.substring(0, 1) == "_" ) {
		adapterName = adapterName.substring(1);
	}
	
	if(eaiBzwkDstCd.length == 4){
		eaiBzwkDstCd = eaiBzwkDstCd.substring(1);
	}
	
	if(adapterIoCode == "IN"){
		adapterIoCode ="I";
	}else if(adapterIoCode == "OU"){
		adapterIoCode ="O";
	}else if(adapterIoCode == "IO"){
		adapterIoCode ="B";
	}	
	
	var names = adapterName.split("_");
}

function validateName(){
	var checkError = 0;
	var adapterName = $('input[name=ADPTRBZWKGROUPNAME]').val();
	var eaiBzwkDstCd = $('select[name=EAIBZWKDSTCD]').val().trim();
	var adapterIoCode = $('select[name=ADPTRIODSTCD]').val();
	var adapterCode = $('select[name=ADPTRCD]').val();
	
	if(eaiBzwkDstCd.length == 4){
		eaiBzwkDstCd = eaiBzwkDstCd.substring(1);
	}
	
// 	var alertMessage = "* 어댑터 명명규칙\n\"_[업무구분코드]_[IN/OUT 구분]_[어댑터 유형]_[통신타입]\"\n"; //Adapter naming rules
	var alertMessage = "<%=localeMessage.getString("adapterDetail.namingRule")%>";
	if(adapterName.length > 0)  {
		adapterName = adapterName.trim();
	}
	
	if(adapterName.length == 0 ) {
		checkError++;
		alert(alertMessage);
		return;
	}
	
	if(adapterName.substring(0, 1) == "_" ) {
		adapterName = adapterName.substring(1);
	}
	var names = adapterName.split("_");
	
	if(names.length < 4) {
		checkError++;
	}
	else {
		if(names[0] != eaiBzwkDstCd) {
			checkError++;
			alertMessage = alertMessage + "\n - 업무구분코드 (" +eaiBzwkDstCd +")와 어댑터명이 일치하지 않음 (" + names[0] +")";
		}
		
		if( !((names[1] == "IO") ||(names[1] == "OU" && adapterIoCode =="O") || (names[1] == "IN" && adapterIoCode =="I") ) ) {
			checkError++;
			alertMessage = alertMessage + "\n - IN/OUT 구분 (" + adapterIoCode +")과 어댑터명이 일치하지 않음 (" + names[1] +")";
		}
		
		if(names[2] != adapterCode) {
			checkError++;
			alertMessage = alertMessage + "\n - 어댑터 유형 (" + adapterCode +")과 어댑터명이 일치하지 않음 (" + names[2] +")";
		}
		
		if(names[3].length >= 3) {
			var tranType = names[3].substring(0,3);
			
			if( !(tranType == 'SyS' || tranType == 'SyC' || tranType == 'AsS' || tranType == 'AsC') ) {
				checkError++;
				alertMessage = alertMessage + "\n - 통신타입 (SyS, SyC, AsS, AsC)과 어댑터명이 일치하지 않음 (" + names[3] +")";
			}
		}
		else {
			checkError++;
			alertMessage = alertMessage + "\n - 통신타입 (SyS, SyC, AsS, AsC)과 어댑터명이 일치하지 않음 (" + names[3] +")";
		}
	}
	
	if(checkError > 0) {
		alert(alertMessage);
	}
	else {
		alertMessage = alertMessage + "\n 어댑터그룹명이 표준에 맞게 입력되었습니다."; //Adapter group name is entered correctly.
		alert(alertMessage);
	}
	validateNameResult = checkError; 
	return checkError;
}

function localSave(isSilent){
	var key =$("input[name=ADPTRBZWKNAME]").val();
	//객체 생성
	var save ={};
	var adapterPropGroup={}
	$("#adapter input,#adapter select").not('select[name=ADAPTERLIST]').each(function(){
		var name = $(this).attr('name').toUpperCase();
		save[name] = $(this).val();
	});
	var fullData = $("#grid").getRowData();
	//getRowData 하면 select html 그대로 들어가기 때문에 추가함
	for(var i=0;i<fullData.length;i++){
		var keyName = fullData[i].PRPTYGROUPNAME+"_"+fullData[i].PRPTYNAME;
		keyName = keyName.replace(/[.\:\{\}\+]/g,'');								//Name은 . 또는 {} 포함안되므로 치환
		var domainType = fullData[i].DOMAINTYPE;
		if(fullData[i].DOMAINTYPE != null && fullData[i].DOMAINTYPE != "" ){
			if(domainType.toUpperCase() == "SELECT"){
				fullData[i]["PRPTY2VAL"]= $("select[name="+keyName+"] option:selected").val();
			}else if(domainType.toUpperCase() == "RADIO"){
				fullData[i]["PRPTY2VAL"]= $("input:radio[name="+keyName+"]:checked").val();
			} else if(domainType.toUpperCase() == "CHECK"){
				fullData[i]["PRPTY2VAL"]= $("input:checkbox[name="+keyName+"]:checked").val();
			}
			
		}else{
				fullData[i]["PRPTY2VAL"]=fullData[i]["PRPTY2VAL"].replace(/&nbsp;/g,' ');
		}
		fullData[i]["PRPTYGROUPNAME"]=$("input[name=PRPTYGROUPNAME]").val();
		
		//추가 2019.03.13 SWCHOI
		fullData[i]["LSTNERCLSNAME"]=$("input[name=LSTNERCLSNAME]").val();
		fullData[i]["TESTCLSNAME"]=$("input[name=TESTCLSNAME]").val();
		fullData[i]["ADPTRDESC"]=$("input[name=ADPTRDESC]").val();
		fullData[i]["PRPTYGROUPDESC"]=$("input[name=PRPTYGROUPDESC]").val();
	}
	
	adapterPropGroup['adapterProps'] = fullData;
	adapterPropGroup['PRPTYGROUPNAME']=$("input[name=PRPTYGROUPNAME]").val();
	
	if ($("input[name=PRPTYGROUPDESC]").val() == "") {
		adapterPropGroup['PRPTYGROUPDESC']= "어댑터 프러퍼티 : " + $("input[name=PRPTYGROUPNAME]").val();
	} else {
		adapterPropGroup['PRPTYGROUPDESC']=$("input[name=PRPTYGROUPDESC]").val();
	}
	
	save['ADPTRBZWKGROUPNAME'] = $("input[name=ADPTRBZWKGROUPNAME]").val();
	save["adapterPropGroup"]= adapterPropGroup;
	save["adapterProps"] = fullData;
	submitData[key]=save;

	if (!isSilent) {
		alert("<%=localeMessage.getString("adapterDetail.saveAlertMsg1")%>");
	} else {
		alert("어댑터 정보 저장 성공!");
	}
	
}

//어댑터 갯수 체크
function chkAdapterCnt(type){
	
	if(type == 'add'){
		adaptersCnt = (adaptersCnt > 0?adaptersCnt += 1:1)
	}else{
		adaptersCnt = (adaptersCnt > 0?adaptersCnt -= 1:0)
	}
	
	$("#adaptersCnt").text("- "+adaptersCnt+" 개");
	
}


function init(key,callback){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=EAIBZWKDSTCD]")).setFormat(codeName3OptionFormat).setData(json.bizRows).rendering();				// 업무구분코드
			new makeOptions("CODE","NAME").setObj($("select[name=ADPTRCD]")).setFormat(codeName3OptionFormat).setNoValueInclude(true).setData(json.adapterTypeRows).rendering();	// 어댑터 유형
			new makeOptions("CODE","NAME").setObj($("select[name=ADPTRMSGDSTCD]")).setFormat(codeName3OptionFormat).setData(json.msgTypeRows).rendering();			// 메시지타입
			new makeOptions("CODE","NAME").setObj($("select[name=MSGENCODE]")).setFormat(codeName3OptionFormat).setNoValueInclude(true).setData(json.msgEncodeRows).rendering();    // 메시지문자셋
			new makeOptions("CODE","NAME").setObj($("select[name=EAISEVRINSTNCNAME]")).setData(json.instanceRows).rendering();										// 서버인스턴스명
			
			new makeOptions("CODE","NAME").setObj($("select[name=ADPTRIODSTCD]")).setData(json.adptrIoDstcdRows).setFormat(codeName3OptionFormat).rendering();		// IN/OUT 구분
			new makeOptions("CODE","NAME").setObj($("select[name=ADPTRMSGPTRNCD]")).setData(json.adptrMsgPtrnCdRows).setFormat(codeName3OptionFormat).rendering();	// 표준/비표준 구분
			new makeOptions("CODE","NAME").setObj($("select[name=ADPTRUSEYN]")).setData(json.ynNumRows).setFormat(codeName3OptionFormat).rendering();				// 어댑터 사용구분
			new makeOptions("CODE","NAME").setObj($("select[name=SNDRCVHMSLOGYN]")).setData(json.ynNumRows).setFormat(codeName3OptionFormat).rendering();			// 송수신 로그여부
			new makeOptions("CODE","NAME").setObj($("select[name=SPCFCLUUSEYN]")).setData(json.ynNumRows).setFormat(codeName3OptionFormat).rendering();				// 특정LU 사용여부
			
			//new makeOptions("CODE","NAME").setObj($("select[name=OSIDINSTIYN]")).setData(json.ynTypeRows).setFormat(codeName3OptionFormat).rendering();				// 대외기관 여부
			//new makeOptions("CODE","NAME").setObj($("select[name=MONIUSEYN]")).setData(json.ynRows).setFormat(codeName3OptionFormat).rendering();				// 모니터링 사용 여부
			//new makeOptions("CODE","NAME").setObj($("select[name=MONIOPTION]")).setData(json.monicondiSetRows).setFormat(codeName3OptionFormat).rendering();				// 모니터링 조건설정여부	
			//new makeOptions("CODE","NAME").setObj($("select[name=TESTMASTERYN]")).setData(json.testMasterYnRows).setFormat(codeName3OptionFormat).rendering();			//TAS참조대표어댑터여부
			
			//EAI서버구분코드
			//new makeOptions("CODE","NAME").setObj($("select[name=EAISEVRDSTCD]")).setData(json.inoutTypeRows).setFormat(codeName3OptionFormat).rendering();
			//DR대상 어댑터여부
			//new makeOptions("CODE","NAME").setObj($("select[name=DRADPTRYN]")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();	
			
			// 동일 세션 사용여부(Socket IOBOUND)
			new makeOptions("CODE","NAME").setObj($("select[name=sameSessionYn]")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();
			// IN/OUT pair Adapter 사용 여부
			new makeOptions("CODE","NAME").setObj($("select[name=pairAdapterYn]")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();

			if(key == "")
			{
				$("input[name=REFCLSNAME]").val(json.refClsName);	// 어댑터 신규 입력할 때 참조 클래스명 default setting.
				setSearchable(selectName);	// 콤보에 searchable 설정
			}

			if(typeof callback === 'function') {
				callback(key);
    		}


		},
		error:function(e){
			alert(e.responseText);
		}
	});

}
function detail(key){
	if (!isDetail) return ;
	
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'DETAIL'
		    , ADPTRBZWKGROUPNAME : key
		    },
		success:function(json){
			var detail = json;
			var adapters = json.adapters;
			
			//어댑터 리스트 카운트
			adaptersCnt = adapters.length;
			if(adaptersCnt > 0){
				$("#adaptersCnt").text("- "+adaptersCnt+" 개");
			}
			
			prptyDomain = json.dInfo;
						//도메인 정보
		
			//adapterGroup
			$("input[name=ADPTRBZWKGROUPNAME]").attr('readonly',true);
			
			var moniTmp = "";
			var org_adptNickNm = "";
			var osidinstiYn = "N";
			
			$("#detail input,#detail select").each(function(){
				var name = $(this).attr('name').toUpperCase();
				
				$(this).val(detail[name]);
				
				//모니터링 조건설정
				if(name == 'MONICNDNCTNT'){
					moniTmp = detail[name];
				}
				
			});

			
			
			//adapter
			if (adapters.length > 0){
				$("#adapter input,#adapter select").not('select[name=ADAPTERLIST]').each(function(){
					var name = $(this).attr('name').toUpperCase();
					$(this).val(adapters[0][name]);
				});
				//addoption
				new makeOptions("PRPTYGROUPNAME","PRPTYGROUPNAME").setObj($("select[name=ADAPTERLIST]")).setData(adapters).rendering();
				for(var i=0;i<adapters.length;i++){
					submitData[adapters[i]["PRPTYGROUPNAME"]]=adapters[i];
				}
			}
			
			//prop
			
			if(adaptersCnt > 0){
				var prop = json.adapters[0].adapterProps;
				$("#grid")[0].addJSONData(prop);
			}
			
			setSearchable(selectName);	// 콤보에 searchable 설정

			var adptriodstcdValue = $('#ADPTRIODSTCD').val();
			toggleClientIdButton(adptriodstcdValue);
			$('input[name=CLIENTID]').val(json.CLIENTID || '');

			updateClientIdButtonStates();
		},
		error:function(e){
			alert(e.responseText);
		}
	});


}

function mltplFormatter (cellvalue, options,rowObject){


 	if(rowObject.DMNKND != null && rowObject.DMNKND != "" && rowObject.DOMAINTYPE != null){	
 		if(rowObject.DOMAINTYPE.toUpperCase() == "SELECT"){
			return setSelectCombo(rowObject);
		}else if(rowObject.DOMAINTYPE.toUpperCase() == "RADIO"){
			var val= setRadio(rowObject);
			return val;
		}else if(rowObject.DOMAINTYPE.toUpperCase() == "CHECK"){
			return setCheckbox(rowObject);
		}else{
			return cellvalue;
		}
	}else{ 
		if(cellvalue === undefined || cellvalue == null){
			return '';	 
		}
		cellvalue = cellvalue.replace(/[ ]/g,'&nbsp;');
		return cellvalue;
	}
	//return '<pre>'+cellvalue + '</pre>';
}

function mltplUnFormatter (cellvalue, options,rowObject){
	var name = (rowObject.PRPTYGROUPNAME==null?"":rowObject.PRPTYGROUPNAME)+"_"+rowObject.PRPTYNAME;
	name = name.replace(/[.\:\{\}\+]/g,'');		
	//name 에는 . {} 못들어가서 제거
	if(rowObject.DMNKND != null && rowObject.DMNKND != "" && rowObject.DOMAINTYPE != null){
 		if(rowObject.DOMAINTYPE.toUpperCase() == "SELECT"){
			return $("select[name="+name+"] option:selected").val();
		}else if(rowObject.DOMAINTYPE.toUpperCase() == "RADIO"){
			//return setRadio(rowObject);
		}else if(rowObject.DOMAINTYPE.toUpperCase() == "CHECK"){
			//return setCheckbox(rowObject);
		}else{
			return cellvalue;
		}	
		
	}
	else{
		return cellvalue.replace(/&nbsp;/g,' ');
	}	
}

function setSelectCombo(rows){
	var domainName = rows.DMNKND;
	var value = rows.PRPTY2VAL;
	var result="";

	var data = prptyDomain[domainName].data;
	if(data == null || data.length == 0){  
		console.log("도메인명 : "+domainName +" 코드 조회 안됨"); 
				
	} 
	var name = (rows.PRPTYGROUPNAME==null?"":rows.PRPTYGROUPNAME)+"_"+rows.PRPTYNAME;
	name = name.replace(/[.\:\{\}\+]/g,'');
	result='<select name="'+name+'" style="width:100%">';
	//result += '<option value=""></option>';
	for(var idx=0;idx < data.length; idx++){
		if(data[idx].CODE == value)
			result += '<option value="'+ data[idx].CODE+'" selected>'+data[idx].NAME +'</option>';
		else
			result += '<option value="'+ data[idx].CODE+'">'+data[idx].NAME +'</option>';
	}

	result +='</select>';	

	return result;
}
function setRadio(rows){
	var domainName = rows.DMNKND;
	var value = rows.PRPTY2VAL;
	var result="";

	var data = prptyDomain[domainName].data;
	if(data == null || data.length == 0){  
		console.log("도메인명 : "+domainName +" 코드 조회 안됨"); 
	} 
	var name = (rows.PRPTYGROUPNAME==null?"":rows.PRPTYGROUPNAME)+"_"+rows.PRPTYNAME;
	name = name.replace(/[.\:\{\}\+]/g,'');

	for(var idx=0;idx < data.length; idx++){
		if(data[idx].CODE == value){
			result += '<input type="radio" name="'+name+'" value="'+ data[idx].CODE+'"  checked>'+data[idx].NAME+" ";
			lastRadioVal[name] = value;
		}else{
			result += '<input type="radio" name="'+name+'" value="'+ data[idx].CODE+'" >'+data[idx].NAME+" ";
		}
	}

	return result;
}

function setCheckbox(rows){

	var domainName = rows.DMNKND;
	var value = rows.PRPTY2VAL;
	var result="";
	
	var data = prptyDomain[domainName].data;
	if(data == null || data.length == 0){  
		console.log("도메인명 : "+domainName +" 코드 조회 안됨"); 
	} 
	var name = (rows.PRPTYGROUPNAME==null?"":rows.PRPTYGROUPNAME)+"_"+rows.PRPTYNAME;
	name = name.replace(/[.\:\{\}\+]/g,'');

	
	for(var idx=0;idx < data.length; idx++){
		if(data[idx].CODE == value)
			result += '<input type="checkbox" name="'+name+'" value="'+ data[idx].CODE+'" checked>'+data[idx].NAME+" ";
		else
			result += '<input type="checkbox" name="'+name+'" value="'+ data[idx].CODE+'">'+data[idx].NAME+" ";
	}

	return result;
}
//도메인 타입이 null이면 조건체크 중에 에러 발생해서 공백으로 치환
function nullFormatter(cellvalue, options, rowData){
	if(cellvalue === undefined || cellvalue == null || cellvalue ==='NULL'){
		cellvalue='';
	}
	return cellvalue;
}
function gridRendering(){
	$('#grid').jqGrid({
		datatype:"local",
	    editurl : "clientArray",
		loadonce: true,
		rowNum: 10000,
		autoencode:false,
		colNames:['<%=localeMessage.getString("adapterDetail.prptyGroupName")%>',
                  '<%=localeMessage.getString("adapterDetail.prptyName")%>',
                  '<%=localeMessage.getString("adapterDetail.prpty2Val")%>', 
                  '<%=localeMessage.getString("adapterDetail.prptydesc")%>',
                  '<%=localeMessage.getString("adapterDetail.dmnkNd")%>',
                  '<%=localeMessage.getString("adapterDetail.domainType")%>'
                  ],
		colModel:[
				{ name : 'PRPTYGROUPNAME' , align:'left' , hidden: true },
				{ name : 'PRPTYNAME'  	  , width: 70    , align:'left'  },
				{ 
			        name : 'PRPTY2VAL', 
			        width: 70, 
			        align:'left', 
			        title:false, 
			        editable: true, 
			        formatter:mltplFormatter, 
			        unformatter:mltplUnFormatter,
			        editoptions: {
			            dataEvents: [
			                {
			                    type: 'keydown',
			                    fn: function(e) {
			                        if (e.which === 13) {
			                            var val = $(this).val();
			                            $(this).val($.trim(val));
			                        }
			                    }
			                },
			                {
			                    type: 'blur', 
			                    fn: function(e) {
			                        var val = $(this).val();
			                        $(this).val($.trim(val));
			                    }
			                }
			            ]
			        }
			        // [여기까지 추가]
			    },
				{ name : 'PRPTYDESC'	  , width: 300    , align:'left'},
				{ name : 'DMNKND'	  	  , hidden:true},
				{ name : 'DOMAINTYPE'	  , hidden:true, formatter:nullFormatter}
				],
        jsonReader: {
             repeatitems:false
        },	   
        loadComplete : function (data) {
		
        },
        gridComplete : function(){
			//라디오 버튼의 해제 기능
			$(":radio").unbind("click");
			$("input[type=radio]").bind('click',function(){
				var name = $(this).attr('name');	
				var lastVal = lastRadioVal[name];
				if(lastVal == $(this).val()){
					$(this).attr('checked',false);
					lastRadioVal[name]= ''; 
				}else{
					lastRadioVal[name]= $(this).val();
				}     
								
			});  
			
			//프라퍼티 정보 tooltip 적용
			var rows = $(this).getDataIDs();
	    	for( var i= 0; i < rows.length; i++){
	    	 var tooltip = $(this).getCell(rows[i],'PRPTYDESC');
	    	 $("#grid").setCell(rows[i],'PRPTYNAME','','',{'title':tooltip}); 
	    	}
        },
	    onSelectRow: function(rowid,status){
	    	var rowData = $(this).getRowData(rowid);
	    	var domainName = rowData.DMNKND;
	    	var domainType = rowData.DOMAINTYPE;
	    	if(domainType.toUpperCase() == 'SELECT' || domainType.toUpperCase() == 'CHECK' || domainType.toUpperCase() == 'RADIO') return;

	    	if (lastsel2 !=undefined){
	            if($("#grid tr#" + lastsel2).attr("editable") == 1){ //editable=1 means row in edit mode
	        	  $("#grid").saveRow(lastsel2,false,"clientArray");
				}
	    	}
	    	
	        $('#grid').restoreRow(lastsel2);       
	        $('#grid').editRow(rowid,true);
	       
	       //도메인 지정
	        if(domainName != null && domainName != "" && prptyDomain[domainName] != null && prptyDomain[domainName] !="")
	        	$("input[name=PRPTY2VAL]").inputmask(prptyDomain[domainName]["info"].DOMAINVAL,{'autoUnmask':true});
	        	
	        var val = $('input[name=PRPTY2VAL]').val();
	        $('input[name=PRPTY2VAL]').val(val.replace(/&nbsp;/g,' '));	//Html Text --> Inputbox Text : &nbsp --> ' '	   
	        lastsel2=rowid;
	    },        
        onSortCol : function(){
        	return 'stop';	//정렬 방지
        },         
	    height: '300',
		autowidth: true,
		viewrecords: true
	});	
	resizeJqGridWidth('grid','content_middle','1000');
}

function toggleClientIdButton(adptriodstcd) {
	if (adptriodstcd === "I") {
		$('#btn_popup_app').prop('disabled', true);
	} else {
		$('#btn_popup_app').prop('disabled', false);
	}
}

function updateClientIdButtonStates() {
	var clientId = $('input[name=CLIENTID]').val();
	$('#btn_popup_app_delete').prop('disabled', !clientId);
}

var submitData = {};
var lastsel2;
$(document).ready(function() {	
	var returnUrl = getReturnUrlForReturn();

	$("button,select[name=ADAPTERLIST]").click(function(){
		if($("#grid tr#" + lastsel2).attr("editable") == 1){ //editable=1 means row in edit mode
          $("#grid").saveRow(lastsel2,false,"clientArray");
		}
	});

	var key ="${param.adptrBzwkGroupName}";
	key = decodeURIComponent(key);
	
	if (key != "" && key !="null"){
		isDetail = true;
	}
	gridRendering();	
	init(key,detail);

	$('#ADPTRIODSTCD').change(function() {
		var adptriodstcdValue = $(this).val();
		toggleClientIdButton(adptriodstcdValue);  // 값이 변경될 때마다 버튼 상태 체크
	});

	$('input[name=CLIENTID]').on('change', updateClientIdButtonStates);

	$("#btn_popup_app_delete").click(function(){
		if(confirm("CLIENT ID를 삭제하시겠습니까?")) {
			$('input[name=CLIENTID]').val('');
			updateClientIdButtonStates();
		}
	});

	// CLIENTID 초기값에 따라 버튼 상태 설정
	updateClientIdButtonStates();

	$("#btn_modify").click(function(){
		if (!isValid()) return;
	
		// 수정 할 때만 confirm 실행.
		if(isDetail)
		{
			var r = confirm("<%=localeMessage.getString("adapterDetail.checkMsg4")%>");
			if (r == false) return;
		}

		// 25.12.16 수정시 어댑터 리스트 자동저장
	    var isSubSaveSuccess = ModifyPopCheckAndSave(true);

	    if (!isSubSaveSuccess) {
		    alert("어댑터 정보 저장이 실패했습니다. 어댑터 정보를 확인해주세요.");
	        return; 
	    }
		
		//공통부만 form으로 구성
		var postData = $('#ajaxForm').serializeArray();
		
		postData.push({ name: "ADAPTERDATA" , value:JSON.stringify(submitData)});
		
		
		if (isDetail){
			postData.push({ name: "cmd" , value:"UPDATE"});
		}else{
			postData.push({ name: "cmd" , value:"INSERT"});
		}
		 $.ajax({
			type : "POST",
			url:url,
			data:postData,
            beforeSend: function() {
            	$("[id^='btn_']").prop("disabled", true);
            	$("#btn_modify").text("처리중 . . . . .");
            },
			success:function(args){
				if(args.status=="error"){
					alert("<%=localeMessage.getString("common.intizMsg")%>"+args.message);
				}else{
					alert("<%=localeMessage.getString("common.saveMsg")%>");
					goNav(returnUrl);//LIST로 이동
				}
			},
			error:function(e){
				alert(e.responseText);
			},
            complete: function() {
            	$("[id^='btn_']").prop("disabled", false);
				$("#btn_modify").text("수정");
            }
		}); 
	});
	$("#btn_clone,#btn_clone_new").click(function(){
		var newAdapterGroupName = $("input[name=NEWADPTRBZWKGROUPNAME]");	// 복제할 어댑터 그룹명
		if (!isValid())return;
		
		var flag = $(this).attr("id");
		
		// 복제할 어댑터 그룹명이 입력되었는지 체크.
		if(newAdapterGroupName.val() == "")
		{
			if(flag == 'btn_clone'){
				alert("<%=localeMessage.getString("adapterDetail.checkRequierd3")%>");
			}else{
				alert("<%=localeMessage.getString("adapterDetail.checkRequierd6")%>");
			}
			newAdapterGroupName.focus();
			return;
		}
		
		
		//공통부만 form으로 구성
		var postData = $('#ajaxForm').serializeArray();
		
		//복제인지 신규인지 체크
		if(flag == 'btn_clone'){
			postData.push({ name: "CLONEYN" , value:"Y"});
		}
		
		postData.push({ name: "ADAPTERDATA" , value:JSON.stringify(submitData)});
		postData.push({ name: "cmd" , value:"CLONE"});
		
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
            beforeSend: function() {
            	$("[id^='btn_']").prop("disabled", true);
            	$("#btn_clone").text("처리중 . . . . .");
            },
			success:function(args){
				alert("<%=localeMessage.getString("common.croneMsg")%>");
				//goNav(returnUrl);//LIST로 이동
				var key = $("input[name=NEWADPTRBZWKGROUPNAME]").val();
				//init(key,detail);
				var url2 = url_view;
	            url2 += '?cmd=DETAIL';
	            url2 += '&menuId='+'${param.menuId}';
	            url2 += '&adptrBzwkGroupName='+key;
	            goNav(url2); 
			},
			error:function(e){
				if (e.responseText != null) {
					try {
						alert(JSON.parse(e.responseText).errorMsg);	
					} catch (e) {
						alert(error);
					}
				}
			},
            complete: function() {
            	$("[id^='btn_']").prop("disabled", false);
				$("#btn_clone").text("복제");
            }
		});
	});	
	$("#btn_delete").click(function(){
		if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){  	
			var postData = $('#ajaxForm').serializeArray();
			postData.push({ name: "cmd" , value:"DELETE"});
			$.ajax({
				type : "POST",
				url:url,
				data:postData,
                beforeSend: function() {
                	$("[id^='btn_']").prop("disabled", true);
                	$("#btn_delete").text("처리중 . . . . .");
                },
				success:function(args){
					if(args.status=="error"){
						alert("<%=localeMessage.getString("common.intizMsg")%>"+args.message);
					}else{
						alert("<%=localeMessage.getString("common.deleteMsg")%>");
						goNav(returnUrl);//LIST로 이동
					}			
				},
				error:function(e){
					alert(e.responseText);
				},
                complete: function() {
                	$("[id^='btn_']").prop("disabled", false);
					$("#btn_delete").text("삭제");
                }
			});
		}else{
			return false;
		}
	});	
	$("#btn_previous").click(function(){
		goNav(returnUrl);//LIST로 이동
	});
	$("input[name=ADPTRBZWKNAME]").keyup(function(key){
		$("input[name=PRPTYGROUPNAME]").val($(this).val());
		$("input[name=PRPTYGROUPDESC]").val("어댑터 프라퍼티 : "+$(this).val());
	});

	$("select[name=ADAPTERLIST]").change(function(){
		if (!($(this).val() == null || $(this).val() == undefined || $(this).val() == "")){
			var adapter = submitData[$(this).val()];
			$("#adapter input,#adapter select").not('select[name=ADAPTERLIST]').each(function(){
				var name = $(this).attr('name').toUpperCase();
				$(this).val(adapter[name]);
			});
			$("#grid")[0].addJSONData(adapter.adapterProps);
		}else{
			$("#adapter input,#adapter select").not('select[name=ADAPTERLIST]').each(function(){
				$(this).val("");
			});
			var ids = $("#grid").getDataIDs();
			for(var i=0;i<ids.length;i++){
				$("#grid").jqGrid('setCell',ids[i],'PRPTY2VAL',null);
			}

		}
	});
	$("#btn_pop_new").click(function(){
		// 어댑터명 입력 확인
		if($("input[name=ADPTRBZWKNAME]").val() == ""){
			alert("<%=localeMessage.getString("adapterDetail.checkRequierd4")%>");
			return;
		}
		// 어댑터 리스트 중복 체크
		var isDuplication = false;
		$("select[name=ADAPTERLIST] option").each(function(){
			if ($(this).val() == $("input[name=ADPTRBZWKNAME]").val()){
				isDuplication = true;
			}
		});
		if (isDuplication){
			alert("<%=localeMessage.getString("adapterDetail.checkMsg1")%>");
			return;
		}
		//어댑터 목록 추가
		var key = $("input[name=ADPTRBZWKNAME]").val();
		var str = new makeOptions("CODE","NAME").setData(key,key).getOption();
		$("select[name=ADAPTERLIST]").append(str);
		$("select[name=ADAPTERLIST]").val(key);
		submitData[key]=""; 
		localSave();
		chkAdapterCnt('add');
		
	}); 
	$("#btn_pop_modify").click(function(){ // 검색용
		ModifyPopCheckAndSave(false);
	});	

	function ModifyPopCheckAndSave(isSilent) {
		var isDuplication = false;
		
		$("select[name=ADAPTERLIST] option").each(function(){
			if ($(this).val() == $("input[name=ADPTRBZWKNAME]").val()){
				isDuplication = true;
			}
		});
		
		if (!isDuplication){
			// 화면 저장시 기존 alert 표시, INSERT/UPDATE 시 메시지 표시하지 않음
			if (!isSilent) {
				alert("<%=localeMessage.getString("adapterDetail.checkMsg2")%>");
			}
			return false;
		}
		
		localSave(isSilent);
		return true;
	}
	
	$("#btn_pop_delete").click(function(){
		var isDuplication = false;
		$("select[name=ADAPTERLIST] option").each(function(){
			if ($(this).val() == $("input[name=ADPTRBZWKNAME]").val()){
				isDuplication = true;
			}
		});
		if (!isDuplication){
			alert("<%=localeMessage.getString("adapterDetail.checkMsg3")%>");
			return;
		}
		//어댑터 목록 삭제
		var key = $("input[name=ADPTRBZWKNAME]").val();
		$("select[name=ADAPTERLIST] option[value='"+key+"']").remove();
		delete submitData[key];
		$("select[name=ADAPTERLIST]").trigger("change");
		
		chkAdapterCnt('del');
		
		alert("화면상에서 저장되었습니다.\n상단 수정버튼을 이용하여 모든 정보를 저장해 주세요.");
		//Only the screen has been saved. Click the modify button on the top to save all info.
	});	
	$("#btn_pop_initialize").click(function(){
		//data 초기화
		$("#adapter input,#adapter select").not('select[name=ADAPTERLIST]').each(function(){
			$(this).val("");
		});
		var ids = $("#grid").getDataIDs();
		for(var i=0;i<ids.length;i++){
			$("#grid").jqGrid('setCell',ids[i],'PRPTY2VAL',null);
		}
	});
	$("select[name=ADPTRCD],select[name=ADPTRIODSTCD]").change(function(){
		if ($('select[name=ADPTRCD]').val()=="") return;
		if ($('select[name=ADPTRIODSTCD]').val()=="") return;
		$.ajax({  
			type : "POST",
			url:url,
			dataType:"json",
			data:{cmd: 'LIST_PROP'
			     , adptrCd : $('select[name=ADPTRCD]').val()
			     , adptrIoDstcd : $('select[name=ADPTRIODSTCD]').val()
			},
			success:function(json){
			
				prptyDomain = json.dInfo;
				//$("#grid").trigger("reloadGrid");
				$("#grid")[0].addJSONData(json);
				
			},
			error:function(e){
				alert(e.responseText);
			}
		});
	});

    $("#btn_pop_validate").click(function(){
		validateName();
	});	
	

	
	$("#btn_json_export").click(function () {
		const uri = url + '?cmd=DETAIL_EXPORT_TO_JSON';
		const params = new URLSearchParams();
		params.append('adapterGroupName', key);

		downloadFiles(uri, params);

		return false;
	});

	$("#btn_popup_app").click(function(){
		const args = {};
		const url2 = url_popup + "?cmd=POPUP";
		showModal2(url2, args, 1280, 860, function(result) {
			if (result && result.selectedClientId) {
				$('input[name=CLIENTID]').val(result.selectedClientId);
			}
		});
	});

	buttonControl(isDetail);
	titleControl(isDetail);

});

// clientManPopup.jsp에서 호출될 함수 (전역 스코프에 정의)
function selectClient(clientId) {
	$('input[name=CLIENTID]').val(clientId);
	updateClientIdButtonStates();
}
</script>
</head>
	<body>
		<div class="right_box">
			<div class="content_top">
				<ul class="path">
					<li><a href="#">${rmsMenuPath}</a></li>					
				</ul>					
			</div><!-- end content_top -->
			<div class="content_middle" id="content_middle">
				<div class="search_wrap">
					<button type="button" class="cssbtn" id="btn_json_export" level="R" status="DETAIL,NEW"><i class="material-icons">download</i> <%=localeMessage.getString("button.exportJson")%></button>
					<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
					<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
					<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
<%-- 					<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" status="DETAIL"/>				 --%>
<%-- 					<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"/> --%>
				</div>
				<div class="title_adptdetail"><%=localeMessage.getString("adapterDetail.title6")%></div>						
				
				<form id="ajaxForm">
					<div class="table_row_title"><%=localeMessage.getString("adapterDetail.title2")%></div>
<%
	String adptrBzwkGroupName = request.getParameter("adptrBzwkGroupName");
	if(adptrBzwkGroupName != null && adptrBzwkGroupName.length() > 0) {
%>					
					<table id="detail" class="table_row"  cellspacing="0" >
						<tr level="W" >
							<td colspan="4">
								<input type="text" name="NEWADPTRBZWKGROUPNAME" style="width:200px;"> 
<%-- 								<img id="btn_clone" src="<c:url value="/img/btn_clone1.png" />" level="W" status="DETAIL" class="btn_img"/>	 --%>
<%-- 								<img id="btn_clone_new" src="<c:url value="/img/btn_pop_new.png" />" level="W" status="DETAIL,NEW" class="btn_img" />	 --%>
								<button type="button" class="cssbtn smallBtn2" id="btn_clone" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL"><i class="material-icons">content_copy</i><%= localeMessage.getString("button.clone2") %></button>
								<button type="button" class="cssbtn smallBtn2" id="btn_clone_new" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">add</i><%= localeMessage.getString("button.new") %></button>
								 &nbsp;<span style="color:blue;">※ <%=localeMessage.getString("adapterDetail.cloneMsg1")%> &nbsp; ※ <%=localeMessage.getString("adapterDetail.cloneMsg2")%></span>
							</td>
						</tr>
					</table>	
<%
	}
%>					
					<table id="detail" class="table_row"  cellspacing="0"  >
						<tr>
							<th width="15%"><%=localeMessage.getString("adapterDetail.adptrbzwkgroupname")%></th>
							<td width="35%" ><input type="text" name="ADPTRBZWKGROUPNAME" style="width:calc(100% - 65px);"/>
<%-- 							<img id="btn_pop_validate" src="<c:url value="/img/btn_pop_validate.png" />" class="btn_img"  level="W" status="DETAIL,NEW" /> --%>
							<button type="button" class="cssbtn smallBtn2" id="btn_pop_validate" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">check_circle</i><%= localeMessage.getString("button.valdt") %></button>
							</td>
							<th width="15%"><%=localeMessage.getString("adapterDetail.eaibzwkdstcd")%></th>
							<td width="35%">
								<div class="select-style">
									<select name="EAIBZWKDSTCD" ></select> 
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.adptrmsgptrncd")%></th>
							<td >
								<div class="select-style">
									<select name="ADPTRMSGPTRNCD"></select>
								</div>
							</td>
							<th><%=localeMessage.getString("adapterDetail.adptruseyn")%></th>
							<td >
								<div class="select-style">
									<select name="ADPTRUSEYN"></select>
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.sndrcvhmslogyn")%></th>
							<td >
								<div class="select-style">
									<select name="SNDRCVHMSLOGYN"></select>
								</div>
							</td>
							<th><%=localeMessage.getString("adapterDetail.adptriodstcd")%></th>
							<td >
								<div class="select-style">
									<select name="ADPTRIODSTCD" id="ADPTRIODSTCD"></select>
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.adptrcd")%></th>
							<td >
								<div class="select-style">
									<select name="ADPTRCD"></select> 
								</div>
							</td>
							<th><%=localeMessage.getString("adapterDetail.adptrmsgdstcd")%></th>
							<td >
								<div class="select-style">
									<select name="ADPTRMSGDSTCD"></select> 
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.msgencode")%></th>
							<td>
								<div class="select-style">
									<select name="MSGENCODE"></select>
								</div>
							</td>
							<th><%=localeMessage.getString("adapterDetail.refclsname")%></th>
							<td><input type="text" name="REFCLSNAME"/> 
								<input type="hidden" name="KESAUSEYN" value="0"/>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.spcfcluuseyn")%></th>
							<td >
								<div class="select-style">
									<select name="SPCFCLUUSEYN"></select>
								</div>
							</td>
							<th width="15%"><%=localeMessage.getString("adapterDetail.adptrbzwkgroupdesc")%></th>
							<td width="35%">
								<input type="text" name="ADPTRBZWKGROUPDESC">
							</td>
						</tr>
						<tr>
							<th>CLIENT 아이디</th>
							<td colspan="3">
								<input type="text"  style="display:inline-block; width:500px;" name="CLIENTID" readonly>
								<button type="button" class="cssbtn smallBtn2" id="btn_popup_app" level="W" status="DETAIL,NEW" disabled>
									<i class="material-icons">add</i> <%= localeMessage.getString("button.add") %>
								</button>
								<button type="button" class="cssbtn smallBtn2" id="btn_popup_app_delete" level="W" status="DETAIL,NEW" disabled>
									<i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
								</button>
							</td>
						</tr>

<c:if test="${param.serviceType eq 'GW' }">
						<tr>
							<th><%=localeMessage.getString("adapterDetail.linkedAdapterGroup")%></th>
							<td>
								<input type="text" name="linkedAdapterGroup"/>
							</td>
							<th><%=localeMessage.getString("adapterDetail.sameSessionYn")%></th>
							<td>
								<div class="select-style">
									<select name="sameSessionYn"></select>
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.pairAdapterYn")%></th>
							<td>
								<div class="select-style">
									<select name="pairAdapterYn"></select>
								</div>
							</td>
							<th></th>
							<td>
							</td>
						</tr>
</c:if>
					</table>
					</form>
					
					<div class="table_row_title">
						<table><tr>
							<td class="table_row_title">
								<%=localeMessage.getString("adapterDetail.title3")%>
							</td>
							<td>&nbsp;</td>
							<td><span style="color:black;" id="adaptersCnt"></span></td><td>&nbsp;</td>
						</tr></table>		
					</div>
					
					<!-- 어댑터-->
					<table id="adapter" class="table_row"  cellspacing="0"  >
						<tr>
							<th width="15%"><%=localeMessage.getString("adapterDetail.title5")%></th>
							<td colspan="3">
								<div class="select-style" style="display:inline-block; width:calc(100% - 250px);">
								<select name="ADAPTERLIST"></select> 
								</div>								
<%-- 								 <img id="btn_pop_new" src="<c:url value="/img/btn_pop_new.png" />" level="W" status="DETAIL,NEW" class="btn_img" /> --%>
<%-- 								 <img id="btn_pop_modify" src="<c:url value="/img/btn_pop_modify.png" />" level="W" status="DETAIL,NEW" class="btn_img" /> --%>
<%-- 								 <img id="btn_pop_delete" src="<c:url value="/img/btn_pop_delete.png" />" level="W" status="DETAIL,NEW" class="btn_img" /> --%>
<%-- 								 <img id="btn_pop_initialize" src="<c:url value="/img/btn_pop_initialize.png" />" level="W" status="DETAIL,NEW" class="btn_img" /> --%>
								 <button type="button" class="cssbtn smallBtn2" id="btn_pop_new" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">add</i><%= localeMessage.getString("button.new") %></button> 
								 <button type="button" class="cssbtn smallBtn2" id="btn_pop_modify" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">save</i><%= localeMessage.getString("button.modify") %></button> 
								 <button type="button" class="cssbtn smallBtn2" id="btn_pop_delete" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">delete</i><%= localeMessage.getString("button.delete") %></button> 
								 <button type="button" class="cssbtn smallBtn2" id="btn_pop_initialize" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL,NEW"><i class="material-icons">restart_alt</i><%= localeMessage.getString("button.reset") %></button> 
							</td>
						</tr>
						<tr>
							<th width="15%"><%=localeMessage.getString("adapterDetail.adptrbzwkname")%></th>
							<td width="35%"><input type="text" name="ADPTRBZWKNAME"/> </td>
							<th width="15%"><%=localeMessage.getString("adapterDetail.eaisevrinstncname")%></th>
							<td width="35%">
								<div class="select-style">
								<select name="EAISEVRINSTNCNAME"></select> 
								</div>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.lstnerclsname")%></th><td colspan="3"><input type="text" name="LSTNERCLSNAME"/> </td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.testclsname")%></th><td colspan="3"><input type="text" name="TESTCLSNAME"/> </td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.adptrdesc")%></th><td colspan="3"><input type="text" name="ADPTRDESC"/> </td>
						</tr>
						<tr style="display:none" >
							<th><%=localeMessage.getString("adapterDetail.prptygroupname")%></th><td colspan="3"><input type="text" name="PRPTYGROUPNAME"/> </td>
						</tr>
						<tr style="display:none" >
							<th><%=localeMessage.getString("adapterDetail.prptygroupdesc")%></th><td colspan="3"><input type="text" name="PRPTYGROUPDESC"/> </td>
						</tr>
					</table>
					<div class="table_row_title"><%=localeMessage.getString("adapterDetail.title4")%></div> <!-- Adapter Property Info -->
					
					<!-- grid -->
					<table id="grid" ></table>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->	
	</body>
</html>

