
;(function($) {
function load(settings, root, child, container) {
	function createNode(parent) {
        var current = $("<li/>");
        current.attr("id",this.id);
        var state = "";
        if(this.type=="shool")
    
        state = this.show?"(<font color='green'>可选</font>)":"(<font color='#a9a9a9'>隐藏</font>)";  
        
//        current.html("<span><a href='javascript:void(0)' onclick=\"openframe(this,'"+this.url+"')\">"+ this.text+state+(this.count==null?"":"("+this.count+")")+"</a></span>");
        else if(this.type=="teacher")
        state = this.state==0?"(<font color='green'>在职</font>)":this.state==1?"(<font color='#a9a9a9'>离职</font>)":this.state==2?"(<font color='#0099Cc'>退休</font>)":"";
        current.html("<span><a href='javascript:void(0)' onclick=\"openframe(this,'"+this.url+"')\">"+ this.text+state+"</a></span>");
            
        current.appendTo(parent);
		if (this.classes) {
			current.children("span").addClass(this.classes);
		}
		if (this.expanded) {
			current.addClass("open");
		}
		if (this.hasChildren || this.children && this.children.length) {
			var branch = $("<ul/>").appendTo(current);
			if (this.hasChildren) {
				current.addClass("hasChildren");
				createNode.call({
					classes: "placeholder",
					text: "&nbsp;",
					children:[]
				}, branch);
			}
			if (this.children && this.children.length) {
				$.each(this.children, createNode, [branch])
			}
		}
	}
	$.ajax($.extend(true, {
		url: settings.url,
		dataType: "json",
		data: {
			root: root
		},
		success: function(response) {
			child.empty();
			$.each(response, createNode, [child]);
	        $(container).treeview({add: child});
	    }
	}, settings.ajax));
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;
	if (!container.children().size())
		load(settings, "source", this, container);
	var userToggle = settings.toggle;
	return proxied.call(this, $.extend({}, settings, {
		collapsed: true,
		toggle: function() {
			var $this = $(this);
			if ($this.hasClass("hasChildren")) {
				var childList = $this.removeClass("hasChildren").find("ul");
				load(settings, this.id, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);