var treeConfig={
	rootIcon        : 'images/xtree/foldericon.png',
	openRootIcon    : 'images/xtree/openfoldericon.png',
	folderIcon      : 'images/xtree/foldericon.png',
	openFolderIcon  : 'images/xtree/openfoldericon.png',
	fileIcon        : 'images/xtree/root.gif',
	iIcon           : 'images/xtree/blank.gif',
	lIcon           : 'images/xtree/root.gif',
	lMinusIcon      : 'images/xtree/openroot.gif',
	lPlusIcon       : 'images/xtree/closeroot.gif',
	tIcon           : 'images/xtree/root.gif',
	tMinusIcon      : 'images/xtree/openroot.gif',
	tPlusIcon       : 'images/xtree/closeroot.gif',
	blankIcon       : 'images/xtree/blank.gif',
	defaultText     : 'Tree Item',
	allowDrag       : false ///是否允许拖动
	
}

var treeHandler={
	idCounter :0,
	idPrefix  :"web-tree-",
	getId     : function() { return this.idPrefix + this.idCounter++; },
	toggle    : function(oItem){ this.all[oItem.id.replace("-plus","")].toggle() },
	hover     : function(oItem){ this.all[oItem.id.replace("-text-anchor","")].hover()},
	restore   : function(oItem){ this.all[oItem.id.replace("-text-anchor","")].restore()},
	select    : function(oItem){ this.all[oItem.id.replace("-text-anchor","")].select()},
	focus     : function(oItem){ this.all[oItem.id.replace("-text-anchor","")].select()},
	keycode   : function(oItem,e){ this.all[oItem.id.replace("-text-anchor","")].keycode(e.keyCode)},
	mousedown : function(oItem,e){ this.all[oItem.id.replace("-text-anchor","")].startDrag(e)},
	mousemove : function(oItem,e){ this.all[oItem.id.replace("-text-anchor","")].Draging(e)},
	mouseup   : function(oItem,e){ this.all[oItem.id.replace("-text-anchor","")].endDrag(e)},
	contextmenu: function(oItem,e){},
	all:{ },
	selected:null
};
function TreeItem(sText,sDirid,sAction,sTarget,sOpenImage){
	this.Text=sText;
	this.Dirid=sDirid;
	this.Action=sAction;
	this.target=sTarget;
	this.OpenImage=sOpenImage;
	this.Nodes=new Array();	
	this.level=0;
	this.parent=null;
	this.id=treeHandler.getId();
	this._last=false;
	this.rendered=false;//是否显示]	
	treeHandler.all[this.id]=this;
	this.open=false;
}

TreeItem.prototype.toString=function(){
	var divText=document.createElement("div");
	divText.className="textDiv";
	divText.nowrap=true;
	divText.onselectstart="return false";
	divText.ondragstart="return false";
	divText.oncontextmenu="return false";	
	divText.ondblclick="treeHandler.toggle(this)";
	divText.id=this.id ;		
	
	var divContainer=document.createElement("div");	
	divContainer.onselectstart="return false";
	divContainer.ondragstart="return false";
	divContainer.oncontextmenu="return false";
	divContainer.id=this.id +"-container";
	
	divContainer.className="subContainer";
	
	divContainer.id=this.id +"-container";
	if (this.level ==0){ //顶层处理
		var img=document.createElement("img");
		img.src=treeConfig.rootIcon;
		divText.appendChild(img);		
	}
	else{
		//for(var i=0;i<(this.level -1);i++){
		var foo=this.parent;
		while(foo.parent){			
			var img=document.createElement("img");			
			if(foo._last==true){
				img.src=treeConfig.blankIcon;
			}
			else{
				img.src=treeConfig.iIcon;
			}
			//divText.appendChild(img);			
			divText.insertAdjacentElement("afterBegin",img);
			foo=foo.parent;
		}
		var plusIcon=document.createElement("img"); 
		plusIcon.id=this.id +"-plus"
		if(this.Nodes.length ==0){			//如果已经是叶子			
			if(this.parent.Nodes[this.parent.Nodes.length-1] == this){
				plusIcon.src=treeConfig.lIcon;
			}
			else{
				plusIcon.src=treeConfig.tIcon;
			}
		}
		else{ //如果不是叶子
			
			plusIcon.src=treeConfig.lPlusIcon;
		}
		plusIcon.onclick="treeHandler.toggle(this)";
		
		divText.appendChild(plusIcon);
		/*
		var folderIcon=document.createElement("img");
		folderIcon.id=this.id +"-node-image";
		if(this.Nodes.length ==0){
			folderIcon.src=treeConfig.fileIcon;
		}
		else{
			folderIcon.src=treeConfig.folderIcon;
		}
		divText.appendChild(folderIcon);
		*/
	}
	
	var text=document.createElement("span");
	text.id=this.id+"-text-anchor";
	text.onmouseover="treeHandler.hover(this)";
	text.onmouseout="treeHandler.restore(this)";	
	text.onfocus="treeHandler.focus(this)";
	text.onkeydown="return treeHandler.keycode(this,event)";
	//text.onclick="treeHandler.select(this)";
	
	text.onmousedown="treeHandler.select(this);treeHandler.mousedown(this,event)";
	text.onmousemove="treeHandler.mousemove(this,event)";
	text.onmouseup="treeHandler.mouseup(this,event)";
	text.tabIndex=1;
	text.innerText=this.Text;
	
	text.className="labelItem";
	divText.appendChild(text);


	return divText.outerHTML+ divContainer.outerHTML;
}

TreeItem.prototype.add=function(oItem){
	var c=this.Nodes.length;	
	this.Nodes[c]=oItem;
	oItem.parent=this;
	if(this.Nodes.length>=2){
		this.Nodes[this.Nodes.length -2]._last=false;
	}	
	
	oItem._last=true;
	oItem._set_level(this.level +1);
	
	if(this._root().rendered){
		this._showParent();
	}
	//update ui
	
	
	if(this.rendered){		
		this.rendered=false;
		this.expand();
	}	
	if(this.parent && this.parent.rendered){ //界面上已经显示
		if(this.open){
			document.getElementById(this.id +"-plus").src=treeConfig.lMinusIcon;
		}
		else{
			document.getElementById(this.id +"-plus").src=treeConfig.lPlusIcon;
		}
		//document.getElementById(this.id +"-node-image").src=treeConfig.folderIcon;
		this.expand();
	}
	
}
TreeItem.prototype.remove=function(){

	this._remove();
	if(this.parent && this.parent.Nodes.length==0){ //没有子节点
		var tmp=document.getElementById(this.parent.id +"-node-image");
		if (tmp) tmp.src=treeConfig.fileIcon;
		var tmp=document.getElementById(this.parent.id +"-container");
		if(tmp) tmp.style.display="none";
	}
	var p=this.parent;
	
	if(p.Nodes.length >0 ){
		var pre=p.Nodes[p.Nodes.length-1];		
		pre._last=true;
		
		if(pre.rendered) pre.rerender();
		if(pre.open){	
			pre.expand();
			
		}
	}
}

TreeItem.prototype.setCaption=function(vCaption){
	if(vCaption){
		this.Text=vCaption;		
		var tmp=document.getElementById(this.id+"-text-anchor");
		if(tmp){
			tmp.innerHTML=vCaption;
		}
	}
}
TreeItem.prototype.rerender=function(){
	this.rendered=false;
	for(var i=0;i<this.Nodes.length;i++){
		this.Nodes[i].rerender();
	}
}
TreeItem.prototype._remove=function(){
	if(this==treeHandler.selected) treeHandler.selected=null;
	for(var i=this.Nodes.length-1;i>=0;i--){
		this.Nodes[i]._remove();
	}
	for(var i=0;i<this.parent.Nodes.length;i++){
		if(this==this.parent.Nodes[i]){
			for(j=i;j<this.parent.Nodes.length;j++){
				this.parent.Nodes[j]=this.parent.Nodes[j+1];
			}
			this.parent.Nodes.length-=1;
			break;
		}
	}
	treeHandler.all[this.id]=null;
	var tmp = document.getElementById(this.id);
	if (tmp) { tmp.parentNode.removeChild(tmp); }
	tmp = document.getElementById(this.id + '-container');
	if (tmp) { tmp.parentNode.removeChild(tmp); }
}
TreeItem.prototype._set_level=function(iLevel){
	this.level=iLevel;
	if(this.Nodes.length>0){
		for(var i=0;i<this.Nodes.length;i++){
			this.Nodes[i]._set_level(iLevel + 1);
		}
	}
}

TreeItem.prototype.unselect=function(){
	document.getElementById(treeHandler.selected.id +"-text-anchor").className="labelItem";
	var root=this._root();
	if(root.onUnSelected){ //定义了处理函数
		if(typeof root.onUnSelected=="function"){
			root.onUnSelected(treeHandler.selected);
		}
		else{
			eval(root.onUnSelected);
		}
	}
}
TreeItem.prototype.select=function(){
	if(treeHandler.selected==this) return;
	if(treeHandler.selected){
		treeHandler.selected.unselect();
	}	
	var div=document.getElementById(this.id +"-text-anchor");	
	treeHandler.selected=this;	
	div.className="selectedItem";	
	
	
	var root=this._root();
	if(root.onSelected){
		if(typeof root.onSelected=="function"){
			root.onSelected(this);
		}
		else{
			eval(root.onSelected);
		}
	}
	div.focus();
}
///////////////////////////////////////
//开始拖动
///////////////////////////////////////
TreeItem.prototype.startDrag=function(e){
	//var label=document.getElementById(this.id+"-text-anchor");
	var label=e.srcElement;
	label.setCapture();
	
	var tip=document.createElement("span");	
	tip.className="dragingTooltip";
	tip.innerText=this.Text;
	tip.style.left=e.clientX +document.body.scrollLeft +label.offsetWidth -e.offsetX;
	tip.style.top=e.clientY +document.body.scrollTop +label.offsetHeight -e.offsetY;
	document.body.appendChild(tip);
	
	this._startX=e.clientX;
	this._startY=e.clientY;	
	this._dragTooltip=tip;
	
}


//处理拖动
TreeItem.prototype.Draging=function(e){
	if(this._dragTooltip){	
		var tip=this._dragTooltip;
		var vX= parseInt(e.clientX) - parseInt(this._startX);
		var vY= parseInt(e.clientY) - parseInt(this._startY);
		tip.style.left=parseInt(tip.style.left) + vX;
		tip.style.top=parseInt(tip.style.top) +vY;
		
		this._startX=e.clientX;
		this._startY=e.clientY;
		
		var el=document.elementFromPoint(e.clientX,e.clientY);
		
		if(el ==document.getElementById(this.id +"-text-anchor")) return;
		if(this._OverObject && this._OverObject !=el){
			this._OverObject.className="labelItem";
		}		
		
		if(el.tagName=="SPAN"){
			this._OverObject=el;
			el.className="dragOverItem";
		}
		else{
			this._OverObject=null;
		}
		
	}
}
//完成拖动
TreeItem.prototype.endDrag=function(e){	
	var label=document.getElementById(this.id +"-text-anchor");
	label.releaseCapture();
	
	document.body.removeChild(this._dragTooltip);
	this._dragTooltip=null;
	if(this._OverObject){
		var root=this._root();
		if(root.onDrag){
			
			var eSrc=treeHandler.all[this.id];
			var eTo=treeHandler.all[this._OverObject.id.replace("-text-anchor","")];
			root.onDrag(eSrc,eTo);//触发事件
		}
	}	

	
}

TreeItem.prototype._root=function(){
	if(!this.parent){
		return this;
	}
	else{
		return this.parent._root();
	}
}
TreeItem.prototype.toggle=function(){
	if(this.open){
		this.collapse();
	}
	else{	
		this.expand();
	}
}

TreeItem.prototype.expand=function(){
	if(this.Nodes.length==0) return;
	
	var subCon=document.getElementById(this.id +"-container")
	
	if(this.rendered){
		subCon.style.display="block";
	}
	else{
		var sHTML="";
		for(var i=0;i<this.Nodes.length;i++){
			sHTML+=this.Nodes[i].toString();
		}		
		subCon.innerHTML=sHTML;
		subCon.style.display="block";
		this.rendered=true;
	}	
	if(this.level>0){
		document.getElementById(this.id +"-plus").src=(this._last?treeConfig.lMinusIcon:treeConfig.tMinusIcon);
	}
	this.open=true;
	//调用自定义事件
	var root=this._root();
	if(root.onExpand){
		if(typeof root.onExpand=="function"){
			root.onExpand(this);
		}
		else{
			eval(root.onExpand);
		}
	}
	
}

TreeItem.prototype.collapse=function(){
	if (this.Nodes.length==0) return;
	if(this.level>0){		
		document.getElementById(this.id +"-plus").src=(this._last?treeConfig.lPlusIcon:treeConfig.tPlusIcon);
	}
	document.getElementById(this.id +"-container").style.display ="none";	
	this.open=false;
	var root=this._root();
	if(root.onCollapse){
		if(typeof root.onCollapse=="function"){
			root.onCollapse(this);
		}
		else{
			eval(root.onCollapse);
		}
	}
}

TreeItem.prototype.collapseAll=function(){
	this.collapse();
	this.collapseChildren();
}

TreeItem.prototype.collapseChildren=function(){
	for(var i=0;i<this.Nodes.length;i++){
		this.Nodes[i].collapseAll();
	}
}
TreeItem.prototype.expandAll=function(){	
	this.expand();	
	this.expandChildren();
}

TreeItem.prototype.expandChildren=function(){
	for(var i=0;i<this.Nodes.length;i++){
		this.Nodes[i].expandAll();
	}
}

TreeItem.prototype.getFirst=function(){
	return this.Nodes[0];
}
TreeItem.prototype.getLast=function(){
	
	if(this.Nodes.length >0 && this.open){		
		return this.Nodes[this.Nodes.length-1].getLast();		
	}
	else{
		return this;
	}
}
TreeItem.prototype.getPreviousSibling=function(b){
	if(this.parent){
		for(var i=0;i<this.parent.Nodes.length;i++){
			if(this==this.parent.Nodes[i]) {
				break;
			}
		}
		
		if(i==0){
			return this.parent;
		}
		else{
			
			if(this.parent.Nodes[i-1].Nodes.length >0){		
				
				return this.parent.Nodes[i-1].getLast();
			}
			else{
				
				return this.parent.Nodes[i-1];
			}
		}
	}
	else{
		return this;
	}
}
TreeItem.prototype.getNextSibling=function(b){		
	if (!b){		
		if(this.Nodes.length >0 && this.open){
			return this.getFirst();
		}
	}
	if(this.parent){
		for(var i=0;i<this.parent.Nodes.length;i++){
			if(this==this.parent.Nodes[i]) {
				break;
			}
		}
		if(i==this.parent.Nodes.length-1){			
			return this.parent.getNextSibling(true);
		}
		else{
			return this.parent.Nodes[i+1];
		}
	}
	else{
		return this;
	}
}
TreeItem.prototype.keycode=function(key){
	
	if(key==39 && this.Nodes.length >0){
		if(!this.open){
			this.expand();
		}
		this.getFirst().select();
		return false;
	}
	else if(key==37){
		if(this.open) {
			this.collapse();	
		}
		else{
			if(this.parent){
				this.parent.select();
			}
			return false;
		}
	}
	else if(key==40){
		this.getNextSibling().select();
		return false;
	}
	else if(key==38){
		this.getPreviousSibling().select();
		return false;
	}else{
		if(key==13){
			this.toggle();
		}
	}
	window.event.returnValue=false;
	window.event.cancelBubble=true;
}
TreeItem.prototype._showParent=function(){
	
	if ( this.parent ){
		this.parent._showParent();		
		this.parent.expand();
	}
}
TreeItem.prototype.hover=function(){
	if(treeHandler.selected!=this){
		document.getElementById(this.id +"-text-anchor").className="hoverItem";	
	}
}

TreeItem.prototype.restore=function(){
	if(treeHandler.selected!=this){		
		document.getElementById(this.id +"-text-anchor").className="labelItem";	
	}

}
//////////////////////
//Check Box Item
/////////////////////
treeHandler.check=function(oItem){
	var objChk=this.all[oItem.id.replace("-checkbox","")];
	objChk.check(!objChk.checked);
}

function TreeCheckItem(sCaption,vChecked,vData){
	this.base=TreeItem;
	this.base(sCaption);
	this.checked=vChecked || false;
	this.NodeData=vData;
}
TreeCheckItem.prototype=new TreeItem;

TreeCheckItem.prototype._TreeItem_toString=TreeItem.prototype.toString; //保留原有的toString方法
TreeCheckItem.prototype.toString=function(){
//因为只是修改其中的字符串，为了方便，我就不重新拷贝代码，也没有使用regexp进行操作
	var tmp=document.createElement("div");
	tmp.innerHTML=this._TreeItem_toString();
	/*
	var objChk=document.createElement("input")
	objChk.id=this.id +"-checkbox";
	objChk.checked=this.checked;
	objChk.type="CheckBox";
	objChk.tabIndex=0;
	*/
	var objChk=document.createElement("span");
	objChk.className="CheckBoxItem";
	objChk.id=this.id +"-checkbox";
	objChk.onclick="treeHandler.check(this)";
	if (this.checked){
		objChk.innerText="R";	
	}
	else{
		objChk.innerText="T";
	}
	var txt=tmp.children[0];
	txt.children[txt.children.length-1].insertAdjacentElement("beforeBegin",objChk);
	return tmp.innerHTML;	
}

TreeCheckItem.prototype.check=function(b){
	if(b){
		this.checked=true;
		document.getElementById(this.id +"-checkbox").innerHTML="R";
	}
	else{
		this.checked=false;
		document.getElementById(this.id +"-checkbox").innerHTML="T";
	}
}
//////////////////////////////////////////
//注释的代码实现自定义选择的样式
/////////////////////////////////////////

TreeCheckItem.prototype.select=function(){
	if(treeHandler.selected ==this) return;
	if(treeHandler.selected){
		treeHandler.selected.unselect();
	}	
	var div=document.getElementById(this.id);	
	treeHandler.selected=this;	
	//div.className="selectedItem";	
	div.style.backgroundColor="activeCaption";
	div.style.color="window";
	var root=this._root();
	if(root.onSelected){
		if(typeof root.onSelected=="function"){
			root.onSelected(this);
		}
		else{
			eval(root.onSelected);
		}
	}
	div.focus();
}
TreeCheckItem.prototype.unselect=function(){	
	document.getElementById(this.id).style.backgroundColor="";
	document.getElementById(this.id).style.color="";
	var root=this._root();
	if(root.onUnSelected){ //定义了处理函数
		if(typeof root.onUnSelected=="function"){
			root.onUnSelected(treeHandler.selected);
		}
		else{
			eval(root.onUnSelected);
		}
	}
}
TreeCheckItem.prototype.hover=function(){
	document.getElementById(this.id +"-text-anchor").className="hoverItem";	
}

TreeCheckItem.prototype.restore=function(){		
	document.getElementById(this.id +"-text-anchor").className="labelItem";	
}

////////////////////////////////////////////////////////////////////
// TreeObject
////////////////////////////////////////////////////////////////////
function TreeObject(sCaption){
	this.base=TreeItem;
	this.base(sCaption);
	this.onSelected=null;
	this.onUnSelected=null;
	this.onExpand=null;
	this.onCollapse=null;
}
TreeObject.prototype=new TreeItem;
TreeObject.prototype.write=function(){
	document.write(this.toString());
	this.expand();
}
TreeObject.prototype.selected=function(){
	return treeHandler.selected;
}

//////////////////////////////////////////////
// XLoadTreeItem
//
/////////////////////////////////////////////
function TreeXLoadItem(sText,sSrc,sAction,sTarget,sOpenImage){
	this.base=TreeItem;
	this.base(sText,sAction,sTarget,sOpenImage);
	this.loaded=false;
	this.loading=false;
	this.xmlSrc=sSrc;
	this._loadingItem=new TreeItem("Loading");
	this.add(this._loadingItem);
	
}

TreeXLoadItem.prototype=new TreeItem;
TreeXLoadItem.prototype._TreeItem_expand=TreeItem.prototype.expand; //rem treeitem's method "expand"

TreeXLoadItem.prototype.expand=function(){
	if(!this.loaded){
		this._TreeItem_expand();		
		_startLoadXmlTree(this.xmlSrc, this);
	}
	else{
		this._TreeItem_expand();
	}
}
//load2
function TreeXLoadItem2(sText,sSrc,sAction,sTarget,sOpenImage){
	this.base=TreeItem;
	this.base(sText,sAction,sTarget,sOpenImage);
	this.loaded=false;
	this.loading=false;
	this.xmlSrc=sSrc;
	this._loadingItem=new TreeItem("Loading");
	this.add(this._loadingItem);
	
}

TreeXLoadItem2.prototype=new TreeItem;
TreeXLoadItem2.prototype._TreeItem_expand=TreeItem.prototype.expand; //rem treeitem's method "expand"

TreeXLoadItem2.prototype.expand=function(){
	if(!this.loaded){
		this._TreeItem_expand();		
		_startLoadXmlTree2(this.xmlSrc, this);
	}
	else{
		this._TreeItem_expand();
	}
}
//开始下载数据2
function _startLoadXmlTree2(sSrc, jsNode) {
		var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
		xmlDoc.async =true;
		
		xmlDoc.onreadystatechange=function(){
			_picxmlFileLoaded(xmlDoc,jsNode);
		}
		window.setTimeout(function(){xmlDoc.loadXML(sSrc)},10);
}
//开始下载数据
function _startLoadXmlTree(sSrc, jsNode) {
		var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
		xmlDoc.async =true;
		
		xmlDoc.onreadystatechange=function(){
			_picxmlFileLoaded(xmlDoc,jsNode);
		}
		window.setTimeout(function(){xmlDoc.load(sSrc)},10);
}
//将xml转换成JS Node
function _xmlTreeToJsTree(oNode) {
	var text=oNode.getAttribute("text");
	var dirid=oNode.getAttribute("dirid");
	var src=oNode.getAttribute("src");
	var oJsNode;
	if(src !=null && src!=""){
		
		oJsNode=new TreeXLoadItem(text,src);
	}
	else{
		oJsNode=new TreeItem(text,dirid);
	}
	
	var cs = oNode.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		if (cs[i].tagName == "tree")
			oJsNode.add( _xmlTreeToJsTree(cs[i]));
	}
	
	return oJsNode;
}

//完成下载
function _picxmlFileLoaded(oXmlDoc, jsParentNode) {
	if(oXmlDoc.readyState==4){		
		//判断是否为空
		if( oXmlDoc == null || oXmlDoc.documentElement == null) {
			//alert(oXmlDoc.xml);
			//jsParentNode.errorText = parseTemplateString(webFXTreeConfig.loadErrorTextTemplate,
								//jsParentNode.src);
			jsParentNode._loadingItem.setCaption("加载错误");
			window.status ="加载错误";
			return ;
		}
		var oRoot=oXmlDoc.documentElement;	
		jsParentNode.loaded=true;	
		//alert(oXmlDoc.xml);
		jsParentNode.Nodes[0].remove();
		for(var i=0;i<oRoot.childNodes.length;i++){
			//alert(oRoot.childNodes[i].getAttribute("text"));
			jsParentNode.add(_xmlTreeToJsTree(oRoot.childNodes[i]));
		}
		jsParentNode.select();
	}
}