<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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 selectedMenuId = '0';

function init(url){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=displayYn]")).setData(json.displayYnRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=useYn]")).setData(json.useYnTypeRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=appCode]")).setData(json.menuAppCdRows).setFormat(codeName3OptionFormat).rendering();
			
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}

function isValid(){
	if($('input[name=menuId]').val() == ""){
		alert("<%= localeMessage.getString("menu.checkRequierd1") %>");
		return false;
	}else if($('input[name=menuName]').val() == ""){
		alert("<%= localeMessage.getString("menu.checkRequierd2") %>");
		return false;
	}else if($('input[name=parentMenuId]').val() == ""){
		alert("<%= localeMessage.getString("menu.checkRequierd3") %>");
		return false;
	}else if($('textarea[name=menuUrl]').val() == ""){
		alert("<%= localeMessage.getString("menu.checkRequierd4") %>");
		return false;
	}
    var pmenu = $('input[name=parentMenuId]').val();
    var menuId = $('input[name=menuId]').val();
	var index = 0;
	for(index=pmenu.length;  index > 0 ; index--){
		if ( 0 != pmenu.substr(index-1,1)){
            break;
		}
	}
	if (pmenu.substr(0,index) != menuId.substr(0,index)){
		/*var r = confirm("상위메뉴ID 의 유효값("+pmenu.substr(0,index) +")과 메뉴ID("+menuId.substr(0,index)+") 의 유효값이\n"
						+"일치 하지 않습니다.\n"
						+ "그래도 저장 하시겠습니까?"); 
		*/
        var r = confirm(replaceMsg("<%=localeMessage.getString("menu.checkMsg1")%>", pmenu.substr(0,index),menuId.substr(0,index))); 
		if (r == false) return false;
	}

	return true;
}
function expand(){
	var rowid = $('#tree').jqGrid('getGridParam','selrow');
	var rowdata = $('#tree').jqGrid('getRowData',rowid);
//	alert(JSON.stringify(rowdata));

	if (rowdata["MENUID"] =="0"){
		var rows = $('#tree').jqGrid('getGridParam','data');
		for( var i=0;i<rows.length;i++){
			$('#tree').jqGrid('expandNode',rows[i]);
			$('#tree').jqGrid('expandRow',rows[i]);
		}
	}else{
		//시작값 가져오기
		var org = $("#tree").getDataIDs();
		var start =0;
		for(var i =0; i<org.length;i++){
			if (org[i]==rowid){
				start =i;
			}
		}
		var rows = $('#tree').jqGrid('getGridParam','data');
		var lvl = rowdata["level"];
		for( var i=start;i<rows.length;i++){
			if (rows[i]["level"] <= lvl && i != start){
				break;
			}
			$('#tree').jqGrid('expandNode',rows[i]);
			$('#tree').jqGrid('expandRow',rows[i]);
		}
	}

}
function collapse(){
	var rowid = $('#tree').jqGrid('getGridParam','selrow');
	var rowdata = $('#tree').jqGrid('getRowData',rowid);
	if (rowdata["MENUID"] =="0"){
		var rows = $('#tree').jqGrid('getGridParam','data');
		for( var i=0;i<rows.length;i++){
			$('#tree').jqGrid('collapseNode',rows[i]);
			$('#tree').jqGrid('collapseRow',rows[i]);
		}
		$('#tree').jqGrid('expandNode',rows[0]);
		$('#tree').jqGrid('expandRow',rows[0]);	
	}else{
		//시작값 가져오기
		var org = $("#tree").getDataIDs();
		var start =0;
		for(var i =0; i<org.length;i++){
			if (org[i]==rowid){
				start =i;
			}
		}
		var rows = $('#tree').jqGrid('getGridParam','data');
		var lvl = rowdata["level"];
		for( var i=start;i<rows.length;i++){
			if (rows[i]["level"] <= lvl && i != start){
				break;
			}
			$('#tree').jqGrid('collapseNode',rows[i]);
			$('#tree').jqGrid('collapseRow',rows[i]);
			
		}
	}

}

function keepSelection() {
	
	/* find selectedMenuId idx */
	var org = $("#tree").getDataIDs();
	var start = 0;
	for(var i = 0; i < org.length; i++) {
		if(org[i] == selectedMenuId) {
			start = i;
		}
	}
	
	/* selection */
	$("#tree").jqGrid("setSelection",$("#tree").getDataIDs()[start], true);
	
	var rowid = $("#tree").jqGrid('getGridParam', 'selrow');
	var rowdata = $('#tree').jqGrid('getRowData', rowid);
	var rows = $('#tree').jqGrid('getGridParam', 'data');
	 
	var lvl = rowdata["level"];
	var targets = [];
	
	var parent = rowdata;
	
	/* find parent's id */
	for(var i = 0; i < lvl; i++) {
		parent = $('#tree').jqGrid('getRowData', parent["PARENTMENUID"]);
		var parentId = parent['MENUID'];
		targets.push(parentId);
	}
	
	/* expand by using rows[idx] */
	for(var i = 0; i < targets.length; i++) {
		for(var j = 0; j < rows.length; j++) {
			if(rows[j]["MENUID"] == targets[i]) {
				$("#tree").jqGrid('expandNode', rows[j]);
				$("#tree").jqGrid('expandRow', rows[j]);
			}	
		}
	}
	
	
}
$(document).ready(function() {	
	var gridPostData = getSearchForJqgrid("cmd","LIST_TREE"); //jqgrid에서는 object 로 
	var url = '<c:url value="/common/acl/menu/menuMan.json" />';
	
	init(url);
	
	$('#tree').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : gridPostData,
		colNames:['MENUID',
                  'PARENTMENUID',
                  'SORTORDER',
                  'MENUNAME',
                  'MENUURL',
                  'MENUIMAGE',
                  'DISPLAYYN',
                  'USEYN',
                  'APPPATH',
                  'DISPLAYYNNM',
                  'USEYNNM',
                  'APPCODE',
                  'PARENTNAME'
                  ],
		colModel:[{ name : 'MENUID'      , hidden:true,key :true 	 },
				{ name : 'PARENTMENUID', hidden:true  },
				{ name : 'SORTORDER'   , hidden:true  },
				{ name : 'MENUNAME'    , align:'left',width:300 ,sortable:false},
				{ name : 'MENUURL'     , hidden:true  },
				{ name : 'MENUIMAGE'   , hidden:true  },
				{ name : 'DISPLAYYN'   , hidden:true  },
				{ name : 'USEYN'       , hidden:true  },
				{ name : 'APPPATH'     , hidden:true  },
				{ name : 'DISPLAYYNNM' , hidden:true  },
				{ name : 'USEYNNM'     , hidden:true  },
				{ name : 'APPCODE'     , hidden:true  },
				{ name : 'PARENTNAME'     , hidden:true  }
		],
	    treeGrid: true,
		treeIcons : {
			plus: "ui-icon-circlesmall-plus",
			minus: "ui-icon-circlesmall-minus",
			leaf : "ui-icon-document"
		},
	    treeGridModel: "adjacency",
	    ExpandColumn: "MENUNAME",
	    height:"500",
	    width:"320",
	    rowNum: 1000,
	    gridview:true,
	    treeIcons: {leaf:'ui-icon-document-b'},
	    jsonReader: {
	        repeatitems: false
	    },
	    loadComplete:function (d){
	    	$("#tree").jqGrid("setSelection",$("#tree").getDataIDs()[0], true);
	    	
	    	if(d.rows.length == 0) {
	    		alert("검색결과가 없습니다.");
	    		return;
	    	}
	    	if(d.rows[0].isLeaf === "false") {
	    		collapse();	
	    	}
	    	
	    	keepSelection();
	    	
	    },
	    loadError: function (jqXHR, textStatus, errorThrown) {
        	var location ='<%=request.getContextPath()%>/';
        	comloadError(jqXHR, textStatus, errorThrown ,location);
        	
    	},	    
		ondblClickRow: function(rowId) {
        },		
		onSelectRow: function(rowId) {
			var data = $(this).getRowData(rowId); 

			$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
				var name = $(this).attr("name");
				var tag  = $(this).prop("tagName").toLowerCase();
				if(name=='parentName'){
					$(tag+"[name="+name+"]").val(data[name.toUpperCase()]+" ("+data.PARENTMENUID+")");
				}else{
					$(tag+"[name="+name+"]").val(data[name.toUpperCase()]);
				}
			});
			
			
			if (data['level'] != 3){
				$(".dynamic").hide();
			}else{
				$(".dynamic").show();
			}
			
       }
	    
	});
	
	
	//resizeJqGridWidth('tree','leftbody','1000');

	$("#btn_search").click(function(){
		var postData = getSearchForJqgrid("cmd","LIST_TREE"); //jqgrid에서는 object 로
		
		var rowid = $('#tree').jqGrid('getGridParam', 'selrow');
    	var rowdata = $('#tree').jqGrid('getRowData', rowid);
    	selectedMenuId = rowdata['MENUID'];

		
		
		$("#tree").setGridParam({ postData: postData ,page : "1" }).trigger("reloadGrid");
    	
    	keepSelection();
		 
	});
	$("#btn_new").click(function(){
		var rowId = $('#tree').getGridParam( "selrow" );
		var rowdata = $('#tree').jqGrid('getRowData', rowId);
    	selectedMenuId = rowdata['MENUID'];
    	
		if (isNull(rowId)){
			alert("<%= localeMessage.getString("menu.checkRequierd5") %>");
			return ;
		}
	 	var row = $('#tree').getRowData( rowId );
	 	var level = Number(row["level"]) + 1;
	    if (level > 3 ){
	        alert("<%= localeMessage.getString("menu.checkMsg3") %>");
			return ;
		}
	    var args = new Object();
	    args['level'] = level;
	    args['parentMenuId'] = row['MENUID'];
	    args['parentName'] = row['MENUNAME']+" ("+row['MENUID']+")";
	    var url2 = '<c:url value="/common/acl/menu/menuMan.view"/>';
	    url2 = url2 + "?cmd=POPUP";
	    showModal(url2,args,650,520,function(){$("#btn_search").click();/*재조회*/});
	    
	});
	$("#btn_delete").click(function(){
		if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){  
			var rowId = $('#tree').getGridParam( "selrow" );
			var rowdata = $('#tree').jqGrid('getRowData', rowId);
	    	selectedMenuId = rowdata['MENUID'];
			if (isNull(rowId)){
				alert("<%= localeMessage.getString("menu.checkRequierd5") %>");
				return ;
			}		
			// $('#tree').jqGrid('resetSelection');
			
		 	var row = $('#tree').getRowData( rowId );
		 	
		 	var ids = $('#tree').getDataIDs();
		 	var index = $('#tree').getInd(rowId);
		 	
		 	if (ids.length > Number(index) ){
		 		//check
			 	var childlevel = $('#tree').jqGrid('getCell',ids[Number(index)],'level');
		 		if (row["level"]< childlevel){//child 존재
		 			var r = confirm("<%= localeMessage.getString("menu.checkMsg2") %>");
		 			if (r == false){
		 				return;
		 			}
		 		}
		 	}
		 	
			var postData = new Array();
			postData.push({ name: "cmd" , value:"DELETE"});
			postData.push({ name: "menuId" , value:$("input[name=menuId]").val()});
			$.ajax({
				type : "POST",
				url:url,
				data:postData,
				success:function(args){
					alert("<%= localeMessage.getString("common.deleteMsg") %>");
					// $('#tree').jqGrid('resetSelection');
					$("#btn_search").click();//재조회
				},
				error:function(e){
					alert(e.responseText);
				}
			});
		 }else{
			return false;
		 }

	});
	$("#btn_modify").click(function(){
		if (confirm("<%= localeMessage.getString("common.checkModify")%>") != true)
		return;
		
		var rowId = $('#tree').getGridParam( "selrow" );
		var rowdata = $('#tree').jqGrid('getRowData', rowId);
    	selectedMenuId = rowdata['MENUID'];
		
		if (isNull(rowId)){
			alert("<%= localeMessage.getString("menu.checkRequierd5") %>");
			return ;
		}	
		if(!isValid()){
			return;
		}		
		var postData = $('#ajaxForm').serializeArray();
		postData['selectedMenuId'] = selectedMenuId;
		postData.push({ name: "cmd" , value:"UPDATE"});
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				alert("<%= localeMessage.getString("common.saveMsg") %>");
				// $('#tree').jqGrid('resetSelection');
				$("#btn_search").click();//재조회
			},
			error:function(e){
				alert(e.responseText);
			}
		});

	});	
		
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	$("#btn_plus").click(function(){
		expand();
	});
	$("#btn_minus").click(function(){
		collapse();
	});
	
	
	buttonControl();
	

	
});
 
</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">
				<div class="search_wrap">
					<button type="button" class="cssbtn" id="btn_delete" level="W"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
					<button type="button" class="cssbtn" id="btn_new" level="W"><i class="material-icons">add</i> <%= localeMessage.getString("button.new") %></button>
					<button type="button" class="cssbtn" id="btn_modify" level="W"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button>
					<button type="button" class="cssbtn" id="btn_search" level="R"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button>
<%-- 					<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W"/> --%>
<%-- 					<img src="<c:url value="/img/btn_new.png"/>" alt="" id="btn_new" level="W" /> --%>
<%-- 					<img src="<c:url value="/img/btn_modify.png"/>" alt="" id="btn_modify" level="W" /> --%>
<%-- 					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />						 --%>
				</div>
				<div class="title"><%= localeMessage.getString("menu.title") %></div>
				
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:10%; min-width:80px;"><%= localeMessage.getString("menu.id") %></th>
							<td><input type="text" name="searchId" value=""></td>
							<th style="width:10%; min-width:80px;"><%= localeMessage.getString("menu.name") %></th>
							<td><input type="text" name="searchName" value=""></td>
						</tr>
						<tr>
							<th><%= localeMessage.getString("menu.parent") %></th>
							<td><input type="text" name="searchParent" value=""></td>
							<th><%= localeMessage.getString("menu.url") %></th>
							<td><input type="text" name="searchUrl" value=""></td>
						</tr>
					</tbody>
				</table>
				<table cellspacing=0;>
					<tbody>
						<tr>
							<td><img src="<c:url value="/img/ic_plus.png"/>" alt="" id="btn_plus" "/>
							<img src="<c:url value="/img/ic_minus.png"/>" alt="" id="btn_minus" "/>
							</td>
						</tr>
					</tbody>
				</table>
				
				<div style="font-size:0;">
					<div style="display:inline-block; width:350px; vertical-align:top;">

						<table id="tree" ></table>
					</div>
					<div style="display:inline-block; width:10px;">
					</div>
					<div style="display:inline-block; width:calc(100% - 362px); vertical-align:top;">
						<form id="ajaxForm">
							<table class="table_row" cellspacing="0">
								<tr>
									<th style="width:120px;"><%= localeMessage.getString("menu.id") %></th>
									<td ><input type="text" name="menuId" readonly="readonly"/> </td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.name") %></th>
									<td ><input type="text" name="menuName"/> </td>
								</tr>
					
								<tr>
									<th><%= localeMessage.getString("menu.parent") %></th>
									<td ><input type="text" name="parentName" readonly="readonly"/> 
										 <input type="hidden" name="parentMenuId" readonly="readonly"/>
									</td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.img") %></th>
									<td ><input type="text" name="menuImage"/> </td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.display") %></th>
									<td>
										<div class="select-style">
											<select type="text" name="displayYn" />
										</div>	
									</td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("combo.useYn") %></th>
									<td>
										<div class="select-style">	
											<select type="text" name="useYn" />
										</div>	
									</td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.order") %></th>
									<td >
										<div class="select-style">
											<select name="sortOrder">
												<option value="1">1</option>
												<option value="2">2</option>
												<option value="3">3</option>
												<option value="4">4</option>
												<option value="5">5</option>
												<option value="6">6</option>
												<option value="7">7</option>
												<option value="8">8</option>
												<option value="9">9</option>
												<option value="10">10</option>
												<option value="11">11</option>
												<option value="12">12</option>
												<option value="13">13</option>
												<option value="14">14</option>
												<option value="15">15</option>
												<option value="16">16</option>
												<option value="17">17</option>
												<option value="18">18</option>
												<option value="19">19</option>
												<option value="20">20</option>
											</select> 
										</div>	
									</td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.appCode") %></th>
									<td>
										<div class="select-style">
											<select name="appCode"></select>
										</div>	
									</td>
								</tr>
								<tr>
									<th><%= localeMessage.getString("menu.useDbTab") %></th>
									<td><input type="text" name="appPath"/> </td>
								</tr>
								<tr style="height:100px;">
									<th><%= localeMessage.getString("menu.url") %><div style="color:red;"><%= localeMessage.getString("menu.checkMsg4") %></div></th>
									<td><textarea  name="menuUrl" style="width:100%;height:100px"></textarea></td>
								</tr>
							</table>
						</form>					
					</div>
				</div>
				
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

