<?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();	
			$html .= '<li id="depart_' . $attrs->departid . '" class="jstree-closed jstree-unchecked">';
			$html .= '<a href="#">' . $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>' . '0' . '</parentdepartid>' . 
	'</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 = '<li id="root" class="jstree-closed jstree-unchecked"><a href="#">[ 组织机构 ]</a><ul>' . ViewDepartments(0, $childs, 0) . '</ul></li>';
		$html_departs = "'" . $html_departs . "'";
echo<<<EOT
<div id="departtree" style="clear:both;margin:0;padding:0;width:264px;height:200px;border:1px solid #d8d8d8;overflow-x:auto;overflow-y:auto"></div>
	
<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 getCheckedIds(){
    var idArray = new Array();
	//$("#departtree").find(".jstree-checked, .jstree-undetermined ").each(function(){
    $("#departtree").find(".jstree-checked").each(function(){
           var isChild = true;
        if($(this).find('li').length != 0){
			if ($(this).attr("id") != 'root')
				idArray.push($(this).attr("id"));      
            isChild = false;
        }
        if(isChild){
			if ($(this).attr("id") != 'root')
				idArray.push($(this).attr("id"));
		}
    });     
	//return idArray;
    var ids=idArray.join(',');
    return ids;
}

$(function () {

$("#departtree")
	.jstree({ 
		"plugins" : [ 
			"themes","html_data","types","ui","checkbox"
		],
        "themes": {
            "theme": "classic",
            "dots": true,
            "icons": true,
			"url": "./jstree/themes/classic/style.css"
        },		
		"html_data" : {
            "data" : $html_departs
        },
		"ui" : {
			"initially_select" : [ "root" ]
		},
		"lang" : {     
			"loading" : "目录加载中..."    
		},    
		"core" : { 
			"initially_open" : [ "root" ],
			"animation" : false
		},
		"types": { "types":
					{
						"person": { "icon": { "image": "./jstree/themes/classic/person.png"} }
					}
		}
	})
	.bind("open_node.jstree", function (event, data) {
		var node = data.rslt.obj, inst = data.inst;

		var departid = node.attr("id").replace('depart_', '');
		var departname = getInnerText(node.children("a")[0]);
		departname = departname.replace(/(\s|(\u00A0)|(\u3000))/, '');

		if ($("#depart_" + departid + " li").length > 0) { return; }

		if (departid != 'root') {
			var xhconn = new XHConn();		
			var sVars = "departid=" + departid;
			xhconn.connect("selectusers_ajax.php", "POST", sVars, function(oXML) {
				var strStatus = oXML.responseText;
				if (strStatus != '') {
					node.append(strStatus);
					inst.close_node(node);
					inst.open_node(node);
				}
			});	
		}
	})
});//$(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 + '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>
