<?php
header("Content-type:text/html;charset=utf-8");  
session_start();
$session_admin = isset($_SESSION['admin']) ? $_SESSION['admin'] : ''; 
if ($session_admin == '') {
	die("Can not access");
}
require_once("../common.php");
checkadminrights($session_admin, 'departments');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" rel="stylesheet" href="../css/base.css" />

<script type="text/javascript" src="jstree/_lib/jquery.js"></script>
<script type="text/javascript" src="jstree/_lib/jquery.cookie.js"></script>
<script type="text/javascript" src="jstree/_lib/jquery.hotkeys.js"></script>
<script type="text/javascript" src="jstree/jquery.jstree.js"></script>
<script type="text/javascript" src="../js/XHConn.js"></script>

<style type="text/css">
html,body{margin:0;padding:0;width:100%;height:100%}
body{margin:0;padding:0;overflow-x:hidden;overflow-y:hidden;font:12px Helvetica,Arial,sans-serif;background-color:#f4f4f4;}
.toolbar ul { margin:0;padding:0;list-style:none;display:inline; }
.toolbar li { float:left;margin:0;padding:10px 0 0 5px; }
</style>

</head>
<body>

<?php
require_once("../common.php");

function CountDepartments($childs) {
	$num = 0;
	foreach($childs as $child) {				
		if ($child->getName() == 'department') { 
			$num += 1;
		}//if
		$num += CountDepartments($child->children()); 
	}//foreach
	return $num;
}//function CountDepartments

function CountDepartUsers($childs) {
	$num = 0;
	foreach($childs as $child) {		
		if ($child->getName() == 'department') { 
			$num += CountDepartUsers($child->children()); 
		} else if ($child->getName() == 'user') {
			$num += 1;
		}//if
	}//foreach
	return $num;
}//function CountDepartUsers

function getChildLength($childs){  
	$count = 0;
	foreach($childs as $child) {	 
			$count = $count + 1;               
   }//for
   return $count;    
}//function getChildLength

function ViewDepartments($indent, $childs, $itemindex) {
	$html = "";
	$temp_index = $itemindex;
	$offset = $indent * 16;
	foreach($childs as $child) {				
		if ($child->getName() == 'department') { 
			$temp_index += 1;
			$itembgcolor = '#f2f2f2';
			if (($temp_index % 2) == 0) $itembgcolor = '#e9e9e9';
			$attrs = $child->attributes();	
			$subpageurlparams = 'departid=' . $attrs->departid . '&departname=' . urlencode($attrs->departname);
			$html .= "<li id='" . $attrs->departid . "'>";
			$html .= "<a href='#' title='点击查看人员列表'>" . $attrs->departname . "</a>";
			if (getChildLength($child->children()) > 0) {
				$html .= '<ul>';
				$html .= ViewDepartments($indent + 1, $child->children(), $temp_index); 
				$html .= '</ul>';
			}
			$html .= "</li>";
		}//if
	}//foreach
	return $html;
}//function ViewDepartments

$departid = isset($_GET['departid']) ? $_GET['departid'] : ''; 
$departname = isset($_GET['departname']) ? urldecode($_GET['departname']) : ''; 

$frameurlparams = '';
if ($departid != '') {
	$frameurlparams = 'departid=' . $departid . '&departname=' . urlencode($departname);
}

$methodname = 'Admin.GetDepartments';
$requestinfo = '<?xml version="1.0" encoding="utf-8"?><request>' . 
    '<ip>' . getip() . '</ip>' . 
	'<parentdepartid>' . '-1' . '</parentdepartid>' . 
	'<showdepartusers>' . '0' . '</showdepartusers>' . 
	'</request>';
$responseinfo = '';
$responsexml = null;
$errorcode = ERRORCODE_UNKNOWN;

$cmd = new COM("OpenCom.Command");
$methodname = iconv('UTF-8', 'GBK//IGNORE', $methodname);
$requestinfo = iconv('UTF-8', 'GBK//IGNORE', $requestinfo);
if ($cmd->Execute($methodname, $requestinfo, $responseinfo, 10000)) {
	$responseinfo = iconv('GBK', 'UTF-8//IGNORE', $responseinfo);
	$responsexml = simplexml_load_string($responseinfo);
	$errorcode = $responsexml->errorcode;
}
$cmd = null;

switch($errorcode) {
	case ERRORCODE_OK: 
		$childs = $responsexml->departments->children();
		$count_depart = CountDepartments($childs);
		$count_user = CountDepartUsers($childs);	
		$html_departs = ViewDepartments(0, $childs, 0);
echo<<<EOT
<table id="main" cellspacing="0" cellpadding="0" style="margin:0;padding:0;border-collapse:collapse;border:none;width:100%height:600px;">
<tr>
	<td valign="top" style="margin:0;padding:0;border:none;">
		<div style="clear:both;margin:0;padding:0;height:40px;text-align:left;font-size:13px;color:#000000;">
			<div class="toolbar" style="float:left;margin:0;padding:0;">
				<ul>
					<!--<li style="padding:10px 0 0 0;"><input class="cssbtn" type="button" value="刷新" onclick="refreshlist();return false;" /></li>-->
					<li style="padding:10px 0 0 0;"><input class="cssbtn" type="button" value="添加部门" onclick="adddepart();return false;" /></li>					
				</ul>
			</div>
			<div class="toolbar" style="float:right;margin:0;padding:0;">
				<ul>
					<li><input id="btn_moveup" class="cssbtn" type="button" value="向上" onclick="moveupdepart();return false;" /></li>
					<li><input id="btn_movedown" class="cssbtn" type="button" value="向下" onclick="movedowndepart();return false;" /></li>						
					<li><input id="btn_rename" class="cssbtn" type="button" value="重命名" onclick="renamedepart();return false;" /></li>
					<li><input id="btn_move" class="cssbtn" type="button" value="移动" onclick="movedepart();return false;" /></li>							
					<li><input id="btn_remove" class="cssbtn" type="button" value="删除" onclick="removedepart();return false;" /></li>							
				</ul>
			</div>			
		</div>	
		
		<div id="departtree" style="clear:both;margin:0;padding:0;width:353px;height:513px;border:1px solid #d8d8d8;overflow-x:auto;overflow-y:auto"></div>
	</td>
	<td valign="top" style="margin:0;padding:0 0 0 8px;border:none;">
		<div style="clear:both;margin:0;padding:0;height:40px;text-align:left;font-size:13px;color:#000000;">
			<div id="users_title" style="float:left;margin:0;padding:15px 0 0 0;">人员列表</div>
			<div class="toolbar" style="float:right;margin:0;padding:0;">
				<ul>
					<li><input id="users_addbtn" class="cssbtn" type="button" value="添加人员" onclick="adddepartusers();return false;" /></li>
				</ul>
			</div>
		</div>		
		<div id="departusers" style="clear:both;width:493px;height:513px;border:1px solid #d8d8d8;">
			<iframe id="frame_departusers" style="width:493px;height:513px" frameborder="0" src="departments_users.php"></iframe>
		</div>
	</td>
</tr>
</table>
	
<script language="javascript">
var selected_departid = '';
var selected_departname = '';
var ismoving = false;

String.prototype.trim=function() {
     return this.replace(/(^\s*)(\s*$)/g, '');
}

function getInnerText(obj) {
	if (document.all) {
		return obj.innerText;
	} else {
		return obj.textContent;
	}	
	return "";
}

function setInnerText(obj, text) {
	if (document.all) {
		obj.innerText = text;
	} else {
		obj.textContent = text;
	}	
}

function selectdepart(departid, departname) {
    if (departid != 'root') {
		selected_departid = departid;
		selected_departname = departname;

		var frame = document.getElementById('frame_departusers');
		frame.src = 'departments_users.php?departid=' + departid + '&departname=' + encodeURIComponent(departname);
		
		var div = document.getElementById('users_title');
		setInnerText(div, '部门人员(' + departname + ')');
		
		var div = document.getElementById('users_addbtn');
		div.style.display = '';	

		var obj = document.getElementById('btn_moveup');
		obj.style.display = '';
		
		var obj = document.getElementById('btn_movedown');
		obj.style.display = '';
		
		var obj = document.getElementById('btn_rename');
		obj.style.display = '';
		
		var obj = document.getElementById('btn_move');
		obj.style.display = '';		
		
		var obj = document.getElementById('btn_remove');
		obj.style.display = '';
    } else {
		selected_departid = '';
		selected_departname = '';
		
		var frame = document.getElementById('frame_departusers');
		frame.src = 'departments_users.php';
		
		var div = document.getElementById('users_title');
		setInnerText(div, '部门人员');
		
		var div = document.getElementById('users_addbtn');
		div.style.display = 'none';	
		
		var obj = document.getElementById('btn_moveup');
		obj.style.display = 'none';
		
		var obj = document.getElementById('btn_movedown');
		obj.style.display = 'none';
		
		var obj = document.getElementById('btn_rename');
		obj.style.display = 'none';
		
		if (ismoving == false) {
			var obj = document.getElementById('btn_move');
			obj.style.display = 'none';
		}		
		
		var obj = document.getElementById('btn_remove');
		obj.style.display = 'none';
	}
}//selectdepart

function adddepart() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
	$("#departtree").jstree("create", null, "last", "新建部门");
}//adddepart

function refreshlist() {
	window.location.href = 'departments.php';
}//refreshlist

function renamedepart() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
    if (selected_departid == '') {
		alert("请选择一个部门！");
		return;
	}
	$("#departtree").jstree('rename');
}//renamedepart

function moveupdepart() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
    if (selected_departid == '') {
		alert("请选择一个部门！");
		return;
	}
	window.location.href = 'departments_moveup.php?departid=' + selected_departid + '&departname=' + encodeURIComponent(selected_departname);
}//moveupdepart

function movedowndepart() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
    if (selected_departid == '') {
		alert("请选择一个部门！");
		return;
	}
	window.location.href = 'departments_movedown.php?departid=' + selected_departid + '&departname=' + encodeURIComponent(selected_departname);
}//movedowndepart

function movedepart() {
	if (ismoving == false) {
		if (selected_departid == '') {
			alert("请选择一个部门！");
			return;
		}	
		ismoving = true;
		$("#departtree").jstree('cut');
		
		var obj = document.getElementById('btn_move');
		obj.value = '放置';
	} else {
		ismoving = false;
		$("#departtree").jstree('paste');
		
		var obj = document.getElementById('btn_move');
		obj.value = '移动';		
	}
}//movedepart

function removedepart() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
    if (selected_departid == '') {
		alert("请选择一个部门！");
		return;
	}
	if (confirm('确定要删除部门"' + selected_departname + '"?')) {
		$("#departtree").jstree('remove');
	}
}//removedepart

function adddepartusers() {
	if (ismoving == true) {
		alert("正在移动部门，不能进行此项操作！");
		return;
	}
    if (selected_departid == '') {
		alert("请选择一个部门！");
		return;
	}
	var frame = document.getElementById('frame_departusers');
	frame.src = 'departments_adduser.php?departid=' + selected_departid + '&departname=' + encodeURIComponent(selected_departname);	
}//adddepartusers

$(function () {

$("#departtree")
	.jstree({ 
		"plugins" : [ 
			"themes","html_data","ui","crrm","cookies","types"
		],
        "themes": {
            "theme": "classic",
            "dots": true,
            "icons": true,
			"url": "jstree/themes/classic/style.css"
        },		
		"html_data" : {
            "data" : "<li id='root'><a href='#'>[ 组织机构 ]</a><ul>{$html_departs}</ul></li>"
        },
		"ui" : {
			"initially_select" : [ "root" ]
		},
		lang:{     
			loading : "目录加载中..."    
		},    
		"core" : { 
			"initially_open" : [ "root" ],
			"animation" : false
		}
	})
 	.bind("create.jstree", function (e, data) {
		var parentdepartid = data.rslt.parent.attr("id")
		if (parentdepartid == 'root') parentdepartid = '0';
		var departname = getInnerText(data.rslt.obj.children("a")[0]);
		var xhconn = new XHConn();		
		var sVars = "parentdepartid=" + parentdepartid + "&departname=" + departname;
		xhconn.connect("departments_add.php", "POST", sVars, function(oXML) {
			var strStatus = oXML.responseText;
			if ((strStatus == '') || (strStatus == 'Can not access') || (strStatus == '-1')) {
				$.jstree.rollback(data.rlbk);
			} else {
				$(data.rslt.obj).attr("id", strStatus);
				data.inst.select_node("#" + strStatus, true);
			}
		});
	})
	.bind("remove.jstree", function (e, data) {
		var departid = data.rslt.obj.attr("id");
		if (departid != 'root') {
			var xhconn = new XHConn();		
			var sVars = "departid=" + departid;
			xhconn.connect("departments_remove.php", "POST", sVars, function(oXML) {
				var strStatus = oXML.responseText;
				if (strStatus != '0') {
					$.jstree.rollback(data.rlbk);
				}
			});	
		}
	})
	.bind("rename.jstree", function (e, data) {
		var departid = data.rslt.obj.attr("id");
		var departname = data.rslt.new_name;
		departname = departname.replace(/(\s|(\u00A0)|(\u3000))/, '');		
		if (selected_departname != departname) {
			var xhconn = new XHConn();		
			var sVars = "departid=" + departid + "&departname=" + departname;
			xhconn.connect("departments_rename.php", "POST", sVars, function(oXML) {
				var strStatus = oXML.responseText;
				if (strStatus != '0') {
					$.jstree.rollback(data.rlbk);
				} else {
					data.inst.select_node("#" + departid, true);
				}
			});					
		}
	})
	.bind("move_node.jstree", function (e, data) {
		data.rslt.o.each(function (i) {  
			var src_departid = this.id;
			var dest_departid = data.rslt.np.attr("id");
			if (dest_departid == 'root') dest_departid = 0;
			if (src_departid != dest_departid) {
				var xhconn = new XHConn();		
				var sVars = "departid=" + src_departid + "&parentdepartid=" + dest_departid;
				xhconn.connect("departments_move.php", "POST", sVars, function(oXML) {
					var strStatus = oXML.responseText;
					if (strStatus != '0') {
						$.jstree.rollback(data.rlbk);
					} else {
						data.inst.select_node("#" + src_departid, true);
					}
				});		
			}
		});
	})
	.bind("select_node.jstree", function(e, data) {
		var departid = data.rslt.obj.attr("id");
		var departname = getInnerText(data.rslt.obj.children("a")[0]);
		departname = departname.replace(/(\s|(\u00A0)|(\u3000))/, '');
		selectdepart(departid, departname);
	})

});//$(function ()

function doresize() {
	var w = document.documentElement.clientWidth;
	var h = document.documentElement.clientHeight;
	
	var main = document.getElementById('main');
	main.style.height = h + 'px';	
	
	var departtree = document.getElementById('departtree');
	departtree.style.height = (h - 48) + 'px';
	
	var departusers = document.getElementById('departusers');
	departusers.style.width = (w - 370) + 'px';
	departusers.style.height = (h - 48) + 'px';	
	
	var frame_departusers = document.getElementById('frame_departusers');
	frame_departusers.style.width = (w - 370) + 'px';
	frame_departusers.style.height = (h - 48) + 'px';		
}

$(document).ready(function(){  
	doresize();
	$(window).resize(function(){  
		doresize();
	}); 	
}); 
</script>
EOT;
		break;
	default:
echo<<<EOT
	<div class="msgbox">
		<div class="msgbox_text">
			<img width="40px" height="40px" align="absmiddle" src="../images/warning.gif" />&nbsp;部门列表获取失败！
		</div>
	</div>
EOT;
}//switch
?>

</body>
</html>
