/*
 * 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) {
	$.getJSON(settings.url, {root: root}, function(response) {
		function createNode(parent) {
			//modify from dwZone
			var testo = ""
			var target = ""
			if(this.url != ""){
				if(this.target != ""){
					var regEx = new RegExp(/^[\w]+_[\d]+_[\d]+$/)
					if(regEx.test(this.target)){
						var tmp = this.target.split("_")
						var popup = "javascript:window.open('" + this.url + "','" + tmp[0] + "','width=" + tmp[1] + ",height=" + tmp[2] + ",resizable=yes,scrollbars=yes').focus()"
						testo = '<a href="' + popup + '" >' + this.text + '</a>'
					}else{
						testo = '<a href="' + this.url + '" target="' + this.target +'" >' + this.text + '</a>'
					}
				}else{
					testo = '<a href="' + this.url + '" >' + this.text + '</a>'
				}
			}else{
				testo = this.text
			}
			var current = $("<li/>").attr("id", this.id || "").html("<span>" + testo + "</span>").appendTo(parent);						
			if (this.classes) {
				current.children("span").addClass(this.classes);
				current.children("span").children("a").addClass(this.classes);	
			}
			//modify from dwZone
			
			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;
	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");
				childList.empty();
				load(settings, this.id, childList, container);
			}
			if (userToggle) {
				userToggle.apply(this, arguments);
			}
		}
	}));
};

})(jQuery);