var clickActionNm = "clickTreeNode";	// ノードクリック時のjavascriptメソッド名
var btnNm = "treeBtn";			// 組織図ポップアップ呼び出しボタン名
var treePopNm = "treeArea";					// 組織図ポップアップのid
var folderNm = contextRoot + "/images/tree"; // アイコン格納場所
var clickValue;

// ノードオブジェクト
function Node(id, pid, name, url, title, target, icon, iconOpen, open) {
	this.id = id;				// ノードID           (組織コード)
	this.pid = pid;				// 紐づくノードのID   (所属コード)
	this.name = name;			// ノードのラベル名   (組織名)
	this.url = url;				// ノードの関連コード (関連コード)
	this.title = title;			// ノードのタイトル(カーソル当てたら出るコメント)
	this.target = target;		// ノードのターゲット
	this.icon = icon;			// 押下前のアイコン
	this.iconOpen = iconOpen;	// 押下時のアイコン
	this._io = open || false;	//
	this._is = false;			//
	this._ls = false;			//
	this._hc = false;			//
	this._ai = 0;				//
	this._p;
};


// ポップアップツリーオブジェクト

function popTree(objNm) {

	this.config = {
		target			: null,
		folderLinks		: true,
		useSelection	: true,
		useCookies		: true,
		useLines		: true,
		useIcons		: false,
		useStatusText	: false,
		closeSameLevel	: false,
		inOrder			: false
	}

	this.icon = {
		root		: folderNm + '/tree-1.gif',
		folder		: folderNm + '/tree-2.gif',
		folderOpen	: folderNm + '/tree-2.gif',
		node		: folderNm + '/tree-2.gif',
		empty		: folderNm + '/tree-empty.gif',
		line		: folderNm + '/tree-line.gif',
		join		: folderNm + '/tree-line_join.gif',
		joinBottom	: folderNm + '/tree-line_joinbottom.gif',
		plus		: folderNm + '/tree-plus.gif',
		plusBottom	: folderNm + '/tree-plusbottom.gif',
		nlPlus		: folderNm + '/tree-plus_nolines.gif',
		minus		: folderNm + '/tree-minus.gif',
		minusBottom	: folderNm + '/tree-minusbottom.gif',
		nlMinus		: folderNm + '/tree-minus_nolines.gif'
	};

	this.obj = objNm;
	this.aNodes = [];			// ノード配列
	this.aIndent = [];
	this.root = new Node(0);
	this.selectedNode = null;
	this.selectedFound = false;
	this.completed = false;
};


// ツリー要素追加プロパティ

popTree.prototype.add = function(id, pid, name, url, icon, iconOpen, open) {

	this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, icon, iconOpen, open);

};


// 全て開くプロパティ

popTree.prototype.openAll = function() {

	this.oAll(true);

};


// 全て閉じるプロパティ

popTree.prototype.closeAll = function() {

	this.oAll(false);

};


// 表示html取得

popTree.prototype.toString = function() {

	var str = '<div class="popTree">\n';

	// IE, FF
	if (document.getElementById) {

		if (this.config.useCookies) this.selectedNode = this.getSelected();

		str += this.addNode(this.root);

	} else str += 'サポートしていないブラウザです';

	str += '</div>';

	if (!this.selectedFound) this.selectedNode = null;

	this.completed = true;

	return str;

};


// ノードの設定プロパティ

popTree.prototype.addNode = function(pNode) {
	var str = '';
	var n=0;
	if (this.config.inOrder) n = pNode._ai;

	for (n; n<this.aNodes.length; n++) {
//alert('this.aNodes[n].pid ' + this.aNodes[n].pid + '  pNode.id ' + pNode.id);
		if (this.aNodes[n].pid == pNode.id) {

			var cn = this.aNodes[n];
			cn._p = pNode;
			cn._ai = n;

			this.setCS(cn);

			// 上位組織名の連結
//			if (pNode.kanrenNm != undefined){ 
//				this.aNodes[n].kanrenNm = pNode.kanrenNm + ' > ' + this.aNodes[n].kanrenNm;
//				this.aNodes[n].oyaTekiyo = pNode.date;	// 親組織の適用開始日を退避
//			}
			
			if (!cn.target && this.config.target) cn.target = this.config.target;

			if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);

			if (!this.config.folderLinks && cn._hc) cn.url = null;

			if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {

					cn._is = true;

					this.selectedNode = n;
					this.selectedFound = true;

			}

			str += this.node(cn, n);

			if (cn._ls) break;
		}
	}

	return str;
};


// URL,テキストの設定プロパティ

popTree.prototype.node = function(node, nodeId) {
//alert('node  ' + node + '  nodeId ' + nodeId);
	var str = '<div class="popTreeNode">' + this.indent(node, nodeId);

	if (this.config.useIcons) {

		if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);

		if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;

		if (this.root.id == node.pid) {

			node.icon = this.icon.root;
			node.iconOpen = this.icon.root;

		}

		//str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
	}

	if (node.url) {

		str += '<a id="s' + this.obj + nodeId + '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + '" href="#"';

		if (node.title) str += ' title="' + node.title + '"';

		if (node.target) str += ' target="' + node.target + '"';

		if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';

		if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))

			str += ' onclick="javascript:' + clickActionNm + '(\'' + node.id + '\',\'' + node.url + '\',\'' + node.name + '\',\'' + clickValue + '\' );"';

		str += '>';

	}

	else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)

		str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';

	str += node.name;

	if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>';

	str += '</div>';

	if (node._hc) {

		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
		str += this.addNode(node);
		str += '</div>';
	}

	this.aIndent.pop();

	return str;
};


// 表示アイコン設定プロパティ

popTree.prototype.indent = function(node, nodeId) {
	var str = '';

	if (this.root.id != node.pid) {

		for (var n=0; n<this.aIndent.length; n++)

			str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';

		(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);

		if (node._hc) {

			str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';

			if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;

			else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );

			str += '" alt="" /></a>';

		} else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
	}

	return str;
};


// 最後のノードかどうか設定

popTree.prototype.setCS = function(node) {

	var lastId;

	for (var n=0; n<this.aNodes.length; n++) {

		if (this.aNodes[n].pid == node.id) node._hc = true;

		if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
	}

	if (lastId==node.id) node._ls = true;
};


// 選択したノードの値を取得

popTree.prototype.getSelected = function() {

	var sn = this.getCookie('cs' + this.obj);

	return (sn) ? sn : null;

};


// 選択したノードの背景色設定★

popTree.prototype.s = function(id) {

	if (!this.config.useSelection) return;

	var cn = this.aNodes[id];

	if (cn._hc && !this.config.folderLinks) return;

	if (this.selectedNode != id) {

		if (this.selectedNode || this.selectedNode==0) {
			eOld = document.getElementById("s" + this.obj + this.selectedNode);
			eOld.className = "node";
		}

		eNew = document.getElementById("s" + this.obj + id);
		eNew.className = "nodeSel";

		this.selectedNode = id;

		if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);

	}

};


// ノードの開閉設定

popTree.prototype.o = function(id) {
	var cn = this.aNodes[id];

	this.nodeStatus(!cn._io, id, cn._ls);

	cn._io = !cn._io;

	if (this.config.closeSameLevel) this.closeLevel(cn);

	if (this.config.useCookies) this.updateCookie();

};


// 全てのノードの開閉設定

popTree.prototype.oAll = function(status) {

	for (var n=0; n<this.aNodes.length; n++) {

		if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
			this.nodeStatus(status, n, this.aNodes[n]._ls)
			this.aNodes[n]._io = status;
		}
	}

	if (this.config.useCookies) this.updateCookie();

};


// Opens the tree to a specific node

popTree.prototype.openTo = function(nId, bSelect, bFirst) {

	if (!bFirst) {

		for (var n=0; n<this.aNodes.length; n++) {

			if (this.aNodes[n].id == nId) {
				nId=n;
				break;
			}
		}
	}

	var cn=this.aNodes[nId];

	if (cn.pid==this.root.id || !cn._p) return;

	cn._io = true;
	cn._is = bSelect;

	if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);

	if (this.completed && bSelect) this.s(cn._ai);

	else if (bSelect) this._sn=cn._ai;

	this.openTo(cn._p._ai, false, true);

};


// 子ノードを全て閉める

popTree.prototype.closeLevel = function(node) {

	for (var n=0; n<this.aNodes.length; n++) {

		if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
			this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
}


// 子ノードを閉める

popTree.prototype.closeAllChildren = function(node) {

	for (var n=0; n<this.aNodes.length; n++) {

		if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {

			if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);

			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);		
		}
	}
}


// ノードの開閉ステータス変更

popTree.prototype.nodeStatus = function(status, id, bottom) {
	eDiv	= document.getElementById('d' + this.obj + id);
	eJoin	= document.getElementById('j' + this.obj + id);

	if (this.config.useIcons) {
		eIcon	= document.getElementById('i' + this.obj + id);
		eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
	}

	eJoin.src = (this.config.useLines)?

	((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):

	((status)?this.icon.nlMinus:this.icon.nlPlus);

	eDiv.style.display = (status) ? 'block': 'none';
};


// クッキー削除

popTree.prototype.clearCookie = function() {

	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);

	this.setCookie('co'+this.obj, 'cookieValue', yesterday);

	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};


// クッキー設定

popTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {

	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '');
};


// クッキーの値を取得

popTree.prototype.getCookie = function(cookieName) {

	var cookieValue = '';
	var cookieObj = document.cookie;
	if(cookieObj){
		var posName = document.cookie.indexOf(escape(cookieName) + '=');
		
		if (posName != -1) {
			var posValue = posName + (escape(cookieName) + '=').length;
			var endPos = document.cookie.indexOf(';', posValue);
			
			if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));
			
			else cookieValue = unescape(document.cookie.substring(posValue));
			
		}
	}
	return (cookieValue);
};


// 開いてるノードのクッキー設定

popTree.prototype.updateCookie = function() {

	var str = '';

	for (var n=0; n<this.aNodes.length; n++) {

		if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {

			if (str) str += '.';

			str += this.aNodes[n].id;
		}
	}

	this.setCookie('co' + this.obj, str);
};


// [Cookie] Checks if a node id is in a cookie

popTree.prototype.isOpen = function(id) {

	var aOpen = this.getCookie('co' + this.obj).split('.');

	for (var n=0; n<aOpen.length; n++)

		if (aOpen[n] == id) return true;

	return false;
};


// If Push and pop is not implemented by the browser

if (!Array.prototype.push) {

	Array.prototype.push = function array_push() {

		for(var i=0;i<arguments.length;i++)

			this[this.length]=arguments[i];

		return this.length;
	}
};


if (!Array.prototype.pop) {

	Array.prototype.pop = function array_pop() {

		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);

		return lastElement;
	}
};


var IE = 0,NN = 0,FF = 0;
var IE_VAR = 0;
if(document.all) IE = true;
else if(document.layers) NN = true;
else if(document.getElementById) FF = true;
if (IE){
	myAgent = navigator.userAgent ;
	_top = myAgent.indexOf ( "MSIE" , 0 ) ;
	_ver = myAgent.substring ( _top + 5 , _top + 6 ) ;
	if (_ver == "6") IE_VAR = true;
}

var fPageX = 0;
var fPageY = 0;
var fClientX = 0;
var fClientY = 0;

/* オブジェクト表示 */
function OnTree(Tree,mX,mY,nX,nY){
	var pX = 0,pY = 0;
	var sX = -5,sY = 20;
	if(IE){
		MyTree = document.all(Tree).style;
		MyTree.visibility = "visible";
	}
	if(NN){
		MyTree = document.layers[Tree];
		MyTree.visibility = "show";
	}
	if(FF){
		MyTree = document.getElementById(Tree).style;
		MyTree.visibility = "visible";
	}
	if(IE){
		pX = document.body.scrollLeft || document.documentElement.scrollLeft;
		pY = document.body.scrollTop  || document.documentElement.scrollTop;
		MyTree.left = mX + pX + sX;
		MyTree.top = mY + pY + sY;
	}
	if(NN || FF){
		// NN:未確認 FF:OK 2008.06.10 aranai
		pX = document.body.scrollLeft || document.documentElement.scrollLeft;
		pY = document.body.scrollTop  || document.documentElement.scrollTop;
		MyTree.left = mX + pX + sX + "px";
		MyTree.top = mY + pY + sY + "px";
	}
}

/* 組織図ポップアップ表示 */
function dispTree(nm, clickName, value){

	// ポップアップの名称設定
	if (nm == undefined || nm == ''){
		treePopNm = 'treeArea';
	}else{
		treePopNm = nm;
	}
	if (clickName == undefined || clickName == ''){
		clickActionNm = 'clickTreeNode';
	}else{
		clickActionNm = clickName;
	}

	if (value == undefined || value == ''){
		clickValue = '';
	}else{
		clickValue = value;
	}

	// 組織ツリー設定
	if (document.getElementById(treePopNm) != null){
		tree = createTreeData();
		document.getElementById(treePopNm).innerHTML = tree;
	}
	
	var obj = document.getElementById(treePopNm);
	obj.style.display = "block";

	// IE6ではセレクト要素がdivで隠せないので、非表示にする
	if (IE_VAR){
		var elems = document.getElementsByTagName("select");
		for (i = 0; i < elems.length; i++) {
			// nameの末尾が「Hid」以外のelement
			if(!elems[i].name.match(/Hid$/)){
				elems[i].style.visibility = "hidden";
			}
		}
	}

	var pos = getTreeElementPosition(document.getElementById(btnNm));

	// null以外の場合に表示
	if (obj.value != "") {
		if(IE){
			obj.style.overflow = "hidden";
			
			OnTree(treePopNm,event.clientX,event.clientY,event.pageX,event.pageY);
		}else{
			obj.style.overflow = "hidden";
			OnTree(treePopNm,fClientX,fClientY,fPageX,fPageY);
		}
	}
/*	if (FF){
		obj.style.left = window.pageXOffset + 100 + 'px';
		obj.style.top  = window.pageYOffset + 100 + 'px';
	}*/
	document.getElementById('treeOpenFlg').value = '1' ;
}

/* 組織図ポップアップ非表示 */
function closeTree(){
	if(IE) document.all(treePopNm).style.visibility = "hidden";
	if(NN) document.layers[treePopNm].visibility = "hide";
	if(FF) document.getElementById(treePopNm).style.visibility = "hidden";
	
	// 非表示にしたセレクト要素を表示する
	if (IE_VAR){
		var elems = document.getElementsByTagName("select");
		for (i = 0; i < elems.length; i++) {
			// nameの末尾が「Hid」以外のelement
			if(!elems[i].name.match(/Hid$/)){
				elems[i].style.visibility = "visible";
			}
		}
	}
}

/* onMouseMoveイベントが発生したら、マウスのXY座標を取得する処理を実行 */
if(!document.all){
	document.onmousemove=getMouseXY;
}

function getMouseXY(evt){ /* Firefox, Netscape */
	fPageX = evt.pageX;
	fPageY = evt.pageY;
	fClientX = evt.clientX;
	fClientY = evt.clientY;
}


/*	要素の絶対位置を取得 */
function getTreeElementPosition(e){
	var p  = {x:0,y:0};

    if(!e.offsetParent){
        return p ;
    }else{
    }
	p.x = e.offsetLeft;
	p.y = e.offsetTop;

	// 親要素が存在する場合、その絶対位置を足す
	if(e.offsetParent){
		var pp = getTreeElementPosition(e.offsetParent);
		p.x += getPixNum(pp.x);
		p.y += getPixNum(pp.y);
	}
	return p;
}

/* pxとかはずして数値にする */
function getPixNum(d){
	var s = (d + "").replace(/\D/g,"");
	var n = parseInt(s);
	return n;
}

/* 組織図ポップアップ表示領域以外をクリック時、ポップアップを消す */
document.onclick = function(e){
	if(document.getElementById('treeOpenFlg') != null &&
	   document.getElementById(treePopNm) != null){
		if(document.getElementById('treeOpenFlg').value == 'true'){
			var obj;
			var x = 0;
			var y = 0;
			var pX = document.body.scrollLeft || document.documentElement.scrollLeft;
			var pY = document.body.scrollTop  || document.documentElement.scrollTop;
			// 位置取得
			if(IE){
				obj = document.all(treePopNm);
				x = event.clientX + pX;
				y = event.clientY + pY;
			}
			else
			{
				obj = document.getElementById(treePopNm);
				x = fClientX + pX;
				y = fClientY + pY;
			}
			var xleft = obj.offsetLeft;
			var xwidth = obj.offsetLeft + obj.offsetWidth;
			var ytop = obj.offsetTop;
			var yheight = obj.offsetTop + obj.offsetHeight;
			
			// 組織図ポップアップ表示エリア外の場合は表示を消す
			if((x < xleft || xwidth < x) || (y < ytop || yheight < y)){
				closeTree();
				document.getElementById('treeOpenFlg').value = false ;
			}
		}else if(document.getElementById('treeOpenFlg').value == '1'){
			document.getElementById('treeOpenFlg').value = true;
		}
		
	}
	
	return true;
}

/* ポップツリーのルートを追加する */
function popTreeAddRoot(obj){
	obj.root = new Node(-1);
	obj.add('0','-1','','0');
	return obj
}
