/*
 * 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,selectedCategoryID, child, container) {
	$.getJSON(settings.url, {root: root,categoryid:selectedCategoryID}, function(response) {
		function createNode(parent) {
		    var strHtml="";
		    if(this.hasChildren || this.children && this.children.length)
		        strHtml="<span>"+ this.text + "</span>";
		        else
		        strHtml="<a href='"+(this.href || "")+"' >" + this.text + "</a>";
			var current = $("<li/>").attr("id", this.id || "").html(strHtml).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({
						text:"placeholder",
						id:"placeholder",
						children:[]
					}, branch);
				}
				if (this.children && this.children.length) {
					$.each(this.children, createNode, [branch])
				}
			}
		}
		$.each(response, createNode, [child]);
        $(container).treeview({add: child});
    });
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;
	if(settings.load)
	{
	    var $this = $(this);
		if ($this.hasClass("hasChildren"))
		{
	        var childList = $this.removeClass("hasChildren").find("ul");
	        $this.addClass("open");
		    childList.empty();
		    childList.removeAttr("style");
	        load(settings, settings.id,settings.CategoryId, childList, 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");
				childList.empty();
				load(settings, this.id,0, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);