/*
 * 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) {
	function createNode(parent) {
		var current = $("<li/>");
		if(this.liClasses){
			current.addClass(this.liClasses);
		}
		
		current.attr("id", this.id || "").html("<span>" + this.text + "</span>").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");
			}
			if (this.children && this.children.length) {
				$.each(this.children, createNode, [branch])
			}
		}
	}
	
	child.empty();
	
	createNode.call({
				classes: "placeholder",
				liClasses: "last",
				text: "&nbsp;",
				children:[]
			}, child);	
	
	$.ajax($.extend(true, {
		url: settings.url + root,
		async: true,
		dataType: "json",
		data: {
			
		},
		success: function(response) {
			child.empty();
					
			$.each(response, createNode, [child]);
			$(container).PAF_TreeviewNator({add: child});
			$(container).find("#" + container.previousSelectedElementId).find(">span").addClass("selected");
			
			settings.afterLoad(root);
			
	    }
	}, settings.ajax));
}

var proxied = $.fn.PAF_TreeviewNator;
$.fn.PAF_TreeviewNator = 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);
			}
		},
		refreshNode: function(aNodeIdToRefresh){			
			if(aNodeIdToRefresh == 'mediapool_list'){
				load(settings, "source", container, container);
			}else{
				if(aNodeIdToRefresh == '' || aNodeIdToRefresh == 'selected_node'){
					aNodeIdToRefresh = container.previousSelectedElementId;
				}
				var childList = $(container).find("#"+aNodeIdToRefresh).find("ul");
				load(settings, aNodeIdToRefresh, childList, container);
			}
			
		},
		getSelectedNodeId: function(){
			return container.previousSelectedElementId;
		}
		
	}));
};

})(jQuery);

