/*
 * Async Treeview 0.1 - Lazy-loading extension for Treeview
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 *
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */

;(function($) {

function load(settings, root, child, container, obj) {

	// Reusable function
	function createNode(parent) {
		var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
		if (this.classes) {
			current.children("span").addClass(this.classes);
		}
		if (this.childURL) {
			current.data("childURL", this.childURL);
		}
		else
		{
			current.data("childURL", "");
		}
		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({
					text:"Loading...",
					id:"placeholder",
					children:[]
				}, branch);
			}
			if (this.children && this.children.length) {
				$.each(this.children, createNode, [branch])
			}
		}
	}
		
	if(settings.initData)
	{
		$.each(settings.initData, createNode, [child]);
        $(container).treeview({add: child});
    
    settings.initData = "";
	}
	else
	{
		if(obj.data("childURL"))
		{
			settings.url = obj.data("childURL");
		}
		
		if(settings.url)
		{
			$.getJSON(settings.url, {root: root}, function(response) {
				$.each(response, createNode, [child]);
		        $(container).treeview({add: child});
		    }
			);
		}
	}
	
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	
	// If we don't have the "url" setting, then we just use the regular treeview
	if (!settings.url && !settings.initData) {
		return proxied.apply(this, arguments);
	}
	
	// If we DO have the "url" setting, then load the treeview with JSON-ed data from that URL
	// and make all the child nodes also load the same treeview.
	
	var container = this;
	load(settings, "source", this, container, $(this));
	
	var userToggle = settings.toggle;

	return proxied.call(this, $.extend({}, settings, {
		collapsed: true,
		toggle: function() {
			
			// When toggling a child element, run load again, but only update that node and pass this.id as the root
			var $this = $(this);
			if ($this.hasClass("hasChildren")) {
				var childList = $this.removeClass("hasChildren").find("ul");
				childList.empty();				
				load(settings, this.id, childList, container, $this);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}

	}));
};

})(jQuery);
