;(function ($) {
/*
 *	jQuery AdubyTree Plugin
 *	version: 2.0 (2009-02-20)
 *
 * 	Copyright (c) 2008, Crystal, shimingxy@163.com
 * 	Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 * 	Date: 2009-02-20 rev 9
 *
 */
$.adubytree = $.adubytree||{};

$.fn.AdubyTree = function(config ) {
	var _this	= this;
	nodeConfig = {
		data				: 'Tree Item',
		icon      			: (config.themes || 'themes/basic/images/')+'Folder.gif',
		openIcon  			: (config.themes || 'themes/basic/images/')+'FolderOpen.gif',
		leafIcon    		: (config.themes || 'themes/basic/images/')+'Leaf.gif',
		iIcon       		: (config.themes || 'themes/basic/images/')+'I.gif',
		lIcon       		: (config.themes || 'themes/basic/images/')+'L.gif',
		lMinusIcon  		: (config.themes || 'themes/basic/images/')+'Lminus.gif',
		lPlusIcon   		: (config.themes || 'themes/basic/images/')+'Lplus.gif',
		tIcon       		: (config.themes || 'themes/basic/images/')+'T.gif',
		tMinusIcon  		: (config.themes || 'themes/basic/images/')+'Tminus.gif',
		tPlusIcon   		: (config.themes || 'themes/basic/images/')+'Tplus.gif',
		emptyIcon			: (config.themes || 'themes/basic/images/')+'Empty.gif',
		uncheckIcon			: (config.themes || 'themes/basic/images/')+'uncheck.gif',
		uncheckHoverIcon	: (config.themes || 'themes/basic/images/')+'uncheck_hover.gif',
		checkedIcon			: (config.themes || 'themes/basic/images/')+'checkecd.gif',
		checkedHoverIcon	: (config.themes || 'themes/basic/images/')+'checked_hover.gif',
		checkedAllIcon		: (config.themes || 'themes/basic/images/')+'checkall.gif',
		checkedAllHoverIcon	: (config.themes || 'themes/basic/images/')+'checkedall.gif',
		loadingIcon			: (config.themes || 'themes/basic/images/')+'loading.gif',
		jsaction   			: 'javascript:void(0);',
		checked				: false,
		open				: false,
		selected			: false,
		loaded				: false,
		haschild			: false,
		children			: []
	};
	//default AdubyTree Config Settings
	config = $.extend({
		url				: '',
		datatype		: "json",
		type			: "GET",
		cookie			: true,
		rootopened      : true,
		prefix 			: null,
		themes			: "",
		altRows			: true,
		selarrrow		: [],
		savedRow		: [],
		selrow			: null,
		onSelected		: null,
		onDbClick		: null,
		onOpen			: null,
		onClose			: null,
		onChecked		: null,
		onAjaxLoad		: null,
		loadComplete	: null,
		loadonce		: false,
		selected		: "",
		checkboxes		: false,
		checkboxesOnlyLeafs		: false,
		multikey		: null,
		nodeConfig		: nodeConfig
		}, config || {});
	_this.config	= config;

	var adubyTree ={
		isClick    : true,//is Click on checkbox
		selectedNode:null,
		//Convert node Json to html
		parseNode : function (node) {
			var str ="";
			if(node.indent&&node.indent.length){
				for(var i=1 ;i < node.indent.length -1; i++) {
					if(node.indent[i] == 0){
						str	+=	"<img src='"+node.iIcon+"' alt='' />";
					}else{
						str	+=	"<img src='"+node.emptyIcon+"' alt='' />";
					}
				}
			}
			if(node.haschild){
				if(node.indent.length > 1){
					if(node.open){
						if(node.indent[node.indent.length-1] == 1){
							str	+= 	"<img id='pm-"+node.id+"' class='plusminus last' src='"+node.lMinusIcon+"' alt='' />";
						}else{
							str	+= 	"<img id='pm-"+node.id+"' class='plusminus' src='"+node.tMinusIcon+"' alt='' />";
						}
					}else{
						if(node.indent[node.indent.length-1 ]== 1){
							str	+= 	"<img id='pm-"+node.id+"' class='plusminus  last' src='"+node.lPlusIcon+"' alt=''  />";
						}else{
							str	+= 	"<img id='pm-"+node.id+"' class='plusminus' src='"+node.tPlusIcon+"' alt=''/>";
						}
					}
				}
				if(node.open){
					str	+= 	"<img id='fd-"+node.id+"' class='folder open' src='"+node.openIcon+"' alt=''/>";
				}else{
					str	+= 	"<img id='fd-"+node.id+"' class='folder'  src='"+node.icon+"' alt=''  />";
				}
			}else{
				if(node.indent[node.indent.length-1] == 0){
					str	+= 	"<img src='"+node.tIcon+"' alt='' />";
				}else{
					str	+= 	"<img src='"+node.lIcon+"' alt='' />";
				}
				str	+= 	"<img id='fd-"+node.id+"' class='leaf' src='"+node.leafIcon+"' alt='' />";
			}

			if(this.config.checkboxes && (!this.config.checkboxesOnlyLeafs || !node.haschild)){
				str	+= 	"<img id='ckbx-"+node.id+"'  class='checkbox'  src='"+node.uncheckIcon+"' alt='' />";
			}
			if(node.selected){
				str	+= 	"<a id='"+node.id+"' name='"+node.id+"' class='node  selected' href='"+ node.jsaction +"'  pid='"+node.parentid+"'  >";
			}else{
				str	+= 	"<a id='"+node.id+"' name='"+node.id+"' class='node' href='"+node.jsaction +"'   pid='"+node.parentid+"' >";
			}
			return str + node.data + "</a>";
		},

		// Convert Json to Html
		parseJSON : function (data,indent,pid) {
			data 		= 	data || this.config.data;
			var node 	=  $.extend({},this.config.nodeConfig,data);
			var indent 	=	indent || [0];
			var pid		= pid || this.config.data.id;
			var str		=	"<div  class='adubytree'>";
			data.indent	= [];
			data.checked = data.checked ? true : false;
			for(var i = 0; i < indent.length; i++) {
				data.indent.push(indent[i]);
			}
			if(this.config.prefix) node.id = this.config.prefix + node.id;
			if(data.children  && data.children.length){
				str	+= this.parseNode($.extend(node,{indent:indent},{haschild :true},{parentid :pid}));
				if(node.open){
					str	+=	"<div id='div-"+node.id+"' class='adubytree'>";
				}else{
					str	+=	"<div id='div-"+node.id+"' class='adubytree' style='display:none'>";
				}
				for(var i = 0; i < data.children.length; i++) {
					(i == data.children.length -1) ? indent.push(1) : indent.push(0);
					str += this.parseJSON(data.children[i],indent,node.id);
					indent.pop();
				}
				str	+=	"</div>";
			}else if(this.config.url){
				str	+= this.parseNode($.extend(node,{indent:indent},{parentid :pid}));
			}else {
				str	+= this.parseNode($.extend(node,{indent:indent},{haschild :false},{parentid :pid}));
			}

			if(node.open){
				str	+=	"<div id='div-"+node.id+"' class='adubytree'></div>";
			}else{
				str	+=	"<div id='div-"+node.id+"' class='adubytree' style='display:none'></div>";
			}
			return str	+=	"</div>";
		},
		//Open one Tree Node and set node open =true
		open : function(node_id,data) {
			data = data || this.config.data;
			node_id = node_id || this.config.data.id;
			var node = $.extend({},this.config.nodeConfig,data);
			if(this.config.url){
				if(node.haschild && node.loaded == false && data.id==node_id){
					data.loaded =true;
					data.open=false;
					_this = this;
					$(this.elem).find("#fd-"+node.id).attr("src",node.loadingIcon);
					if(this.config.dataType=="xml"){
						$.ajax({url: this.config.url,type: this.config.type || "POST",dataType:this.config.dataType,data:{ id : 0 ||node_id},timeout: 600000,
							error: function(){alert('Error loading XML document');},
							complete:function(xmldata){
							    stripWhiteSpace(xmldata.responseXML);
								_this.addNode(_this.getJsonFromXml(xmldata.responseXML,false,"xml"),node_id);
								$(_this.elem).html(_this.parseJSON());
								_this.open(node_id);
								if (_this.config.onAjaxLoad) {
                                    _this.config.onAjaxLoad.call(null);
                                }
							}
						});
					}else{
						$.getJSON(this.config.url, { id : 0 ||node_id}, function (jsondata) {
							_this.addNode(jsondata,node_id);
							$(_this.elem).html(_this.parseJSON());
							_this.open(node_id);
						});
					}
					if (this.config.onOpen) {
					    this.config.onOpen.call(null,node_id);
					}
					return;
				}
			}
			if(data.children  && data.children.length){
				if(data.id==node_id){
					data.open=true;
					var node = $.extend({},this.config.nodeConfig,data);
					if(this.config.prefix) node.id = this.config.prefix + node.id;
					$(this.elem).find("#div-"+node.id).slideDown({duration:500, easing: 'easeOutBounce'});
					$(this.elem).find("#fd-"+node.id).attr("src",node.openIcon);
					$(this.elem).find("#fd-"+node.id).addClass("open");
					if($("#"+node.id).hasClass("last")){
						$(this.elem).find("#pm-"+node.id).attr("src",node.lMinusIcon);
					}else{
						$(this.elem).find("#pm-"+node.id).attr("src",node.tMinusIcon);
					}
					return;
				}
				for(var i = 0; i < data.children.length; i++) {
					this.open(node_id,data.children[i]);
				}
			}
		},
		//Close one Tree Node and set node open =false
		close : function(node_id,data) {
			data = data || this.config.data;
			if(data.children  && data.children.length){
				if(data.id == node_id){
					data.open=false;
					var node = $.extend({},this.config.nodeConfig,data);
					if(this.config.prefix) node.id = this.config.prefix + node.id;
					$(this.elem).find("#fd-"+node.id).attr("src",node.icon);
					$(this.elem).find("#fd-"+node.id).removeClass("open");
					if($("#"+node.id).hasClass("last")){
						$(this.elem).find("#pm-"+node.id).attr("src",node.lPlusIcon);
					}else{
						$(this.elem).find("#pm-"+node.id).attr("src",node.tPlusIcon);
					}
					$(this.elem).find("#div-"+node.id).slideUp({duration:500, easing: 'easeOutBounce'});
				}
				for(var i = 0; i < data.children.length; i++) {
					this.close(node_id,data.children[i]);
				}
			}
		},
		//Check is the Tree Node open, if open return true or return false
		isOpen : function(node_id){
			return $(this.elem).find("#fd-"+(this.config.prefix ? this.config.prefix+node_id :node_id)).hasClass("open");
		},
		//Open All Tree Node and set node open =true
		openAll : function(data){
			data = data || this.config.data;
			if(data.children  && data.children.length){
				data.open = true;
				var node = $.extend({},this.config.nodeConfig,data);
				if(this.config.prefix) node.id = this.config.prefix + node.id;
				$(this.elem).find("#div-"+node.id).slideDown();
				$(this.elem).find("#fd-"+node.id).attr("src",node.openIcon);
				$(this.elem).find("#fd-"+node.id).addClass("open");
				if($("#"+node.id).hasClass("last")){
					$(this.elem).find("#pm-"+node.id).attr("src",node.lMinusIcon);
				}else{
					$(this.elem).find("#pm-"+node.id).attr("src",node.tMinusIcon);
				}
				for(var i = 0; i < data.children.length; i++) {
					this.openAll(data.children[i]);
				}
			}
		},
		//Close All Tree Node and set node open =false
		closeAll : function(data){
			data = data || this.config.data;
			if(data.children  && data.children.length){
				data.open = false;
				var node = $.extend({},this.config.nodeConfig,data);
				if(this.config.prefix) node.id = this.config.prefix + node.id;
				$(this.elem).find("#div-"+node.id).slideUp();
				$(this.elem).find("#fd-"+node.id).attr("src",node.icon);
				$(this.elem).find("#fd-"+node.id).removeClass("open");
				if($("#"+node.id).hasClass("last")){
					$(this.elem).find("#pm-"+node.id).attr("src",node.lPlusIcon);
				}else{
					$(this.elem).find("#pm-"+node.id).attr("src",node.tPlusIcon);
				}
				for(var i = 0; i < data.children.length; i++) {
						this.closeAll(data.children[i]);
				}
			}
		},
		//Change a Tree Node status,if node is open,change the node to close,or change to open
		changeStatus : function(node_id){
			//alert(node_id+$(this.elem).find("#fd-"+node_id).hasClass("open"));
			node_id =node_id.substring((this.config.prefix ? this.config.prefix:"").length);//(this.config.prefix ? this.config.prefix+node_id :node_id);
			if($(this.elem).find("#fd-"+(this.config.prefix ? this.config.prefix+node_id :node_id)).hasClass("open")){
				this.close(node_id);
			}else{
				this.open(node_id);
			}
		},

		//Add a new node to current Aduby Tree
		addNode : function(node,pnode_id,data){
			pnode_id = pnode_id || this.config.data.id;
			data = data || this.config.data;
			if(data.id==pnode_id){
				data.children =	data.children || [];
				if(this.config.url)data.loaded = true;
				if(node.constructor==Array){
					for(var i=0;i < node.length;i++){
						node[i].open=false;
						node[i].loaded=false;
						data.children.push(node[i]);}
				}else{
					data.children.push(node);
				}
			}else
			if(data.children  && data.children.length){
				for(var i = 0; i < data.children.length; i++) {
					this.addNode(node,pnode_id,data.children[i]);
				}
			}
		},
		//Remove a Tree node from current Aduby Tree
		remove : function(node_id,data){
			data = data || this.config.data;
			if(data.children  && data.children.length){
				var dataChild=[];
				var isRemove =false;
				for(var i = 0; i < data.children.length; i++) {
					if(data.children[i].id==node_id){
						isRemove=true;
					}else{
						dataChild.push(data.children[i]);
					}
					this.remove(node_id,data.children[i]);
				}
				if(isRemove){
					data.children=dataChild;
					return;
				}
			}
		},
		//get a Tree node from node_id Aduby Tree
		getNode : function(node_id,data,pNode){
			data = data || this.config.data;
			pNode = pNode || this.config.data;
			if(data.id==node_id){
				var node = $.extend({},this.config.nodeConfig,data);
				node.parent=pNode;
				this.selectedNode =node;
				return ;
			}
			if(data.children  && data.children.length){
				for(var i = 0; i < data.children.length; i++) {
					this.getNode(node_id,data.children[i],data);
				}
			}
		},
		mouseOver :function(elem,type){
			if(type == "mouseover"){
				if($(elem).hasClass("checked")){
					$(elem).attr("src",this.config.nodeConfig.checkedHoverIcon);
				}else{
					$(elem).attr("src",this.config.nodeConfig.uncheckHoverIcon);
				}
			}else{
				if($(elem).hasClass("checked")){
					$(elem).attr("src",this.config.nodeConfig.checkedIcon);
				}else{
					$(elem).attr("src",this.config.nodeConfig.uncheckIcon);
				}
			}
		},
		setCheckStatus : function(elem){
			if($("#ckbx-"+elem).hasClass("checked")){
				$("#ckbx-"+elem).removeClass("checked");
				$("#ckbx-"+elem).attr("src",this.config.nodeConfig.uncheckIcon);
			}else{
				$("#ckbx-"+elem).addClass("checked");
				$("#ckbx-"+elem).attr("src",this.config.nodeConfig.checkedIcon);
			}
		},
		setCheckStatusAll : function(elem){
			_this = this;
			this.setCheckStatus(elem);
			if($("#ckbx-"+elem).hasClass("checked")){
				$("#div-"+elem).find('.checkbox').each(function(i){
						$(this).removeClass("checked");
						$(this).attr("src",_this.config.nodeConfig.uncheckIcon);
					});
			}else{
				$("#div-"+elem).find('.checkbox').each(function(i){
						$(this).addClass("checked");
						$(this).attr("src",_this.config.nodeConfig.checkedIcon);
					});
			}
			while( elem != this.config.data.id){
				elem = $("#"+elem).attr( "pid" );
				if(!$("#ckbx-"+elem).hasClass("checked") ){
					$("#ckbx-"+elem).addClass("checked");
					$("#ckbx-"+elem).attr("src",_this.config.nodeConfig.checkedIcon);
				}
			}
		},
		getChecked : function(){
			var strCheckedNodes ="";
			_this = this;
			$(this.elem).find('img.checked').each(function(i){
						strCheckedNodes +=this.id.substring(("ckbx-"+(_this.config.prefix ? _this.config.prefix:"")).length) +",";
			});
			return strCheckedNodes.substring(0,strCheckedNodes.length -1 );
		},
		getOpened : function(){
			var strOpenNodes ="";
			$(this.elem).find('img.open').each(function(i){
						strOpenNodes +=this.id.substring(("fd-"+ (_this.config.prefix ? _this.config.prefix:"")).length) +",";
			});
			return strOpenNodes.substring(0,strOpenNodes.length -1 );
		},
		//Get Tree selected nodes
		getSelected : function(){
			return (this.selected)? this.selected.substring((this.config.prefix ? this.config.prefix:"").length) : '';
		},
		//Change Tree Node selected  status
		setSelect : function(elem){
			if(this.selected){
				$("#"+this.selected).removeClass("selected");
			}
			this.selected = elem;
			if (this.selected && '' != this.selected) {
			    $("#"+elem).addClass("selected");
            }
		},
		refresh : function(){
			$(this.elem).html(this.parseJSON());
			this.applyCookie();
		},

		clearCookie : function(){
			$.cookie(this.elem.id+'_Opened', null);
			//$.cookie(this.elem.id+'_Checked',null);
			$.cookie(this.elem.id+'_Selected',null);
		},

		setCookie : function(type){
			if(this.config.cookie){
				switch(type) {
					case "selected":
						$.cookie(this.elem.id+'_Selected', this.getSelected());
						break;
					case "checked":
						//$.cookie(this.elem.id+'_Checked', this.getChecked());
						break;
					case "opened":
						$.cookie(this.elem.id+'_Opened', this.getOpened());
					break;
				}
			}
		},
		modify : function(node_id,node,data) {
			data = data || this.config.data;
			if(data.id == node_id){
				data=$.extend(node,data);
				return;
			}
			if(data.children  && data.children.length){
				for(var i = 0; i < data.children.length; i++) {
					this.modify(node_id,node,data.children[i]);
				}
			}
		},
		getCookie : function(type){
			var cookie ;
			switch(type) {
				case "opened":
					cookie = $.cookie(this.elem.id+'_Opened');
					break;
				case "checked":
					cookie = $.cookie(this.elem.id+'_Checked');
					break;
				case "selected":
					cookie = $.cookie(this.elem.id+'_Selected');
					break;
			}
			return cookie ? cookie : "";
		},
		applyCookie : function(type){
			var openedCookies = this.getCookie("opened").split(",");
			for(var i=0;i<openedCookies.length;i++){
				this.open(openedCookies[i]);
			}
			var checkedCookies = this.getCookie("checked").split(",");
			for(var i=0;i<checkedCookies.length;i++){
				this.setCheckStatus((_this.config.prefix ? _this.config.prefix:"")+checkedCookies[i]);
			}
			this.setSelect((_this.config.prefix ? _this.config.prefix:"")+this.getCookie("selected"));
		},
		xmlToObject: function(xml){
			var node={};
			for(var i=0;i<xml.childNodes.length &&xml.hasChildNodes();i++ ){
				var nodeName = (xml.childNodes[i].nodeName).toUpperCase();
				var nodeValue =xml.childNodes[i].textContent  || xml.childNodes[i].text
				if ('' == nodeValue) {
				    continue;
				}
				if(nodeName == "ID"){
					node.id = nodeValue;
				}else if(nodeName == "DATA"){
					node.data = nodeValue;
				}else if(nodeName == "HASCHILD"){
					node.haschild =  nodeValue=="true" ? true: false;
				}else if(nodeName == "JSACTION"){
					node.jsaction =  nodeValue;
				}else if(nodeName == "ICON"){
					node.icon =  nodeValue;
				}else if(nodeName == "OPENICON"){
					node.openIcon =  nodeValue;
				}else if(nodeName == "LEAFICON"){
					node.leafIcon =  nodeValue;
				}else if(nodeName == "SELECTED"){
					node.selected =  nodeValue;
				}else if(nodeName == "OPEN"){
					node.open =  nodeValue;
				}else if(nodeName == "CHECKED"){
					node.checked =  nodeValue=="true" ? true: false;
				}
			}
			return node;
		},
		getJsonFromXml: function(xml,includeRoot,type){
			var xmlDoc;
			if(typeof(xml)!='object'){
				xml=xml.substring(xml.indexOf("<root>"));
				try {//Internet Explorer
					xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
					xmlDoc.async=false;
					xmlDoc.loadXML(xml);
				//	alert(xmlDoc.childNodes[0].text);
				}catch(e){
					try {//Firefox, Mozilla, Opera, etc.
						//xmlDoc=(new DOMParser()).parseFromString(xml,"text/xml");
						xmlDoc = GXml.parse(xml);
					}catch(e) {alert(e.message)}
				}
				xmlDoc =  xmlDoc.childNodes[0];
			}else{
			    xmlDoc=xml;
			    if (document.all) {
                    xml = xml.documentElement;
                }
			}
			var tree_obj = type ? [] :this.xmlToObject(xmlDoc);

            if (!includeRoot) {
                for(var i=0;i<xmlDoc.childNodes.length &&xmlDoc.hasChildNodes();i++ ) {
                    var parentNode = xmlDoc.childNodes[i];
                    if (parentNode.nodeName == 'root') {
                        for(var k=0;k<parentNode.childNodes.length && parentNode.hasChildNodes();k++) {
                            var node=parentNode.childNodes[k];
                            if((node.nodeName).toUpperCase() == "CHILDREN") {
                                xmlDoc = node;
                                break;
                            }
                        }
                    }
                }
            }

			if(type){
				for(var i=0;i<xmlDoc.childNodes.length &&xmlDoc.hasChildNodes();i++ ){

				    var parentNode = xmlDoc.childNodes[i];
				    if ('xml' == parentNode.nodeName) {
				        continue;
				    }
					var length = tree_obj.push(this.xmlToObject(parentNode));

					for(var k=0;k<parentNode.childNodes.length && parentNode.hasChildNodes();k++){
                        var node=parentNode.childNodes[k];
                         if((node.nodeName).toUpperCase() == "CHILDREN"){
                            tree_obj[length - 1].children = [];
                            for(var j=0;j<node.childNodes.length &&node.hasChildNodes();j++ ){
                                tree_obj[length - 1].children.push(this.getJsonFromXml(node.childNodes[j]));
                            }
                        }
                    }
				}

			}else{
				for(var i=0;i<xmlDoc.childNodes.length &&xmlDoc.hasChildNodes();i++ ){
					var node=xmlDoc.childNodes[i];
					 if((node.nodeName).toUpperCase() == "CHILDREN"){
						tree_obj.children = [];
						for(var j=0;j<node.childNodes.length &&node.hasChildNodes();j++ ){
							tree_obj.children.push(this.getJsonFromXml(node.childNodes[j]));
						}
					}
				}
			}
			return tree_obj;
		},
		loadTree	: function(){
			$(this.elem).append(this.parseJSON());
			if (this.config.cookie) {
			    this.applyCookie();
			}
			if (this.config.rootopened) {
                this.open();
            } else {
                this.close();
			}
		}
	};
	//
	$.fn.getChecked = function () {
		return this[0].adubyTree.getChecked();
	};

	$.fn.getSelected = function () {
		return this[0].adubyTree.getSelected();
	};
	$.fn.getNode = function (node_id) {
		this[0].adubyTree.getNode(node_id);
		return this[0].adubyTree.selectedNode;
	};

	$.fn.refresh = function () {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.refresh();
		});
	};
	$.fn.openAll = function () {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.openAll();
		});
	};
	$.fn.setCheckStatus = function (node_id) {
	    return this.each( function() {
	        if(this.adubytree) return;
			this.adubyTree.setCheckStatus(node_id);
		});
	}
	$.fn.setSelected = function (node_id) {
	    return this.each( function() {
	        if(this.adubytree) return;
			this.adubyTree.setSelect(node_id);
		});
	}
	$.fn.closeAll = function () {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.closeAll();
		});
	};
	$.fn.addNode = function (newNode,pnode_id) {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.addNode(newNode,pnode_id);
			this.adubyTree.open(pnode_id);
			this.adubyTree.refresh();
		});
	};
	$.fn.modify = function (node_id,node) {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.modify(node_id,node);
			this.adubyTree.refresh();
		});
	};

	$.fn.removeNode = function (node_id) {
		return this.each( function() {
			if(this.adubytree) return;
			this.adubyTree.remove(node_id);
			this.adubyTree.refresh();
		});
	};
	return this.each( function() {
		if(this.adubytree) return;
		var _this= this;
		//default AdubyTree Node Config
		_this.adubyTree = $.extend({elem:_this},{config:config},adubyTree);
		// define events to Aduby Tree
		var applyEvents	= function(){
			$(_this).bind("click", function (event) {
				//
			}).listen("click", "img", function (event) {
				if($(this).hasClass("folder")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.changeStatus(this.id.substring("fd-".length));
					_this.adubyTree.setCookie("opened");

					if(_this.adubyTree.isOpen(this.id.substring("fd-".length))){
						if(_this.adubyTree.config.onOpen){
							_this.adubyTree.config.onOpen.call(null,this.id.substring("fd-".length));
						}
					}else{
						if(_this.adubyTree.config.onClose){
							_this.adubyTree.config.onClose.call(null,this.id.substring("fd-".length));
						}
					}
				}else if($(this).hasClass("plusminus")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.changeStatus(this.id.substring("pm-".length));
					_this.adubyTree.setCookie("opened");
					if(_this.adubyTree.isOpen(this.id.substring("fd-".length))){
						if(_this.adubyTree.config.onOpen){
							_this.adubyTree.config.onOpen.call(null,this.id.substring("fd-".length));
						}
					}else{
						if(_this.adubyTree.config.onClose){
							_this.adubyTree.config.onClose.call(null,this.id.substring("fd-".length));
						}
					}
				}else if($(this).hasClass("checkbox")){
					event.preventDefault();
					event.stopPropagation();
					//judge is click
					if(_this.adubyTree.isClick === true){
						_this.adubyTree.isClick = false;
						_this.adubyTree.setCheckStatus(this.id.substring("ckbx-".length));
						_this.adubyTree.setCookie("checked");
						if(_this.adubyTree.config.onChecked){
							_this.adubyTree.config.onChecked.call(null,this.id.substring("ckbx-".length));
						}
					}
					window.setTimeout(function(){_this.adubyTree.isClick = true;},400);
				}
				event.stopPropagation();
				return false;
			}).listen("dblclick", "a", function (event) {
				if($(this).hasClass("node")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.changeStatus(this.id);
					_this.adubyTree.setCookie("opened");
					if(_this.adubyTree.config.onDbClick){
						_this.adubyTree.config.onDbClick.call(null,this.id);
					}
					return false;
				}
			}).listen("dblclick", "img", function (event) {
				if($(this).hasClass("checkbox")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.setCheckStatusAll(this.id.substring("ckbx-".length));
					_this.adubyTree.setCheckStatus(this.id.substring("ckbx-".length));
					_this.adubyTree.setCookie("checked");
					return false;
				}
			}).listen("click", "a", function (event) {
				if($(this).hasClass("node")){
					_this.adubyTree.setSelect(this.id);
					_this.adubyTree.setCookie("selected");
					if(_this.adubyTree.config.onSelected){
						_this.adubyTree.config.onSelected.call(null,_this.adubyTree.getSelected());
					}
					return true;
				}
			}).listen("mouseover", "img", function (event) {
				if($(this).hasClass("checkbox")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.mouseOver(this,"mouseover");
					return false;
				}
			}).listen("mouseout", "img", function (event) {
				if($(this).hasClass("checkbox")){
					event.preventDefault();
					event.stopPropagation();
					_this.adubyTree.mouseOver(this,"mouseout");
					return false;
				}
			});

		};
		//Add events to Aduby Tree
		applyEvents();
		//start the init...
		$(_this).addClass("adubytree");
		if(_this.adubyTree.config.url){
			if(_this.adubyTree.config.dataType=="xml"){
				$.ajax({url: _this.adubyTree.config.url,type: _this.adubyTree.config.type || "POST",dataType: _this.adubyTree.config.dataType || "json",data:{ id : 0 ||_this.adubyTree.config.id},timeout: 600000,
					error: function(){alert('Error loading XML document');},
					complete:function(data){
					    stripWhiteSpace(data.responseXML);
						_this.adubyTree.config.data =_this.adubyTree.getJsonFromXml(data.responseXML,true,"xml")[0];
						_this.adubyTree.loadTree();
						if (_this.adubyTree.config.onAjaxLoad) {
							_this.adubyTree.config.onAjaxLoad.call(null);
						}
					}
				});
			}else{
				$.getJSON(_this.adubyTree.config.url, { id : 0 ||_this.adubyTree.config.id}, function (data) {
					_this.adubyTree.config.data =data[0];
					_this.adubyTree.loadTree();
				});
			}
		}else {
			if(_this.adubyTree.config.dataType=="xml"){
				_this.adubyTree.config.data =_this.adubyTree.getJsonFromXml(_this.adubyTree.config.data);
			}
			_this.adubyTree.loadTree();
		}
	});
};
})(jQuery);
