/**
 * admin/api
 */
var mplus_admin_api = function() {
	// 상속
	mplus_admin.call(this);

	var self = this;
	// 변수
	var $wrapper = $('.main-wrapper #wrapper'),
		$txtId = $('#txtId'), 
		$txtName = $('#txtName'), 
		$spanCatPathName = $('#spanCatPathName'), 
		$txtApiUrl = $('#txtApiUrl'), 
		$sltApiType = $('#sltApiType'), 
		$btnApiTypeHelp = $('#btnApiTypeHelp'), 
		$sltHttpMethodType = $('#sltHttpMethodType'), 
		$sltResultType = $('#sltResultType'), 
		$sltDataSourceName = $('#sltDataSourceName'), 
		$txtTargetUrlAddr = $('#txtTargetUrlAddr'), 
		$txtQueryMsg = $('#txtQueryMsg'), 
		$txtProcedure = $('#txtProcedure'), 
		$btnCreateNode = $('#btnCreateNode'), 
		$btnRemoveNode = $('#btnRemoveNode'), 
		$btnSaveNode = $('#btnSaveNode'), 
		$btnCacheInit = $('#btnCacheInit'), 
		$btnDeselectNode = $('#btnDeselectNode'), 
		$btnHeaderInfo = $('#btnHeaderInfo'), 
		$btnNewItemHeader = $('#btnNewItem_header'), 
		$btnConfirmHeader = $('#btnConfirmItem_header'), 
		$btnParameter = $('#btnParameter'), 
		$btnNewItemParam = $('#btnNewItem_param'), 
		$btnConfirmParam = $('#btnConfirmItem_param'),
		$txtResSampleCl = $('#txtResSampleCl'), 
		$txtApiDesc = $('#txtApiDesc'), 
		$spanCreateDt = $('#spanCreateDt'), 
		$spanCreateId = $('#spanCreateId'), 
		$spanUpdateDt = $('#spanUpdateDt'), 
		$spanUpdateId = $('#spanUpdateId'), 
		$crudServiceBaseUrl = contextPath + '/admin/api';

	this.treeView = null;
	/**
	 * 초기화
	 */
	this.init = function() {
		initTree();
		// 설명 글자수 이벤트 - core에 선언
		self.checkDescBytes($txtApiDesc, 'txtApiDesc');
		addEvent();

	};
	/**
	 * 이벤트 등록
	 */
	var addEvent = function() {
		// api type 변경 이벤트
		$sltApiType.on('change', function(e) {
			/*
			 * var treeView = self.treeView; var node = treeView.select(), item =
			 * treeView.dataItem(node), observer = new kendo.observable( item );
			 */

			enableApiTypeRow(this.value);
			httpMethodType($sltHttpMethodType.val(), e);
		});

		// http method 필드 변경 이벤트
		$sltHttpMethodType.on('change', function(e) {
			httpMethodType(this.value, e);
		});

		// 아이템 추가
		$btnCreateNode.on('click', function(e) {
			addItem(e);
		});

		// 아이템 삭제
		$btnRemoveNode.on('click', function(e) {
			removeItem(e);
		});

		// 아이템 저장
		$btnSaveNode.on('click', function(e) {
			saveItem(e);
		});

		// 아이템 갱신 (to 모바일 서버)
		$btnCacheInit.on('click', function(e) {
			reloadItem(e);
		});

		$('#btnTest, #btnTest_inModal').on('click', function(e) {
			testApi(e);
		});

		// 아이템 선택 해제
		$btnDeselectNode.on('click', function(e) {
			deselectItem(e);
		});
		$btnHeaderInfo.on('click', function(e) {
			editTableHeaderInfo(e);
		});
		$btnNewItemHeader.on('click', function(e) {
			newTableHeader(e);
		});
		$btnConfirmHeader.on('click', function(e) {
			confirmTableHeader(e);
		});
		$btnParameter.on('click', function(e) {
			editTableParam(e);
		});
		$btnNewItemParam.on('click', function(e) {
			newTableParam(e);
		});
		$btnConfirmParam.on('click', function(e) {
			confirmTableParam(e);
		});
	};
	/**
	 * http method 필드 변경 이벤트
	 */
	var httpMethodType = function(value, e) {

		var node = $('#apiTreeView').fancytree('getActiveNode'), 
			item = $('#apiTreeView').fancytree('getActiveNode').data;
		var apiType = $('#sltApiType').val();

		if (apiType === 'SQL') {
			if (value !== 'GET' && value !== '') {
				// POST,PUT,DELETE 라면 INT만
				$('#sltResultType option').hide();
				$('#sltResultType option[value=INT]').show();
				$('#sltResultType').val('INT');
			} else {
				// GET 이면 MAP, LIST만
				$('#sltResultType option').hide();
				$('#sltResultType option[value=MAP]').show();
				$('#sltResultType option[value=LIST]').show();
				$('#sltResultType').val('MAP');
			}
		} else {
			// 웹서비스, procedure면 전부다
			$('#sltResultType option').show();
			$('#sltResultType').val('MAP');
		}
	};
	/**
	 * 아이템 추가
	 */
	var addItem = function(e) {
		var node = $('#apiTreeView').fancytree('getActiveNode'), // 부모노드 추출에 사용될 예정
			selectNode = $('#apiTreeView').fancytree('getActiveNode');
		if(node==undefined){
			alert('카테고리를 선택해주세요.');
			return false;
		};
		if(node.expanded==undefined){
			$('#apiTreeView').fancytree('getActiveNode').setExpanded();
		};
		
		var item = $('#apiTreeView').fancytree('getActiveNode').data;
		
		if (addedNodeArr.length > 0) {
			alert('저장하지 않은 아이템이 있습니다');
			return false;
		};

		if (node.length === 0) {
			alert('아이템을 선택하세요');
			return false;
		}
		if (item.nodeType === 'API') {
			alert('카테고리를 선택하여 추가하세요.');
			return false;
		}
		var cat_seq = item.catSeq;
		var cat_name = item.catName;

		var arr = new Array();

		arr.push(item.pathName);
		while (node.parent) {
			node = node.parent.data;
			if(node.pathName!=null) arr.push(node.pathName);
		}

		var cat_path_name = '/';
		for (var n = arr.length; n > 0; n--) {
			cat_path_name += (arr[n - 1] + '/');
		}

		var nodeData = null, 
		defData = {
				apiSeq : '',
				apiName : 'New api',
				nodeType : 'API',
				addedNode : true,
				apiType : $('#sltApiType').val(),
				catSeq : cat_seq,
				catName : cat_name,
				catPathName : cat_path_name,
				dataSourceName : '',
				apiDesc : '',
				httpMethodType : '',
				targetName : '',
				queryMsg : '',
				resultType : '',
				reqUrlAddr : '',
				reqUrlName : '',
				targetUrlAddr : '',
				useYn : 1,
				reqParams : [],
				wsUrl : '',
				wsHeaders : [],
				resSampleCl : ''
			};
		
		selectNode.addChildren({
			title : defData.apiName,
			key : defData.id,
			folder : false,
			lazy : false,
			data : defData
		});
		addedNodeArr.push(defData);
		$('#apiTreeView').fancytree('getActiveNode').children[$('#apiTreeView')
				.fancytree('getActiveNode').children.length - 1].li.click();
		
		$('#txtName').focus();
	};
	/**
	 * 아이템 삭제
	 */
	var removeItem = function(e) {
		var node = $('#apiTreeView').fancytree('getActiveNode'),
	    item = $('#apiTreeView').fancytree('getActiveNode').data;
				
		if (node.length === 0) {
			alert('선택한 아이템이 없습니다');
			return false;
		}
		if (item.nodeType === 'CATEGORY') {
			alert('카테고리는 카테고리 관리에서 삭제가능합니다.');
			return false;
		}
		if (item.addedNode) {
			node.remove();
			addedNodeArr = [];
			$('#apiMsg').css('display', 'block');
			$('#apiContent').css('display', 'none');
			return false;
		}
		if (item.childCount > 0) {
			alert('하위 카테고리가 존재하여 삭제할 수 없습니다');
			return false;
		}

		if (item.apiCount > 0) {
			alert('하위 API가 존재하여 삭제할 수 없습니다');
			return false;
		}

		if (!confirm('삭제 하시겠습니까?')) {
			return false;
		}

		var opt = {
			url : $crudServiceBaseUrl + '/remove.json',
			data : self.util.stringifyJson({
				apiSeq : item.id
			}),
			type : 'POST'
		};
		var success = function(data) {
			alert('삭제 되었습니다.');
			$('#apiTreeView').fancytree('getActiveNode').remove();
			/*location.reload(true);*/
		};
		var error = function(xhr, d, t) {
			console.log(xhr);
			alert(xhr.responseText);
		};
		self.ajaxAdmin(opt, success, error);
	};
	/**
	 * 아이템 저장
	 */
	var saveItem = function(e) { 
		var treeView = self.treeView;

		var item = $('#apiTreeView').fancytree('getActiveNode');

		if (item.length === 0 || item.data.nodeType === 'CATEGORY') {
			alert('선택한 아이템이 없습니다');
			return false;
		};
		
		var reqParamsArr = paramList;

		for (var i = 0; i < reqParamsArr.length; i++) {
			var it = reqParamsArr[i], 
				paramName = it.paramName;

			reqParamsArr[i].paramName = paramName.replace(/\s/gi, '');
			reqParamsArr[i].apiSeq = item.data.apiSeq;
		};
		
		var reqHeaderArr = headerList;

		for (var i = 0; i < reqHeaderArr.length; i++) {
			var it = reqHeaderArr[i];
			
			reqHeaderArr[i].apiSeq = item.data.apiSeq;
		};
		
		var param = $.extend(true, {}, item.data, {
			apiName: $txtName.val(),
			apiType: $sltApiType.val(),
			apiDesc: $txtApiDesc.val(),
			httpMethodType: $sltHttpMethodType.val(),
			queryMsg: $txtQueryMsg.val(),
			resSampleCl: $txtResSampleCl.val(),
			reqUrlAddr: $txtApiUrl.val(),
			resultType: $sltResultType.val(),
			targetUrlAddr: $txtTargetUrlAddr.val(),
			targetName : $txtProcedure.val(),
			dataSourceName: $sltDataSourceName.val(),
			nodeType : 'API',
			reqParams : reqParamsArr,
			wsHeaders : reqHeaderArr
		}, null);
		
		if (!fieldValidation(param)) {
			return false;
		}

		var opt = {
			url : $crudServiceBaseUrl + '/save.json',
			data : self.util.stringifyJson(param),
			type : 'POST',
			dataType : 'json',
			contentType : 'application/json;charset=UTF-8;'
		};
		var success = function(data) {
			alert('저장 되었습니다.');
			addedNodeArr = [];
			var saveItemData = $('#apiTreeView').fancytree('getActiveNode');
			$('#title'+saveItemData.key).text(data.apiName);
			saveItemData.data = data;
			saveItemData.data.id = data.apiSeq;
			saveItemData.data.name = data.apiName;
			/*location.reload(true);*/
		};
		var error = function(xhr, d, t) {
			console.log(xhr);
			alert(xhr.responseText);
		};
		self.ajaxAdmin(opt, success, error);
	};
		
	/**
	 * 트리 아이템 reload 이벤트
	 * 
	 * @private
	 */
	var reloadItem = function(e) {
		var opt = {
			url : $crudServiceBaseUrl + '/cacheReload.json',
			type : 'POST',
			contentType : 'application/json; charset=UTF-8'
		};
		var success = function(data) {
			if (data === 1) {
				alert('갱신 되었습니다');
			} else {
				alert('수행 중 에러가 발생하였습니다');
			}
		};
		var error = function(xhr, d, t) {
			console.log(xhr);
			console.log(t);
		};
		self.ajaxAdmin(opt, success, error);
	};
	/**
	 * 트리 아이템 선택 해제 이벤트
	 * @private
	 */
	var deselectItem = function(e){
		var node = $('#apiTreeView').fancytree('getActiveNode');
		if(node!=undefined){
			node.setActive(false);
			node.setFocus(false);
			
			$('#apiMsg').css('display', 'block');
			$('#apiContent').css('display', 'none');
		};
	};
	
	/**
	 * 실행 테스트 이벤트
	 */
	var testApi = function(e) {
		var node = $('#apiTreeView').fancytree('getActiveNode'),
		item = $('#apiTreeView').fancytree('getActiveNode').data;

		var reqParamsArr = [];
		if(e.currentTarget.id=='btnTest'){
			$.extend(reqParamsArr, paramList); // 객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		}else if(e.currentTarget.id=='btnTest_inModal'){
			$.extend(reqParamsArr, paramEditList); // 객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		};
		
		if (item.dataSourceName !== null
				&& typeof item.dataSourceName === 'object'
				&& item.dataSourceName.value !== undefined) {
			item.dataSourceName = item.dataSourceName.value;
		};
		
		for (var i = 0; i < reqParamsArr.length; i++) {
			var it = reqParamsArr[i], 
				paramName = it.paramName,
				paramSeq = it.paramSeq;

			reqParamsArr[i].paramName = paramName.replace(/\s/gi, '');
			reqParamsArr[i].paramSeq = paramSeq!=null&&typeof(paramSeq)!="number" && paramSeq.indexOf('new_')>-1 ? null: paramSeq;
		};
		
		var param = $.extend(true, {}, item.data, {
			apiName: $txtName.val(),
			apiType: $sltApiType.val(),
			apiDesc: $txtApiDesc.val(),
			httpMethodType: $sltHttpMethodType.val(),
			queryMsg: $txtQueryMsg.val(),
			resSampleCl: $txtResSampleCl.val(),
			reqUrlAddr: $txtApiUrl.val(),
			resultType: $sltResultType.val(),
			targetUrlAddr: $txtTargetUrlAddr.val(),
			targetName : $txtProcedure.val(),
			dataSourceName: $sltDataSourceName.val(),
			nodeType : 'API',
			reqParams : reqParamsArr,
			wsHeaders : headerList
		}, null);
		

		var opt = {
			beforeSend: function(){
				self.loading('show');
			},
			url : $crudServiceBaseUrl + '/test.json',
			data : JSON.stringify(param),
			type : 'POST',
			dataType: 'json',
    		contentType : 'application/json; charset=UTF-8;',
    		complete: function(){
    			self.loading('hide');
    		}
		};
		var success = function(data) {
			if ($.isEmptyObject(data)) {
				alert('테스트에 대한 결과 데이터가 없습니다.');
				return false;
			}

			var responseData = self.util.stringifyJson(data, null, 2);

			$('#modal_testResult .modal-body').empty();
			$('#modal_testResult .modal-body').append(
					$('<pre style="height: 500px;"></pre>').html(responseData));
			$('#modal_testResult').modal('show');
		};
		var error = function(xhr, d, t) {
			console.log(xhr);
			alert('[' + xhr.statusText + '] ' + xhr.responseText);
		};
		
		self.ajaxAdmin(opt, success, error);
	};
	/**
	 * 트리 초기화
	 */
	var createDeptNodeData = function(data) {
		return $.extend({
			title : data.name,
			key : data.id,
			folder : data.nodeType == 'CATEGORY' ? true : false,
			lazy : data.nodeType == 'CATEGORY' ? true : false,
			data : data
		}, data.data);
	};

	var initTree = function() {
		var $tree = $('#apiTreeView').fancytree(
				{
					extensions : [ 'edit' ],
					lazyLoad : function(event, ctx) {
						var param_lazyload = {
							async : false,
							url : $crudServiceBaseUrl + '/getList.json',
							dataType : 'json',
							type : 'POST',
							data : self.util.stringifyJson({
								catSeq : ctx.node.data.catSeq
							})
						};
						result = [];
						var success_lazyload = function(data) {
							apiList = data;

							for ( var i in apiList) {
								var item = apiList[i];
								result.push(createDeptNodeData(item));
							}
							;
							ctx.result = result;

						};
						var error_lazyload = function(xhr, d, t) {
							console.log(xhr);
							console.log(t);
						};
						self.ajaxAdmin(param_lazyload, success_lazyload,
								error_lazyload);

					},
					selectMode : 3,
					activate : function(event, ctx) {
						var apiData = ctx.node.data;
						if(apiData.nodeType=='CATEGORY'){
							$('#apiMsg').css('display', 'block');
							$('#apiContent').css('display', 'none');
						}else{
							$('#apiMsg').css('display', 'none');
							$('#apiContent').css('display', 'block');
							
							if (apiData.apiSeq == undefined || apiData.apiSeq == '') {
								$txtId.val('');
								$txtName.val('');
								$spanCatPathName.text(apiData.catPathName);
								$txtApiUrl.val('');
								$sltApiType.val('');
								enableApiTypeRow(apiData.apiType);
								$sltHttpMethodType.val('');
								$sltResultType.val('');
								$sltDataSourceName.val('');
								$txtTargetUrlAddr.val('');
								$txtResSampleCl.val('');
								$txtApiDesc.val('');
								$spanCreateDt.text('');
								$spanCreateId.text('');
								$spanUpdateDt.text('');
								$spanUpdateId.text('');
								$txtQueryMsg.val('');
								$txtProcedure.val('');
								paramList = [];
								headerList = [];
								paramEditList = [];
								headerEditList = [];	
								$('#table_header_view').empty();
								$('#table_param_view').empty();
							} else {
								var opt = {
			            				url : $crudServiceBaseUrl + "/getApi.json",
			            				type : "POST",
			            				data : self.util.stringifyJson( {'apiSeq': apiData.apiSeq} ),
			            				dataType : "json",
			            				contentType : "application/json;charset=utf-8"
			                	};
			                	var success = function(data){
			                		$txtId.val(data.apiSeq);
									$txtName.val(data.apiName);
									$spanCatPathName.text(data.catPathName);
									$txtApiUrl.val(data.reqUrlAddr);
									$sltApiType.val(data.apiType);
									enableApiTypeRow(data.apiType);
									$sltHttpMethodType.val(data.httpMethodType);
									$sltResultType.val(data.resultType);
									$sltDataSourceName.val(data.dataSourceName);
									$txtTargetUrlAddr.val(data.targetUrlAddr);
									$txtResSampleCl.val(data.resSampleCl);
									$txtApiDesc.val(data.apiDesc);
									$spanCreateDt.text(moment(data.createDt).format(
											'YYYY-MM-DD'));
									$spanCreateId.text(data.createId==null? '': data.createId);
									$spanUpdateDt.text(moment(data.updateDt).format(
											'YYYY-MM-DD'));
									$spanUpdateId.text(data.updateId==null? '': data.updateId);
									$txtQueryMsg.val(data.queryMsg);
									$txtProcedure.val(data.targetName);
									initGrid(data.apiSeq);
			                	};
			                	var error = function(xhr,d,t){
			                		console.log(xhr);
			            			console.log(xhr.responseText);
			                	};
			                	self.ajaxAdmin( opt, success, error );
							};

							// 설명 글자수제한 초기화
							$txtApiDesc.trigger('keyup');
						}
					},
					click : function(event, data) {
					},
				}).fancytree('getTree');
		var apiList;
		$.ajax({
			async : false,
			url : $crudServiceBaseUrl + '/getList.json',
			dataType : 'json',
			type : 'POST',
			contentType : 'application/json',
			data: JSON.stringify({}),
			success : function(result) {
				apiList = result;
			}
		});

		var $root = $tree.getRootNode();
		for ( var i in apiList) {
			var item = apiList[i];
			$root.addNode(createDeptNodeData(item));
		}

	};
	var paramList = [];
	var headerList = [];
	var paramEditList = [];
	var headerEditList = [];	

	/**
	 * 그리드 초기화
	 */
	var initGrid = function(apiSeq) {
		// 헤더 테이블
		var opt_header = {
			url : $crudServiceBaseUrl + '/getHeaderList.json',
			type : 'POST',
			dataType : 'json',
			data : self.util.stringifyJson({
				'apiSeq' : apiSeq
			}),
			contentType : 'application/json; charset=UTF-8'
		};
		var success_header = function(data) {
			$('#table_header_view').empty();
			headerList = data;
			for (var i = 0; i < headerList.length; i++) {
				var tr = $('<tr></tr>').clone();
				var tdName = $('<td></td>').clone().text(headerList[i].headerName);
				var tdValue = $('<td></td>').clone().text(headerList[i].headerValue==null? '': self.util.getBytes(headerList[i].headerValue)>20? self.util.cut(headerList[i].headerValue, 20)+'...': headerList[i].headerValue);

				$('#table_header_view').append(tr.append(tdName).append(tdValue));
			};
		};
		var error_header = function(xhr, d, t) {
			console.log(xhr);
			console.log(t);
		};
		self.ajaxAdmin(opt_header, success_header, error_header);

		// 파라미터 테이블
		var opt_param = {
			url : $crudServiceBaseUrl + '/getParamList.json',
			type : 'POST',
			dataType : 'json',
			data : self.util.stringifyJson({
				'apiSeq' : apiSeq
			}),
			contentType : 'application/json; charset=UTF-8'
		};
		var success_param = function(data) {
			paramList = data;
			$('#table_param_view').empty();

			for (var i = 0; i < paramList.length; i++) {
				var tr = $('<tr></tr>').clone();
				var tdNo = $('<td></td>').clone().text(i+1);
				var tdName = $('<td></td>').clone().text(paramList[i].paramName);
				var tdType = $('<td></td>').clone().text(paramList[i].dataType);
				var tdValue = $('<td></td>').clone().text(paramList[i].sampleValue==null? '': self.util.getBytes(paramList[i].sampleValue)>10? self.util.cut(paramList[i].sampleValue, 10)+'...': paramList[i].sampleValue);
				var tdDesc = $('<td></td>').clone().text(paramList[i].paramDesc==null? '': self.util.getBytes(paramList[i].paramDesc)>20? self.util.cut(paramList[i].paramDesc, 20)+'...': paramList[i].paramDesc);

				$('#table_param_view').append(tr.append(tdNo).append(tdName).append(tdType).append(tdValue).append(tdDesc));
			};
		};
		var error_param = function(xhr, d, t) {
			console.log(xhr);
			console.log(t);
		};
		self.ajaxAdmin(opt_param, success_param, error_param);
	};

	// 저장하지 않은 아이템 배열
	var addedNodeArr = [];

	/**
	 * api type 변경 처리
	 */
	function enableApiTypeRow(typeName) {
		if (typeName === 'WEB_SERVICE') {
			$('#rowWebService').show();
			$('#rowProcedure').hide();
			$('#rowQueryMsg').hide();			
		} else if (typeName === 'SQL') {
			$('#rowWebService').hide();
			$('#rowProcedure').hide();
			$('#rowQueryMsg').show();
		} else if (typeName === 'PROCEDURE') {
			$('#rowWebService').hide();
			$('#rowProcedure').show();
			$('#rowQueryMsg').hide();
		} else{
			$('#rowWebService').hide();
			$('#rowProcedure').hide();
			$('#rowQueryMsg').hide();
		}
	}

	/**
	 * 필수값 체크
	 */
	function fieldValidation(item) {
		if (item.apiName === '') {
			alert('이름을 입력하세요');
			return false;
		}
		if (item.reqUrlAddr === '') {
			alert('API URI를 입력하세요');
			return false;
		}
		if (item.apiType === '') {
			alert('API 타입을 선택하세요');
			return false;
		}
		if (item.httpMethodType === '') {
			alert('HttpMethod 타입을 선택하세요');
			return false;
		} else {
			if (item.httpMethodType === 'GET' && item.resultType === 'INT') {
				alert('HttpMethod 타입이 GET일 경우 응답결과가 [INT] 일 수 없습니다');
				return false;
			}
		}
		if (item.resultType == '') {
			alert('응답결과 타입을 선택하세요');
			return false;
		} else {
			if (item.apiType === 'WEB_SERVICE') {
				if (item.targetUrlAddr === '') {
					alert('URL을 등록하세요');
					return false;
				}
				if (item.resultType === 'POST' || item.resultType === 'DELETE') {
					alert('웹서비스는 POST, DELETE 타입을 지원하지 않습니다');
					return false;
				}
			} else {
				if (item.dataSourceName === '') {
					alert('데이터소스를 선택하세요');
					return false;
				}
				if (item.apiType === 'PROCEDURE') {
					if (item.targetName === '') {
						alert('Procedure를 등록하세요');
						return false;
					}
				} else { // SQL, MYBATIS, SQL_GROOVY_TEMPLATE, VELOCITY
					if (item.queryMsg === '') {
						alert('SQL을 등록하세요');
						return false;
					}
				}
			}
		}
		if (item.resultType === '') {
			alert('응답결과 타입을 선택하세요');
			return false;
		}
		return true;
	};
	
	var getItemData = function(itemList, tableCheckValue, checkValue){
		var itemData = {};
		for(i=0; i<itemList.length; i++){
			if(itemList[i][tableCheckValue] == checkValue){
				itemData = itemList[i];
				break;
			}
		};
		return itemData;
	};

	var editTableHeaderInfo = function() {
		$('#sltHeader').val($('#sltHeader option:first').val());
		$('#txtHeaderValue').val('');

		$('#table_header').empty();
		for (var i = 0; i < headerList.length; i++) {
			var tr = $('<tr itemData="'+ headerList[i].headerName +'"></tr>').clone();
			var tdName = $('<td></td>').clone().text(headerList[i].headerName);
			var tdValue = $('<td></td>').clone().addClass('max-width-sm').text(headerList[i].headerValue==null? '': self.util.getBytes(headerList[i].headerValue)>10? self.util.cut(headerList[i].headerValue, 10)+'...': headerList[i].headerValue);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + headerList[i].headerName
							+ '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_header').append(tr.append(tdName).append(tdValue).append(tdEdit));
		};

		$('#table_header tr').unbind();
		$('#table_header tr').on('click', function(e) {
			editItemHeader(e);
			$('#table_header tr').removeClass('active');
			$(this).addClass('active');
		});
		$('#table_header tr td button').unbind();
		$('#table_header tr td button').on('click', function(e) {
			removeItemHeader(e);
		});
		/* i18nEditList = i18nList; */
		headerEditList = [];
		$.extend(headerEditList, headerList); // 객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		$('#addItemModal_header').modal('show');
		
		$('#saveItem_header').unbind();
		$('#saveItem_header').on('click', function() {
			var param = {
				'headerSeq' : null,
				'headerName' : $('#sltHeader').val(),
				'headerValue' : $('#txtHeaderValue').val()
			};
			saveItemHeader(param, 'new');
		});
		if($('#table_header tr').length>0){
			$('#table_header tr')[0].click();
			$('#modalHeaderDetail').css('display', 'block');
			$('#modalHeaderDetailEmpty').css('display', 'none');
		}else{
			$('#modalHeaderDetail').css('display', 'none');
			$('#modalHeaderDetailEmpty').css('display', 'block');
		}
	};

	var newTableHeader = function() {
		$('#sltHeader').val($('#sltHeader option:first').val());
		$('#txtHeaderValue').val('');
		$('#table_header tr').removeClass('active');
		$('#modalHeaderDetail').css('display', 'block');
		$('#modalHeaderDetailEmpty').css('display', 'none');
		
		$('#sltHeader').focus();

		$('#saveItem_header').unbind();
		$('#saveItem_header').on('click', function() {
			var param = {
				'headerSeq' : null,
				'headerName' : $('#sltHeader').val(),
				'headerValue' : $('#txtHeaderValue').val()
			};
			saveItemHeader(param, 'new');
		});
	};

	var saveItemHeader = function(param, newYn) {
		if($('#table_header tr[class!="active"][itemData="'+param.headerName+'"]').length>0){
			alert('헤더명은 중복될 수 없습니다.');
			return;
		};
		
		if(param.headerValue==null || param.headerValue==''){
			alert('값을 입력해주세요.');
			return;
		};
		
		if(newYn=='edit'){	
			olderValue = $('#table_header tr.active')[0].attributes.itemData.value;
			$('#table_header tr[itemData="'+olderValue+'"]')[0].children[0].innerText=param.headerName;
			$('#table_header tr[itemData="'+olderValue+'"]')[0].children[1].innerText=param.headerValue;
			$('#table_header tr[itemData="'+olderValue+'"]')[0].children[2].children[0].attributes.itemData.value=param.headerName;
			$('#table_header tr[itemData="'+olderValue+'"]')[0].attributes.itemdata.value=param.headerName;
			for(var i=0; i<headerEditList.length; i++){
				if(headerEditList[i].headerName==olderValue){
					headerEditList[i].headerName = param.headerName;
					headerEditList[i].headerValue = param.headerValue;
				}
			};
		}else{
			var tr = $('<tr itemData="'+ param.headerName +'"></tr>').clone();
			var tdName = $('<td></td>').clone().text(param.headerName);
			var tdValue = $('<td></td>').clone().addClass('max-width-sm').text(param.headerValue==null? '': self.util.getBytes(param.headerValue)>10? self.util.cut(param.headerValue, 10)+'...': param.headerValue);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + param.headerName + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_header').append(tr.append(tdName).append(tdValue).append(tdEdit));
			
			headerEditList.push(param);
		};
		
		$('#table_header tr').unbind();
		$('#table_header tr').on('click', function(e) {
			editItemHeader(e);
			$('#table_header tr').removeClass('active');
			$(this).addClass('active');
		});

		$('#table_header tr td button').unbind();
		$('#table_header tr td button').on('click', function(e) {
			removeItemHeader(e);
		});
		
		$('#table_header tr[itemData="'+ param.headerName +'"]').click(); 
	};

	var editItemHeader = function(e) {		
		var itemData = getItemData(headerEditList, 'headerName', e.currentTarget.attributes.itemData.value);
		if(itemData==undefined || itemData ==null){
			alert('정상적인 데이터가 아닙니다.'); //이표시가 맞을까?
			return;
		};
		
		$('#sltHeader').val(itemData.headerName);
		$('#txtHeaderValue').val(itemData.headerValue);

		$('#saveItem_header').unbind();
		$('#saveItem_header').on('click', function() {
			var param = {
				'headerSeq' : itemData.headerSeq,
				'headerName' : $('#sltHeader').val(),
				'headerValue' : $('#txtHeaderValue').val()
			};
			saveItemHeader(param, 'edit');
		});
		
		$('#modalHeaderDetail').css('display', 'block');
		$('#modalHeaderDetailEmpty').css('display', 'none');
	};

	var removeItemHeader = function(e) {
		$('#table_header tr[itemData="'+e.currentTarget.attributes.itemData.value+'"]').remove();
		
		for(var i=0; i<headerEditList.length; i++){
			if(headerEditList[i].headerName == e.currentTarget.attributes.itemData.value){
				headerEditList.splice(i, 1);
				break;
			}
		};
		
		$('#table_header tr').removeClass('active');
		
		$('#modalHeaderDetail').css('display', 'none');
		$('#modalHeaderDetailEmpty').css('display', 'block');
		
	};

	var confirmTableHeader = function(e) {
		$('#addItemModal_header').modal('hide');
		$('#table_header_view').empty();

		for (var i = 0; i < headerEditList.length; i++) {
			var tr = $('<tr>').clone();
			var tdName = $('<td></td>').clone().text(headerEditList[i].headerName);
			var tdValue = $('<td></td>').clone().text(headerEditList[i].headerValue==null? '': self.util.getBytes(headerEditList[i].headerValue)>20? self.util.cut(headerEditList[i].headerValue, 20)+'...': headerEditList[i].headerValue);

			$('#table_header_view').append(tr.append(tdName).append(tdValue));
		}
		;
		headerList = [];
		$.extend(headerList, headerEditList); // 객체 복사
	};

	var editTableParam = function() {
		$('#txtParam').val('');
		$('#sltParam').val($('#sltParam option:first').val());
		$('#txtSampleParam').val('');
		$('#txtParamDesc').val('');

		$('#table_param').empty();
		for (var i = 0; i < paramList.length; i++) {
			var tr = $('<tr itemData="' + paramList[i].paramName + '"></tr>').clone();
			var tdName = $('<td></td>').clone().text(paramList[i].paramName);
			var tdSampleValue = $('<td></td>').clone().text(paramList[i].sampleValue==null? '': self.util.getBytes(paramList[i].sampleValue)>10? self.util.cut(paramList[i].sampleValue, 10)+'...': paramList[i].sampleValue);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + paramList[i].paramName + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_param').append(tr.append(tdName).append(tdSampleValue).append(tdEdit));
		};

		$('#table_param tr').unbind();
		$('#table_param tr').on('click', function(e) {
			editItemParam(e);
			$('#table_param tr').removeClass('active');
			$(this).addClass('active');
		});
		$('#table_param tr td button').unbind();
		$('#table_param tr td button').on('click', function(e) {
			removeItemParam(e);
		});
		/* i18nEditList = i18nList; */
		paramEditList = [];
		$.extend(paramEditList, paramList); // 객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		$('#addItemModal_param').modal('show');
		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function() {
			var param = {
				'paramSeq' : null,
				'paramName' : $('#txtParam').val(),
				'dataType' : $('#sltParam').val(),
				'sampleValue' : $('#txtSampleParam').val(),
				'paramDesc' : $('#txtParamDesc').val()
			};
			saveItemParam(param, 'new');
		});
		if($('#table_param tr').length>0){
			$('#table_param tr')[0].click();
			$('#modalParamDetail').css('display', 'block');
			$('#modalParamDetailEmpty').css('display', 'none');
		}else{
			$('#modalParamDetail').css('display', 'none');
			$('#modalParamDetailEmpty').css('display', 'block');
		};
	};

	var newTableParam = function() {
		$('#txtParam').val('');
		$('#sltParam').val($('#sltParam option:first').val());
		$('#txtSampleParam').val('');
		$('#txtParamDesc').val('');
		$('#table_param tr').removeClass('active');
		
		$('#modalParamDetail').css('display', 'block');
		$('#modalParamDetailEmpty').css('display', 'none');

		$('#txtParam').focus();
		
		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function() {
			var param = {
				'paramSeq' : null,
				'paramName' : $('#txtParam').val(),
				'dataType' : $('#sltParam').val(),
				'sampleValue' : $('#txtSampleParam').val(),
				'paramDesc' : $('#txtParamDesc').val()
			};
			saveItemParam(param, 'new');
		});
	};

	var saveItemParam = function(param, newYn) {
		if(param.paramName==null || param.paramName==''){
			alert('이름을 입력해주세요.');
			return;
		};
		if($('#table_param tr[class!="active"][itemData="'+param.paramName+'"]').length>0){
			alert('파라미터명은 중복될 수 없습니다.');
			return;
		};
		
		if(param.dataType==null || param.dataType==''){
			alert('타입을 선택해주세요.');
			return;
		};
		
		if(newYn=='edit'){	
			olderValue = $('#table_param tr.active')[0].attributes.itemData.value;
			$('#table_param tr[itemData="'+olderValue+'"]')[0].children[0].innerText=param.paramName;
			$('#table_param tr[itemData="'+olderValue+'"]')[0].children[1].innerText=param.sampleValue;
			$('#table_param tr[itemData="'+olderValue+'"]')[0].children[2].children[0].attributes.itemData.value=param.paramName;
			$('#table_param tr[itemData="'+olderValue+'"]')[0].attributes.itemdata.value=param.paramName;
			for(var i=0; i<paramEditList.length; i++){
				if(paramEditList[i].paramName==olderValue){
					paramEditList[i].paramName = param.paramName;
					paramEditList[i].dataType = param.dataType;
					paramEditList[i].sampleValue = param.sampleValue;
					paramEditList[i].paramDesc = param.paramDesc;
				}
			};
		}else{
			var tr = $('<tr itemData="'+ param.paramName +'"></tr>').clone();
			var tdName = $('<td></td>').clone().text(param.paramName);
			var tdValue = $('<td></td>').clone().addClass('max-width-sm').text(param.sampleValue==null? '': self.util.getBytes(param.sampleValue)>10? self.util.cut(param.sampleValue, 10)+'...': param.sampleValue);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + param.paramName + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_param').append(tr.append(tdName).append(tdValue).append(tdEdit));
			
			paramEditList.push(param);
		};
		
		$('#table_param tr').unbind();
		$('#table_param tr').on('click', function(e) {
			$('#table_param tr').removeClass('active');
			$(this).addClass('active');
			editItemParam(e);
		});
		$('#table_param tr td button').unbind();
		$('#table_param tr td button').on('click', function(e) {
			removeItemParam(e);
		});
		
		$('#table_param tr[itemData="'+ param.paramName +'"]').click(); 
	};

	var editItemParam = function(e) {
		var itemData = getItemData(paramEditList, 'paramName', e.currentTarget.attributes.itemData.value);
		if(itemData==undefined || itemData ==null){
			alert('정상적인 데이터가 아닙니다.'); //이표시가 맞을까?
			return;
		};
		$('#txtParam').val(itemData.paramName);
		$('#sltParam').val(itemData.dataType);
		$('#txtSampleParam').val(itemData.sampleValue==null? '': itemData.sampleValue);
		$('#txtParamDesc').val(itemData.paramDesc==null? '': itemData.paramDesc);

		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function() {
			var param = {
				'paramSeq' : itemData.paramSeq,
				'paramName' : $('#txtParam').val(),
				'dataType' : $('#sltParam').val(),
				'sampleValue' : $('#txtSampleParam').val(),
				'paramDesc' : $('#txtParamDesc').val()
			};
			saveItemParam(param, 'edit');
		});
		
		$('#modalParamDetail').css('display', 'block');
		$('#modalParamDetailEmpty').css('display', 'none');
	};

	var removeItemParam = function(e) {
		$('#table_param tr[itemData="'+e.currentTarget.attributes.itemData.value+'"]').remove();
		
		for(var i=0; i<paramEditList.length; i++){
			if(paramEditList[i].paramName == e.currentTarget.attributes.itemData.value){
				paramEditList.splice(i, 1);
				break;
			}
		};	
		
		$('#table_param tr').removeClass('active');
		
		$('#modalParamDetail').css('display', 'none');
		$('#modalParamDetailEmpty').css('display', 'block');
	};

	var confirmTableParam = function(e) {
		$('#addItemModal_param').modal('hide');
		$('#table_param_view').empty();

		for (var i = 0; i < paramEditList.length; i++) {
			var tr = $('<tr>').clone();
			var tdNo = $('<td></td>').clone().text(i+1);
			var tdName = $('<td></td>').clone().text(paramEditList[i].paramName);
			var tdType = $('<td></td>').clone().text(paramEditList[i].dataType);
			var tdValue = $('<td></td>').clone().text(paramEditList[i].sampleValue==null? '': self.util.getBytes(paramEditList[i].sampleValue)>10? self.util.cut(paramEditList[i].sampleValue, 10)+'...': paramEditList[i].sampleValue);
			var tdDesc = $('<td></td>').clone().text(paramEditList[i].paramDesc==null? '': self.util.getBytes(paramEditList[i].paramDesc)>20? self.util.cut(paramEditList[i].paramDesc, 20)+'...': paramEditList[i].paramDesc);

			$('#table_param_view').append(tr.append(tdNo).append(tdName).append(tdType).append(tdValue).append(tdDesc));
		};
		paramList = [];
		$.extend(paramList, paramEditList); // 객체 복사
	};
};
var rowNum = 0;
function resetRowNum() {
	rowNum = 0;
}
function getNum() {
	return ++rowNum;
}