jQuery(document).ready(function() {
	
	var bo = false;
	var number = 0;
	function getAsyncUrl(treeId, treeNode) {
		if(treeNode!=null){
			bo = true;
		}
		return !treeNode ? "/permission/findUpdateRootByParentId" : "/permission/findUpdateNodeByParentId";
	}

	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
		var treeObj = $.fn.zTree.getZTreeObj("roleanizationTree");
		if (!treeNode) {
			var nodes = treeObj.getNodes();
			treeObj.selectNode(nodes[0]);
		}
		var treeObj = $.fn.zTree.getZTreeObj("roleanizationTree");
		var nodes = treeObj.getCheckedNodes(true);
		number=nodes.length;
	}

	var roleTreeInit = function() {
		var setting = {
			callback : {
				onAsyncSuccess : zTreeOnAsyncSuccess
			},
			view : {
				dblClickExpand : false
			},
			async : {
				enable : true,
				dataType : "json",
				url : getAsyncUrl,
				autoParam : [ "id=parentId" ],
				otherParam: [ "roleId", $("input[name=id]").val()]
			},
			data : {
				simpleData : {
					enable : true
				}
			},
			check: {
				enable:true
			}
		};

		$.fn.zTree.init($("#roleanizationTree"), setting);
	}
	roleTreeInit();
	

	$("#roleForm").validate({
		onkeyup : false,
		submitHandler:function(form){
			var result = '';
			var treeObj = $.fn.zTree.getZTreeObj("roleanizationTree"),form = $(form);
			var nodes = treeObj.getChangeCheckedNodes();
			form.find(".node").remove();
			if(nodes){
				for (var i = 0; i < nodes.length; i++) {
					form.append('<input name="permissions['+i+'].id" value="'+nodes[i].id+'" class="node" type="hidden"/>');
					form.append('<input name="permissions['+i+'].check" value="'+nodes[i].checked+'" class="node" type="hidden"/>');
				}
			}
			
			$(form).ajaxSubmit({
				dataType:"JSON",
		    	success:function(e){
		    		if(e && e.success == true){
			    		jQuery("#grid-table").trigger("reloadGrid");
		    			sxUtil.msgbox.success('操作成功！');
			    		sxUtil.dialog.close($(form).data('index'));
		    		}else{
		    			sxUtil.msgbox.error(e,'修改失败');
					}
		    	}
		    });
		},
		rules : {
			'name':{
				required : true,
				rangelength:[2,20],
				remote:{
					url:"/role/validateUpdate",
					type:"get",
					dataType:'json',
					data:{
						roleName:function(){
							return $("input[name=name]").val();
						},
						roleId:function(){
							return $("input[name=id]").val();
						}
					}
				}
			},
			
		},
		messages :{
			'name':{
				required : "角色名称不能为空",
				rangelength:"角色名称必须是2~20个字符之间",
				remote:"角色名称已存在"
			}
		}
	 });
	
});