<%@ 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_custom.jsp"/>
<jsp:include page="/jsp/common/include/script.jsp"/>

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

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

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=EAISEVRINSTNCNAME]")).setData(json.instanceRows).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.detail;
			var adapters = json.detail.adapters;
			var prop = json.detail.adapters[0];
			prptyDomain = json.dInfo;
						//도메인 정보
		
			//adapterGroup
			$("input[name=ADPTRBZWKGROUPNAME]").attr('readonly',true);
			
			var moniTmp = "";
			var org_adptNickNm = "";
			
			$("#detail input,#detail select").each(function(){
				var name = $(this).attr('name').toUpperCase();
				
				$(this).val(detail[name]);
				
			});
			
			//어댑터별칭
			$("input[name=ORGADPTRNICKNAME]").val(org_adptNickNm);
			
			//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];
				}
			}
			/* if(prop.rows[0].PRPTYNAME == "APP_CODE"){
				$("#APP_CODE").val(prop.rows[0].PRPTY2VAL);
			} */
			
			//prop 
			$("#grid")[0].addJSONData(prop);
			
			setSearchable(selectName);	// 콤보에 searchable 설정
		},
		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")%>',
                  'PRPTYDESC',
                  '<%=localeMessage.getString("adapterDetail.dmnkNd")%>',
                  '<%=localeMessage.getString("adapterDetail.domainType")%>'
                  ],
		colModel:[
				{ name : 'PRPTYGROUPNAME' , align:'left' , hidden:true},
				{ name : 'PRPTYNAME'      , align:'left' , width:20},
				{ name : 'PRPTY2VAL'      , align:'left' , title:false, editable: false, formatter:mltplFormatter, unformatter:mltplUnFormatter},
				{ name : 'PRPTYDESC'	  ,hidden:true},
				{ 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)
	        	$("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');
}

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

	$("img,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}";
	
	if (key != "" && key !="null"){
		isDetail = true;
	}
	gridRendering();	
	init(key,detail);
	
	
	$("#btn_previous").click(function(){
		goNav(returnUrl);//LIST로 이동
	});

	$("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);		
		}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_modify").click(function(){
	    var args = new Object();
	    args['adptrbzwkgroupname'] = $("input[name=ADPTRBZWKGROUPNAME]").val();
	    args['adptrbzwkname'] = $("input[name=ADPTRBZWKNAME]").val();
	    
	    //인스턴스명추가
	    args['eaiSevrInstncName'] = $("select[name=EAISEVRINSTNCNAME]").val();
	    
	    var url2 = url_view;
	    url2 += "?cmd=POPUP";
	    //showModal(url2,args,470,740);
	    var ret = showModal(url2,args,980,650, 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 ret = args.returnValue;
	        $("select[name=ADAPTERLIST] option").remove();
	        $("select[name=EAISEVRINSTNCNAME] option").remove();
	        init(key,detail);
	        
	    });
	    
		
	});	

	buttonControl(isDetail);
	titleControl(isDetail);
	
});
 
</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">
					<img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW"/>
				</div>
				<div class="title"><%=localeMessage.getString("snaAdapterMan.detailTitle")%></div>						
				
				<form id="ajaxForm">
					<div class="table_row_title"><%=localeMessage.getString("adapterDetail.title2")%></div>
				
					<table id="detail" class="table_row"  cellspacing="0"  >
						<tr>
							<th style="width:180px;"><%=localeMessage.getString("adapterDetail.adptrbzwkgroupname")%></th>
							<td><input type="text" name="ADPTRBZWKGROUPNAME" ></td>
						</tr>
					</table>
				</form>
					<div class="table_row_title"><%=localeMessage.getString("adapterDetail.title3")%></div>
					<!-- 어댑터-->
					<table id="adapter" class="table_row"  cellspacing="0"  >
						<tr>
							<th style="width:180px;"><%=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>
							</td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.adptrbzwkname")%></th><td ><input type="text" name="ADPTRBZWKNAME" readonly/> </td>
							<th style="width:180px;"><%=localeMessage.getString("adapterDetail.eaisevrinstncname")%></th>
							<td >
								<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" readonly/> </td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.testclsname")%></th><td colspan="3"><input type="text" name="TESTCLSNAME" readonly/> </td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("adapterDetail.adptrdesc")%></th><td colspan="3"><input type="text" name="ADPTRDESC" readonly/> </td>
						</tr>
						<tr style="display:none" >
							<th><%=localeMessage.getString("adapterDetail.prptygroupname")%></th><td colspan="3"><input type="text" name="PRPTYGROUPNAME" readonly/> </td>
						</tr>
						<tr style="display:none" >
							<th><%=localeMessage.getString("adapterDetail.prptygroupdesc")%></th><td colspan="3"><input type="text" name="PRPTYGROUPDESC" readonly/> </td>
						</tr>
					</table>
					
					<div class="table_row_title">
						<table><tr><td class="table_row_title"><%= localeMessage.getString("adapterDetail.title4")%> </td>
						<td>&nbsp;</td>
						<td>
						<img id="btn_modify" src="<c:url value="/img/btn_pop_modify.png" />"  level="W" status="DETAIL,NEW" class="btn_img" />
						</td></tr></table>		
					</div>
					<!-- <table id="detail" class="table_row"  cellspacing="0"  >
						<tr>
							<th style="width:180px;">APP_CODE</th>
							<td><textarea name="APP_CODE" id="APP_CODE" style="height:80px;" readonly></textarea></td>
						</tr>
					</table> -->
					
					<!-- grid -->
					 <table id="grid" ></table>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->	
	</body>
</html>

