/*
 * 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$
 * 
 * Modified by Pawel Aleksiun 21may2009: possible to add callback function to run after new node is added [settings.callback]
 *
 */

;(function($) {

function load(settings, root, child, container, obj_type) {
	if (root == 'source')
	{		
		elem = $("#structure-admin");
		if (elem.length == 0)
		{			
			if (settings.url.indexOf("m2=1")>0)
			{				
				elem = $("#admincompany");	
			}
			else
			{
				elem = $("#mycompany");	
			}
		}		
	}
	else
	{		
		elem = $("#"+root);
	}	
	addProgressIndicator(elem);
	$.getJSON(settings.url, {root: root, obj_type: (obj_type || "KTH")}, function(response) {
		removeProgressIndicator(elem);
		removeProgressIndicator($("#mycompany"));
		function createNode(parent) {
			var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>" + (this.menuTrigger?this.menuTrigger:'')).appendTo(parent);
			if (this.obj_type)
			{
				current.attr("obj_type", this.obj_type);
			}
			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});
        
        if (settings.callback instanceof Function) {
        	settings.callback(container, response);
        }
    });
}

var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
	if (!settings.url) {
		return proxied.apply(this, arguments);
	}
	var container = this;	
	if (settings.url.indexOf("chng=1")>0) var obj_type = "CHNG";
	load(settings, "source", this, container, obj_type);
	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, childList, container,$this.attr("obj_type"));
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);
