;(function($) {

function load(settings, root, child, container) {
	function createNode(parent) {
		var isWas = $('li[name="'+this.name+'"]').length && this.name != "ph0";
		var add = '<div class="hitarea hasChildren-hitarea closed-hitarea expandable-hitarea"></div>';
		if (!this.hasChildren)
			add ='';
		var current = null;
		if (this.name == "ph0") {
			current = $("<li/>").css('font-weight', 'normal').attr("id", this.id || "").html('<span class="placeholder">&nbsp;</span>');
		} else {
			current = $("<li/>").css('font-weight', 'normal').attr("id", this.id || "").attr("name", this.name || "").html(add + "<nobr><span><img src='" + this.icon+ "' class='navigation_image'/> <A href='businessmodel.php?oguid="+ this.name +"' title='" + this.text.split("&frasr;").join("\\") + "'>" + this.text.split("&frasr;").join("\\") + "</a></span></nobr>");
		}

		if ( !isWas )
			current.appendTo(parent);
		else
			current = $('li[name="'+this.name+'"]')[0];

		if ( !isWas && this.name != "ph0" && this.classes ) {
			current.children("span").addClass(this.classes);
		}

		if ( !isWas && this.expanded ) {
			current.addClass("open");
		}


		if (this.hasChildren || this.children && this.children.length) {
			if( !isWas ) {
				var branch = $("<ul/>").attr("style", "display: none").appendTo(current);
				if (this.hasChildren) {
					branch.html('<li><span class="placeholder">&nbsp;</span></li>');
					current.addClass("hasChildren");
					current.addClass("closed");
				}
				if (this.children && this.children.length) {
					$.each(this.children, createNode, [branch]);
				}
			} else {
				var branch = current.children('ul');
				if (!branch)
					branch = $("<ul/>").appendTo(current);
				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);