/**
 * admin/menu
 */
var mplus_admin_menu = function( language_code ){
	//상속
	mplus_admin.call(this);
	
	var self = this;
	//언어코드
	var DEFAULT_LANGUAGE = language_code;
	
	//변수
	var $crudServiceBaseUrl = contextPath + '/admin/menu',
		$txtId = $('#txtId'),
		$txtMenu = $('#txtMenu'),
		$txtOrder = $('#txtOrder'),
		$sltMenuType = $('#sltMenuType'),
		$sltDisplay = $('#sltDisplay'),
		$txtPageUrl = $('#txtPageUrl'),
		$txtImageUrl = $('#txtImageUrl'),
		$txtMenuDesc = $('#txtMenuDesc'),
		$btnCreateNode = $('#btnCreateNode'),
		$btnCreateI18n = $('#btnCreateI18n'),
		$btnNewItemI18n = $('#btnNewItem_i18n'),
		$btnConfirmI18n = $('#btnConfirmItem_i18n'),
		$btnCreateParam = $('#btnCreateParam'),
		$btnNewItemParam = $('#btnNewItem_param'),
		$btnConfirmParam = $('#btnConfirmItem_param'),
		$btnCreateAuth = $('#btnCreateAuth'),
		$btnNewItemAuth = $('#btnNewItem_auth'),
		$btnConfirmAuth = $('#btnConfirmItem_auth'),
		$btnRemoveNode = $('#btnRemoveNode'),
		$btnSaveNode = $('#btnSaveNode'),
		$btnCacheInit = $('#btnCacheInit'),
		$btnDeselectNode = $('#btnDeselectNode'),
		$authCrudServiceBaseUrl = contextPath + "/admin/auth";		//속성 관련 요청을 위해 별도로 작성;
	
	var addedNodeArr = [];
		
	
	/**
	 * 객체 초기화
	 */
	this.init = function(){
		initTree();
		initDropDownList();
		//설명 글자수 이벤트 - core에 선언
		self.checkDescBytes($txtMenuDesc, 'txtMenuDesc');
		addEvent(); 
		/*if($("#menuTreeView .fancytree-expander")[0]!=undefined){
			$('#menuTreeView').fancytree('getTree').getNodeByKey($("#menuTreeView .fancytree-expander")[0].id).setActive();
		}else{*/
		$('#menuDetail').css('display', 'none');
		$('#menuDetailEmpty').css('display', 'block');
		/*};*/
	};
	
	
	/**
	 * 이벤트 등록
	 */
	var addEvent = function(){
	 	// 아이템 갱신 (to 모바일 서버)
	    $btnCacheInit.on("click",function(e) {
	    	reloadItem(e);
	    }); 
	    $btnCreateNode.on('click', function(e){
	    	addItem(e);
	    });
	    
	    $btnSaveNode.on("click",function(e) {
	    	saveItem(e);
	    });	    
	    
	    $btnRemoveNode.on("click",function(e) {
			removeItem(e);
	    }); 
	    
	    $btnDeselectNode.on("click",function(e) {
	    	deselectItem(e);
	    });
	    $btnCreateI18n.on("click",function(e) {
	    	editTableI18n(e);
	    });
	    $btnNewItemI18n.on("click", function(e){
	    	newTableI18n(e);
	    });
	    $btnConfirmI18n.on("click", function(e){
	    	confirmTableI18n(e);
	    });
	    $btnCreateParam.on("click",function(e) {
	    	editTableParam(e);
	    });
	    $btnNewItemParam.on("click", function(e){
	    	newTableParam(e);
	    });
	    $btnConfirmParam.on("click", function(e){
	    	confirmTableParam(e);
	    });
	    $btnCreateAuth.on("click",function(e) {
	    	editTableAuth(e);
	    });
	    $btnNewItemAuth.on("click", function(e){
	    	newTableAuth(e);
	    });
	    $btnConfirmAuth.on("click", function(e){
	    	confirmTableAuth(e);
	    });
	};
	/**
	 * 트리 아이템 신규 이벤트
	 * @private
	 */
	var addItem = function(e){        
        if($("#menuTreeView").fancytree("getActiveNode")!=null){
	        var node = $("#menuTreeView").fancytree("getActiveNode"),
			item = $("#menuTreeView").fancytree("getActiveNode").data;
	        
	        if(node.expanded==undefined){
				$("#menuTreeView").fancytree("getActiveNode").setExpanded();
			};
		}else{
			var node = $("#menuTreeView").fancytree("getRootNode");
		};
		
		if (addedNodeArr.length > 0) {
        	alert("저장하지 않은 아이템이 있습니다");
        	return false;
        };
    	
    	var nodeData = null,
    		defData = {
			menuType: "CONT",
 			menuName: "NewItem",
 			menuOrder: 0,
 			enabledYn: "Y",
 			accessUriAddr: "",
 			imageUriAddr: "",
 			menuDesc: "",
 			childCount: 0,
 			i18ns: [],
 			menuSeq: null,
 			selected: false,
 			menuParam : [],
 			menuAuths : [],
  		};
        
     	if( node.length==undefined || node.length === 0 ) {
 			nodeData = $.extend(true, {}, {
				menuType: 'MAIN'
			}, defData);
 			
         } else {
     		if( item.childCount === 0 ) {
     			item.loaded(true);
            }
     		
     		nodeData = $.extend( true, {}, JSON.stringify(item), {
     			menuId: null,
     			parentMenuId: item.menuId
 			}, defData);
     	}
     	
        node.addChildren({title: defData.menuName,
        	key: defData.key,
        	folder: false,
        	lazy: false,
        	data: defData}
        );
        
        addedNodeArr.push( defData );
        
        if(node.children.length==1 && node.parent!=null){
    		$("#menuTreeView").fancytree("getActiveNode").setExpanded();
    	};
        node.children[node.children.length-1].li.click();
        //첫번째놈, 그니까 추가된놈을 선택해야함!
        
        $('#txtId').focus();
	};
	// 다국어 코드 중복 체크
	var i18nArr = [];
	/**
	 * 트리 아이템 저장 이벤트
	 * @private
	 */
	var saveItem = function(e){
		var node = $("#menuTreeView").fancytree("getActiveNode"),
		    item = $("#menuTreeView").fancytree("getActiveNode").data,
		    pnode = node.parent.data;
		
		if( node.length === 0 ) {
    		alert("선택한 아이템이 없습니다");
    		return false;
    	};
		
    	
    	var reqI18nArr = [];

		for (var i = 0; i < i18nList.length; i++) {
			var it = i18nList[i];
			
			reqI18nArr.push({'menuId': it.menuId, 'cdText': it.cdText, 'i18nCd': it.i18nCd});
		};
		
		var reqParamArr = [];

		for (var i = 0; i < paramList.length; i++) {
			var it = paramList[i], 
				paramName = it.paramName,
				paramSeq = it.paramSeq;
			
			reqParamArr.push({
				'dataType': it.dataType,
				'menuId': it.menuId,
				'paramDesc': it.paramDesc,
				'paramName': it.paramName.replace(/\s/gi, ''),
				'paramValue': it.paramValue
			});
		};
    	
		var paramItem = {
				accessUriAddr: $txtPageUrl.val(),
				menuSeq: item.menuSeq,
				auth: $("input:radio[name='certifyYN']:checked").val()=='Y'? true: false,
	 			childCount: item.menuSeq==null? '0': item.childCount,
	 			enabledYn: $sltDisplay.val(),
	 			i18ns: reqI18nArr,
	 			imageUriAddr: $txtImageUrl.val(),
	 			menuAuth : authList,
	 			menuDesc: $txtMenuDesc.val(),
	 			menuId: $txtId.val(), 
	 			menuName: $txtMenu.val(), 
	 			menuOrder: $txtOrder.val(),
	 			menuParam : reqParamArr,
	 			menuType: $sltMenuType.val(),
	 			parentMenuId: pnode.menuId
	 	};
		    	
    	
    	if( paramItem.menuId === null || paramItem.menuId === "" ) {
    		alert( "아이디를 입력해주세요." );
    		return false;
    	};
    	
    	if( paramItem.menuName === null || paramItem.menuName === "" ) {
    		alert( "이름을 입력해주세요." );
    		return false;
    	};
    	if( paramItem.accessUriAddr === null || paramItem.accessUriAddr === "" ) {
    		alert( "페이지 URL을 입력해주세요." );
    		return false;
    	};
    	
    	if( pnode.hasOwnProperty() ) {
	    	if( pnode.menuType === "CONT" && paramItem.menuType !== "CONT" ) {
	    		alert( "콘텐츠 하위에는 콘텐츠만 등록할 수 있습니다" );
	    		return false;
	    	}
	    	
	    	if( paramItem.menuType === "SIDE" ){
	    		alert( "메뉴타입을 사이드바로 지정할 수 없습니다." );
	    		return false;
	    	}
    	}
    	    
    	paramItem.accessUriAddr = $('#txtPageUrl').val();
    	
    	/*if( paramItem.accessUriAddr.indexOf("javascript:") > -1 && paramItem.aggYn === "Y" ){
    		alert( "스크립트 메뉴는 통계여부를 '아니오'로 설정해주세요.")
    		return false;
    	};*/
    		
		var opt = {
				url : $crudServiceBaseUrl + "/save.json",
				method : "POST",
				data : self.util.stringifyJson(paramItem),
				dataType : "json",
				contentType: "application/json; charset=UTF-8"
    	};
    	var success = function(data){
    		alert("저장 되었습니다");
    		addedNodeArr = [];
			var saveItemData = $('#menuTreeView').fancytree('getActiveNode');
			$('#title'+saveItemData.key).text(data.menuName);
			saveItemData.data = data;
    		/*location.reload(true);*/
    	};
    	var error = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt, success, error );
    	addedNodeArr = [];
	};
	/**
	 * 트리 아이템 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 removeItem = function(e){
		var node = $("#menuTreeView").fancytree("getActiveNode");
	    
		
    	if( node.length === 0 ) {
            alert( '삭제할 메뉴를 선택해주세요.' );
            return false;
        }
    	var item = $("#menuTreeView").fancytree("getActiveNode").data;
		if( item.menuSeq === null ) {
			node.remove();
			addedNodeArr = [];
			$('#menuDetail').css('display', 'none');
			$('#menuDetailEmpty').css('display', 'block');
        } else {
		
			if( item.childCount > 0 ) {
	    		alert( "하위 아이템이 존재하여 삭제할 수 없습니다." );
	    		return false;
	        }
			
			if( !confirm( "삭제 하시겠습니까?" ) ) {
	    		return false;
	    	}
			
			var opt = {
					url : $crudServiceBaseUrl + "/remove.json",
					type : "POST",
					data : self.util.stringifyJson({ menuId : item.menuId }),
					dataType : "json"
	    	};
	    	var success = function(data){
	    		alert( "삭제 되었습니다" );
	    		$('#menuTreeView').fancytree('getActiveNode').remove();
//	    		location.reload(true);
	    	};
	    	var error = function(xhr,d,t){
	    		console.log(xhr);
				console.log(t);
	    	};
	    	self.ajaxAdmin( opt, success, error );
        }
	};
	/**
	 * 트리 아이템 선택 해제 이벤트
	 * @private
	 */
	var deselectItem = function(e){
		var node = $("#menuTreeView").fancytree("getActiveNode");
		if(node!=null) {
			node.setActive(false);
			node.setFocus(false);
		};
		$txtId.attr('readonly', false);
		$txtId.val('');
		$txtMenu.val('');
		$txtOrder.val('');
		$sltMenuType.val('');
		$sltDisplay.val('');
		/*$("input:radio[name='displayYN']:radio[value='Y']").prop('checked', true);*/
		/*$("input:radio[name='statsYN']:radio[value='Y']").prop('checked', true);*/
		$("input:radio[name='certifyYN']:radio[value='Y']").prop('checked', true);
		$("input:radio[name='certifyDisplayYN']:radio[value='Y']").prop('checked', true);
		$txtPageUrl.val('');
		$txtImageUrl.val('');
		$txtMenuDesc.val('');
		
		$('#menuDetail').css('display', 'none');
		$('#menuDetailEmpty').css('display', 'block');
	};
	
	/**
	 * 속성 데이터 가져오기
	 */
	var authList;
	
	var initDropDownList = function(){
		$sltMenuType.on('change', function(e){
			//네비게이션이면
			if( e.currentTarget.value === "NAVI" ){
				$('#txtPageUrl').val("/navigation.page");
			} else {
				var text = $('#txtPageUrl').val();
				text = (text!==""&& text !=="/navigation.page")?text:"";
				$('#txtPageUrl').val(text);
			}
		});
		
		
		var opt = {
			url : $authCrudServiceBaseUrl + '/getList.json',
			type: 'post',
			dataType: 'json',
			contentType: 'application/json'
		};
		var success = function(data) {
			for (var i = 0; i < data.length; i++) {
				var auth = data[i];
				$('#sltAuth').append('<option value="'+ auth.authId +'">' + auth.authName + '</option>');
			}
		};
		var error = function(xhr, d, t) {
			console.log(xhr);
			alert(xhr.responseText);
		};
		self.ajaxAdmin(opt, success, error);
	};

	/**
	 * 트리 초기화
	 */
    var createDeptNodeData = function(data) {
        return $.extend({
            title : data.menuName,
            key : data.menuId,
            folder : data.childCount>0? true: false,
            lazy : data.childCount>0? true: false,
            data : data
        }, data);
    };

	var initTree = function(){
		var $tree = $("#menuTreeView").fancytree(
                {
                	extensions: ["edit"],
                	lazyLoad : function(event, ctx) {         	
            	var param_lazyload = {
            			async: false,
            			url : $crudServiceBaseUrl + "/getList.json",
            			dataType : 'json',
            			type : 'POST',
            			data: {menuId: ctx.node.data.menuId}
            	};
            	result = [];
            	var success_lazyload = function(data){
            		deptList = data;
            		
                	for ( var i in deptList) {
                        var item = deptList[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 menuData = ctx.node.data;
            	
            	if(menuData.menuId==undefined){
            		$txtId.attr('readonly', false);
            		$txtId.val('');
            		$txtMenu.val('');
            		$txtOrder.val(0);
            		$sltMenuType.val('');
            		$sltDisplay.val('Y');
            		/*$("input:radio[name='displayYN']:radio[value='Y']").prop('checked', true);*/
            		/*$("input:radio[name='statsYN']:radio[value='Y']").prop('checked', true)*/
            		$("input:radio[name='certifyYN']:radio[value='Y']").prop('checked', true);
            		$("input:radio[name='certifyDisplayYN']:radio[value='Y']").prop('checked', true);
            		$txtPageUrl.val('');
            		$txtImageUrl.val('');
            		$txtMenuDesc.val('');
            		
            		$('#table_i18n_view').empty();
            		$('#table_param_view').empty();
            		$('#table_auth_view').empty();
            		i18nList = [];
            		paramList = [];
            		authList = [];
            		i18nEditList = [];
            		paramEditList = [];
            		authEditList = [];
            		
            	}else{
            		$txtId.attr('readonly', true);
	            	$txtId.val(menuData.menuId);
	        		$txtMenu.val(menuData.menuName);
	        		$txtOrder.val(menuData.menuOrder);
	        		$sltMenuType.val(menuData.menuType);
	        		$sltDisplay.val(menuData.enabledYn);
	        		$txtPageUrl.val(menuData.accessUriAddr);
	        		$txtImageUrl.val(menuData.imageUriAddr);
	        		$txtMenuDesc.val(menuData.menuDesc);
	        		menuInfo(menuData.menuId);
            	};
            	
            	//설명 글자수제한 초기화
                $txtMenuDesc.trigger("keyup");
                
                $('#menuDetail').css('display', 'block');
    			$('#menuDetailEmpty').css('display', 'none');
            },
            click : function(event, data) {
            },
        }).fancytree('getTree');
		var deptList;
		$.ajax({
			async : false,
			url : $crudServiceBaseUrl + "/getList.json",
			dataType : 'json',
			type : 'POST',
			contentType : 'application/json',
			success : function(result){
				deptList = result;
			}
		});
		
    	var $root = $tree.getRootNode();
        for ( var i in deptList) {
            var item = deptList[i];
            if (item.parentMenuId == null) {
                $root.addNode(createDeptNodeData(item));
            };
        }

	};
	var i18nList = [];
	var paramList = [];
	var authList = [];
	var i18nEditList = [];
	var paramEditList = [];
	var authEditList = [];
	var temI18nSeq;
	var temParamSeq;
	

	var menuInfo = function(menuId){
		//다국어 테이블
		var opt_i18n = {
				url : $crudServiceBaseUrl + "/getI18nList.json",
				type : "POST",
				dataType : "json",
				data: self.util.stringifyJson({'menuId': menuId}),
				contentType: "application/json; charset=UTF-8"
    	};
    	var success_i18n = function(data){
    		$('#table_i18n_view').empty();
    		i18nList = data;
    		temI18nSeq = data.length;
    		for(var i=0; i<i18nList.length; i++){
    			var tr = $('<tr></tr>').clone();
    			var tdCode = $('<td></td>').clone().text(i18nList[i].i18nCd);
    			var tdText = $('<td></td>').clone().text(i18nList[i].cdText==null? '': self.util.getBytes(i18nList[i].cdText)>20? self.util.cut(i18nList[i].cdText, 20)+'...': i18nList[i].cdText);
    			
    			i18nList[i].i18nSeq = i;
    			
    			$('#table_i18n_view').append(tr.append(tdCode).append(tdText));    
    		};
    	};
    	var error_i18n = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt_i18n, success_i18n, error_i18n );
		
    	//파라미터 테이블
		var opt_param = {
				url : $crudServiceBaseUrl + "/getParamList.json",
				type : "POST",
				dataType : "json",
				data: self.util.stringifyJson({'menuId': menuId}),
				contentType: "application/json; charset=UTF-8"
    	};
    	var success_param = function(data){
    		paramList = data;
    		temParamSeq = data.length;
    		$('#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==null? '': self.util.getBytes(paramList[i].paramName)>10? self.util.cut(paramList[i].paramName, 10)+'...': paramList[i].paramName);
    			var tdType = $('<td></td>').clone().text(paramList[i].dataType);
    			var tdValue = $('<td></td>').clone().text(paramList[i].paramValue==null? '': self.util.getBytes(paramList[i].paramValue)>10? self.util.cut(paramList[i].paramValue, 10)+'...': paramList[i].paramValue);
    			var tdDesc = $('<td></td>').clone().text(paramList[i].paramDesc==null? '': self.util.getBytes(paramList[i].paramDesc)>10? self.util.cut(paramList[i].paramDesc, 10)+'...': paramList[i].paramDesc);
    			
    			paramList[i].paramSeq = i;
    			
    			$('#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 opt_auth = {
				url : $crudServiceBaseUrl + "/getMenuAuthList.json",
				type : "POST",
				dataType : "json",
				data: self.util.stringifyJson({'menuId': menuId}),
				contentType: "application/json; charset=UTF-8"
    	};
    	var success_auth = function(data){
    		authList = data;
    		$('#table_auth_view').empty();
    		
    		for(var i=0;i <authList.length; i++){
	    		var tr = $('<tr></tr>').clone();
	    		var tdName = $('<td></td>').clone().text(authList[i].authName);
	    		
	    		$('#table_auth_view').append(tr.append(tdName));
    		};
    	};
    	var error_auth = function(xhr,d,t){
    		console.log(xhr);
			console.log(t);
    	};
    	self.ajaxAdmin( opt_auth, success_auth, error_auth );
    	
	};
	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;
	};
	
	/*-------------------------- 다국어 테이블 CRUD -------------------------- */
	var editTableI18n = function(){
		$("#sltI18n").val($("#sltI18n option:first").val());
		$('#txtI18n').val('');
		
		$('#table_i18n').empty();
		for(var i=0; i<i18nList.length; i++){
			var tr = $('<tr itemData="'+i18nList[i].i18nCd+'"></tr>').clone();
			var tdCode = $('<td></td>').clone().text(i18nList[i].i18nCd);
			var tdText = $('<td></td>').clone().addClass('max-width-sm').text(i18nList[i].cdText==null? '': self.util.getBytes(i18nList[i].cdText)>10? self.util.cut(i18nList[i].cdText, 10)+'...': i18nList[i].cdText);
			var tdEdit = $('<td></td>').clone().append('<button type="button" class="btn btn-default  btn-xs" itemData="'+i18nList[i].i18nCd+'"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');
			
			$('#table_i18n').append(tr.append(tdCode).append(tdText).append(tdEdit));    
		};
		$('#table_i18n tr').unbind();
		$('#table_i18n tr').on('click', function(e){
			editItemI18n(e);
			$('#table_i18n tr').removeClass('active');
			$(this).addClass('active');
		});
		$('#table_i18n tr td button').unbind();
		$('#table_i18n tr td button').on('click', function(e){
			removeItemI18n(e);
		});
		/*i18nEditList = i18nList;*/
		i18nEditList = [];
		$.extend(i18nEditList, i18nList); //객체 복사, 위의 방식으로하면 객체 공유가 되어버림!
		$('#addItemModal_i18n').modal('show');
		$('#saveItem_i18n').unbind();
		$('#saveItem_i18n').on('click', function(){
			var param = { 'i18nSeq': null,
						 'i18nCd': $('#sltI18n').val(),
						 'cdText': $('#txtI18n').val(),
						 'menuId': $("#txtId").val()};
			saveItemI18n(param, 'new');
		});
		
		if($('#table_i18n tr').length>0){
			$('#table_i18n tr')[0].click();
		}else{
			$('#modalI18nDetail').css('display', 'none');
			$('#modalI18nDetailEmpty').css('display', 'block');
		};
	};
	
	var	newTableI18n = function(){
		/*$('#sltI18n').attr('disabled', false);*/
		$("#sltI18n").val($("#sltI18n option:first").val());
		$('#txtI18n').val('');
		$('#table_i18n tr').removeClass('active');
		
		$('#saveItem_i18n').unbind();
		$('#saveItem_i18n').on('click', function(){
			var param = {
					 	'i18nSeq': null,
						 'i18nCd': $('#sltI18n').val(),
						 'cdText': $('#txtI18n').val(),
						 'menuId': $("#txtId").val()
						};
			saveItemI18n(param, 'new');
		});
		
		$('#modalI18nDetail').css('display', 'block');
		$('#modalI18nDetailEmpty').css('display', 'none');
		
		$("#sltI18n").focus();
	};
	
	var	saveItemI18n =function(param, newYn){
		if($('#table_i18n tr[class!="active"][itemData="'+param.i18nCd+'"]').length>0){
			alert('다국어 코드는 중복될 수 없습니다.');
			return;
		};
		
		if(param.cdText==null||param.cdText==''){
			alert('다국어 텍스트를 입력해주세요.');
			return;
		};
		
		if(newYn=='edit'){	
			olderValue = $('#table_i18n tr.active')[0].attributes.itemData.value;
			$('#table_i18n tr[itemData="'+olderValue+'"]')[0].children[0].innerText=param.i18nCd;
			$('#table_i18n tr[itemData="'+olderValue+'"]')[0].children[1].innerText=param.cdText==null? '': self.util.getBytes(param.cdText)>10? self.util.cut(param.cdText, 10)+'...': param.cdText;
			$('#table_i18n tr[itemData="'+olderValue+'"]')[0].children[2].children[0].attributes.itemData.value=param.i18nCd;
			$('#table_i18n tr[itemData="'+olderValue+'"]')[0].attributes.itemdata.value=param.i18nCd;
			for(var i=0; i<i18nEditList.length; i++){
				if(i18nEditList[i].i18nCd==olderValue){
					i18nEditList[i].i18nCd = param.i18nCd;
					i18nEditList[i].cdText = param.cdText;
				}
			};
		}else{
			var tr = $('<tr itemData="'+param.i18nCd+'"></tr>').clone();
			var tdCode = $('<td></td>').clone().text(param.i18nCd);
			var tdText = $('<td></td>').clone().addClass('max-width-sm').text(param.cdText==null? '': self.util.getBytes(param.cdText)>10? self.util.cut(param.cdText, 10)+'...': param.cdText);
			var tdEdit = $('<td></td>').clone().append('<button type="button" class="btn btn-default  btn-xs" itemData="'+param.i18nCd+'"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');
			
			$('#table_i18n').append(tr.append(tdCode).append(tdText).append(tdEdit));
			i18nEditList.push(param);
		};
				
		$('#table_i18n tr').unbind();
		
		$('#table_i18n tr').on('click', function(e){
			editItemI18n(e);
			$('#table_i18n tr').removeClass('active');
			$(this).addClass('active');
		});
		
		$('#table_i18n tr td button').unbind();
		$('#table_i18n tr td button').on('click', function(e){
			removeItemI18n(e);
		});
		$('#table_i18n tr[itemData="'+param.i18nCd+'"]').click();
	};
	
	var	editItemI18n = function(e){
		var itemData = getItemData(i18nEditList, 'i18nCd', e.currentTarget.attributes.itemData.value);
		if(itemData==undefined || itemData ==null){
			alert('정상적인 데이터가 아닙니다.'); //이표시가 맞을까?
			return;
		};
		
		$('#sltI18n').val(itemData.i18nCd);
		$('#txtI18n').val(itemData.cdText);
		
		$('#saveItem_i18n').unbind();
		$('#saveItem_i18n').on('click', function(){
			var param = {
					'i18nSeq': itemData.i18nSeq,
					'i18nCd': $('#sltI18n').val(), 'cdText': $('#txtI18n').val(), 'menuId': $("#txtId").val()};
			saveItemI18n(param, 'edit');
		});
		$('#modalI18nDetail').css('display', 'block');
		$('#modalI18nDetailEmpty').css('display', 'none');
	};
	
	var	removeItemI18n = function(e){
		$('#table_i18n tr[itemData="'+e.currentTarget.attributes.itemData.value+'"]').remove();
				
		for(var i=0; i<i18nEditList.length; i++){
			if(i18nEditList[i].i18nCd == e.currentTarget.attributes.itemData.value){
				i18nEditList.splice(i, 1);
				break;
			}
		};
		$('#table_i18n tr').removeClass('active');
		$('#modalI18nDetail').css('display', 'none');
		$('#modalI18nDetailEmpty').css('display', 'block');
	};
	
	var	confirmTableI18n = function(e){
		$('#addItemModal_i18n').modal('hide');
		$('#table_i18n_view').empty();
		
		for(var i=0; i<i18nEditList.length; i++){
			var tr = $('<tr>').clone();
			var tdCode = $('<td></td>').clone().text(i18nEditList[i].i18nCd);
			var tdText = $('<td></td>').clone().text(i18nEditList[i].cdText==null? '': self.util.getBytes(i18nEditList[i].cdText)>20? self.util.cut(i18nEditList[i].cdText, 20)+'...': i18nEditList[i].cdText);
			
			$('#table_i18n_view').append(tr.append(tdCode).append(tdText));
		};
		i18nList = [];
		$.extend(i18nList, i18nEditList); //객체 복사
	};
	/*-------------------------- 다국어 테이블 CRUD 끝-------------------------- */
	
	/*-------------------------- 파라미터 테이블 CRUD -------------------------- */
	var editTableParam = function(){
		$('#txtParamName').val('');
		$("#sltParamType").val($("#sltParamType option:first").val());
		$('#txtParamValue').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==null? '': self.util.getBytes(paramList[i].paramName)>10? self.util.cut(paramList[i].paramName, 10)+'...': paramList[i].paramName);
			var tdValue = $('<td></td>').clone().text(paramList[i].paramValue==null? '': self.util.getBytes(paramList[i].paramValue)>10? self.util.cut(paramList[i].paramValue, 10)+'...': paramList[i].paramValue);
			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(tdValue).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);
		});
		
		paramEditList = [];
		$.extend(paramEditList, paramList); //객체 복사
	
		$('#addItemModal_param').modal('show');
		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function(){
			var param = {
						'paramSeq' : null,
						'paramName': $('#txtParamName').val(),
						'dataType': $('#sltParamType').val(),
						'paramValue': $('#txtParamValue').val(),
						'paramDesc': $('#txtParamDesc').val(),
						'menuId': $("#txtId").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(){
		$('#txtParamName').val('');
		$("#sltParamType").val($("#sltParamType option:first").val());
		$('#txtParamValue').val('');
		$('#txtParamDesc').val('');
		$('#table_param tr').removeClass('active');
		
		$('#modalParamDetail').css('display', 'block');
		$('#modalParamDetailEmpty').css('display', 'none');
		
		$('#txtParamName').focus();
		
		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function(){
			var param = {
					'paramSeq' : null,
					'paramName': $('#txtParamName').val(),
					'dataType': $('#sltParamType').val(),
					'paramValue': $('#txtParamValue').val(),
					'paramDesc': $('#txtParamDesc').val(),
					'menuId': $("#txtId").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==null? '': self.util.getBytes(param.paramName)>10? self.util.cut(param.paramName, 10)+'...': param.paramName;
			$('#table_param tr[itemData="'+olderValue+'"]')[0].children[1].innerText=param.paramValue==null? '': self.util.getBytes(param.paramValue)>10? self.util.cut(param.paramValue, 10)+'...': param.paramValue;
			$('#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].paramValue = param.paramValue;
					paramEditList[i].paramDesc = param.paramDesc;
				}
			};
		}else{
			var tr = $('<tr itemData="' + param.paramName + '"></tr>').clone();
			var tdName = $('<td></td>').clone().text(param.paramName==null? '': self.util.getBytes(param.paramName)>10? self.util.cut(param.paramName, 10)+'...': param.paramName);
			var tdValue = $('<td></td>').clone().text(param.paramValue==null? '': self.util.getBytes(param.paramValue)>10? self.util.cut(param.paramValue, 10)+'...': param.paramValue);
			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) {
			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);
		});
		
		$('#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;
		};
		
		$('#txtParamName').val(itemData.paramName);
		$("#sltParamType").val(itemData.dataType);
		$('#txtParamValue').val(itemData.paramValue);
		$('#txtParamDesc').val(itemData.paramDesc);
		
		$('#saveItem_param').unbind();
		$('#saveItem_param').on('click', function(){
			var param = {
					'paramSeq' : itemData.paramSeq,
					'paramName': $('#txtParamName').val(), 
					'dataType': $('#sltParamType').val(), 
					'paramValue': $('#txtParamValue').val(), 
					'paramDesc': $('#txtParamDesc').val(), 
					'menuId': $("#txtId").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></tr>').clone();
			var tdNo = $('<td></td>').clone().text(i+1);
			var tdName = $('<td></td>').clone().text(paramEditList[i].paramName==null? '': self.util.getBytes(paramEditList[i].paramName)>10? self.util.cut(paramEditList[i].paramName, 10)+'...': paramEditList[i].paramName);
			var tdType = $('<td></td>').clone().text(paramEditList[i].dataType);
			var tdValue = $('<td></td>').clone().text(paramEditList[i].paramValue==null? '': self.util.getBytes(paramEditList[i].paramValue)>10? self.util.cut(paramEditList[i].paramValue, 10)+'...': paramEditList[i].paramValue);
			var tdDesc = $('<td></td>').clone().text(paramEditList[i].paramDesc==null? '': self.util.getBytes(paramEditList[i].paramDesc)>10? self.util.cut(paramEditList[i].paramDesc, 10)+'...': paramEditList[i].paramDesc);
			
			$('#table_param_view').append(tr.append(tdNo).append(tdName).append(tdType).append(tdValue).append(tdDesc));	
		};
		paramList = [];
		$.extend(paramList, paramEditList); //객체 복사
	};
	/*-------------------------- 파라미터 테이블 CRUD 끝-------------------------- */
	
	/*-------------------------- 권한 테이블 CRUD -------------------------- */
	var editTableAuth = function(){
		$("#sltAuth").val($("#sltAuth option:first").val());
		
		$('#table_auth').empty();
		for(var i=0;i <authList.length; i++){
			var tr = $('<tr itemData="'+authList[i].authId+'"></tr>').clone();
    		var tdName = $('<td></td>').clone().text(authList[i].authName);
    		var tdEdit = $('<td></td>').clone().append('<button type="button" class="btn btn-default  btn-xs" itemData="'+authList[i].authId+'"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');
    		
    		$('#table_auth').append(tr.append(tdName).append(tdEdit));
		};
		$('#table_auth tr').unbind();
		$('#table_auth tr').on('click', function(e){
			editItemAuth(e);
			$('#table_auth tr').removeClass('active');
			$(this).addClass('active');
		});
		
		$('#table_auth tr td button').unbind();
		$('#table_auth tr td button').on('click', function(e){
			removeItemAuth(e);
		});
		authEditList = [];
		$.extend(authEditList, authList); //객체 복사
		$('#addItemModal_auth').modal('show');
		$('#saveItem_auth').unbind();
		$('#saveItem_auth').on('click', function(){
			var param = {'authId': $('#sltAuth').val(),
					'authName': $('#sltAuth option:selected').text()};
			saveItemAuth(param);
		});
		
		if($('#table_auth tr').length>0){
			$('#table_auth tr')[0].click();
		}else{
			$('#modalAuthDetail').css('display', 'none');
			$('#modalAuthDetailEmpty').css('display', 'block');
		};
	};
	
	var newTableAuth = function(){
		$("#sltAuth").val($("#sltAuth option:first").val());
		$('#table_auth tr').removeClass('active');
				
		$('#modalAuthDetail').css('display', 'block');
		$('#modalAuthDetailEmpty').css('display', 'none');
		
		$('#sltAuth').focus();
		
		$('#saveItem_auth').unbind();
		$('#saveItem_auth').on('click', function(){
			var param = {
					'authId': $('#sltAuth').val(),
					'authName': $('#sltAuth option:selected').text()
			};
			saveItemAuth(param, 'new');
		});
	};
	var saveItemAuth = function(param, newYn) {
		if(param.authId==''){
			alert('권한을 선택해주세요.');
			return;
		};
		if($('#table_auth tr[class!="active"][itemData="'+param.authId+'"]').length>0){
			alert('권한은 중복될 수 없습니다.');
			return;
		};
		
		if(newYn=='edit'){	
			olderValue = $('#table_auth tr.active')[0].attributes.itemData.value;
			$('#table_auth tr[itemData="'+olderValue+'"]')[0].children[0].innerText=param.authName;
			$('#table_auth tr[itemData="'+olderValue+'"]')[0].children[1].children[0].attributes.itemData.value=param.paramName;
			$('#table_auth tr[itemData="'+olderValue+'"]')[0].attributes.itemdata.value=param.paramName;
			for(var i=0; i<authEditList.length; i++){
				if(authEditList[i].authId==olderValue){
					authEditList[i].authId = param.authId;
					authEditList[i].authName = param.authName;
				}
			};
		}else{
			var tr = $('<tr itemData="'+ param.authId +'"></tr>').clone();
			var tdName = $('<td></td>').clone().text(param.authName);
			var tdEdit = $('<td></td>').clone().append(
					'<button type="button" class="btn btn-default  btn-xs" itemData="' + param.authId + '"><span class="glyphicon glyphicon-minus">&nbsp;삭제</span></button>');

			$('#table_auth').append(tr.append(tdName).append(tdEdit));
			authEditList.push(param);
		};
	    
	    $('#table_auth tr').unbind();		
	    $('#table_auth tr').on('click', function(e){
			editItemAuth(e);
			$('#table_auth tr').removeClass('active');
			$(this).addClass('active');
		});
		
	    $('#table_auth tr td button').unbind();
	    $('#table_auth tr td button').on('click', function(e){
			removeItemAuth(e);
		});
		$('#table_auth tr[itemData="'+param.authId+'"]').click();
	};
	var editItemAuth = function(e){
		var itemData = getItemData(authEditList, 'authId', e.currentTarget.attributes.itemData.value);
		if(itemData==undefined || itemData ==null){
			alert('정상적인 데이터가 아닙니다.'); //이표시가 맞을까?
			return;
		};
		
		$('#sltAuth').val(itemData.authId);
		
		$('#saveItem_auth').unbind();
		$('#saveItem_auth').on('click', function(){
			var param = {'authId': $('#sltAuth').val(), 'authName': $('#sltAuth option:selected').text()};
			saveItemAuth(param, 'edit');
		});	
		$('#modalAuthDetail').css('display', 'block');
		$('#modalAuthDetailEmpty').css('display', 'none');
	};
	var removeItemAuth = function(e){
		$('#table_auth tr[itemData="'+e.currentTarget.attributes.itemData.value+'"]').remove();
		
		for(var i=0; i<authEditList.length; i++){
			if(authEditList[i].authId == e.currentTarget.attributes.itemData.value){
				authEditList.splice(i, 1);
				break;
			}
		};	
		$('#table_auth tr').removeClass('active');
		
		$('#modalAuthDetail').css('display', 'none');
		$('#modalAuthDetailEmpty').css('display', 'block');
	};
	var confirmTableAuth = function(e){
		$('#addItemModal_auth').modal('hide');
		$('#table_auth_view').empty();
		
		for(var i=0; i<authEditList.length; i++){
			var tr = $('<tr></tr>').clone();
			var tdName = $('<td></td>').clone().text(authEditList[i].authName);
			
			$('#table_auth_view').append(tr.append(tdName));
		};
		authList = [];
		$.extend(authList, authEditList); //객체 복사
	};
	
	/*-------------------------- 권한 테이블 CRUD 끝-------------------------- */
}; 
var rowNum = 0;
function resetRowNum(){
	rowNum = 0;
}
function getNum(){
	return ++rowNum;
};
