(function($) {
	
$.widget("ui.treeselect", {
	_init: function() {
		var _this=this;
		this.id=this.element.attr("id");
		
		this.container=$('<div class="'+this.options.cssPrefix+'"/>')
			.insertAfter(this.element);
			
		this.container.append(this.element);
		
		this.display=$('<ul class="'+this.options.cssPrefix+'-display"/>')
			.appendTo(this.container);
		
		this.selectButton=$('<input type="button" class="'+this.options.cssPrefix+'-selectbutton"/>')
			.click(function() {_this.select();})
			.appendTo(this.container);
		
//		this.clearButton=$('<input type="button" class="'+this.options.cssPrefix+'-clearbutton"/>')
//			.click(function() {_this.clear();})
//			.appendTo(this.container);
		
		this.popup=$('<div style="display:none"/>')
			.appendTo(this.container);
		
		
		
		var nodes=this.getNodeIds();
		if (nodes!=null && nodes!="" && nodes!="0")
		{
			this.setNodeIds(nodes);
		}
		else
		{
			this.clear()
		}
	},
	
	select: function() {
		var _this=this;
		
		var position=this.display.offset();
		var top=position.top+this.selectButton.height()+1-$(document.body).scrollTop();
		var left=position.left-$(document.body).scrollLeft();
		var width=this.container.width();
		
		this._loadPopup(function(content) {
			_this.popup.html(content)
				.treeview({
					url: _this.options.url,
					clickHandler: function(nodeId) {
						_this.addNode(nodeId);
						_this.popup.dialog("close");
					}
				})
				.dialog({
					dialogClass: _this.options.cssPrefix+"-popup",
					resizable: false,
					position: [left,top],
					width: width,
					minWidth: width,
					modal: true,
					open: function() {
						var closeAllDialogs=function() {
							$(document).one("click",function() {
								_this.popup.dialog("close");
							}); 
						}
						window.setTimeout(closeAllDialogs,1);
						$(this).bind("click",function() {return false;});
					},
					close: function() {
						$(this).dialog("destroy");
					}
				});
		});
	},
	
	clear: function() {
		this.element.val("");
		this.display.text(this.options.emptyText);
		this.element.change();
	},
	
	setNodeIds: function(nodeIds) {
		if (nodeIds==null) this.clear();
		this.element.val(nodeIds);
		this._loadNodes();
	},
	
	getNodeIds: function() {
		return this.element.val();
	},
	
	addNode: function(id) {
		var values=this.element.val().split(",");
		if ($.inArray(id,values)==-1) {
			values.push(id);
			this.setNodeIds(values.join(","));
		}
	},
	
	removeNode: function(id) {
		var values=this.element.val().split(",");
		if ($.inArray(id,values)>-1) {
			var newValues=new Array();
			for (var i=0; i<values.length; i++) {
				if (values[i]!=id) {
					newValues.push(values[i]);
				}
			}
			this.setNodeIds(newValues.join(","));
		}
	},
	
	_displayNodes: function(data) {
		var _this=this;
		if (data!=null && data.length>0) {
			var idlist=[];
			this.display.empty();
			for (var i=0; i<data.length; i++) {
				var node=data[i];
				idlist.push(node.id);
				var nodeDisplay=$('<li _id="'+node.id+'" class="'+_this.options.cssPrefix+'-entry" title="'+node.name.replace('"','&quot;')+'">'+node.name+'</li>').hover(function() {
					$('<a href="javascript:;" title="'+node.name.replace('"','&quot;')+' entfernen"></a>').click(function() {
						_this.removeNode($(this).parent().attr("_id"));
					}).appendTo($(this).addClass("multiselect-entry-hover"));
				},function() {
					$(this).removeClass("multiselect-entry-hover").find("a").remove();
				});
				this.display.append(nodeDisplay);
			}
			this.element.val(idlist);
		} else {
			this.clear();
		}
		if (this.popup) 
			this.popup.dialog("close");
	},
	
	_loadNodes: function() {
		var _this=this;
		var data={
			action: "nodes", 
			nodeIds: this.getNodeIds()
		};
		$.post(this.options.url,data,function(response) {
			_this._displayNodes(response.content);
		},"json");
	},
	
	_loadPopup: function(onSuccess) {
		var data={
			nodeId: 0,
			action: "content",
			nodeIds: this.getNodeIds()
		}
		$.post(this.options.url,data,function(response) {
			onSuccess(response.content);
		},"json");
	}
});

//default options
$.extend($.ui.treeselect, {
	version: "0.1",
	defaults: {
		url: "/data.ajaxinput",
		cssPrefix: "multiselect",
		selectButtonSuffix: "_selectbutton",
		clearButtonSuffix: "_clearbutton",
		popupSuffix: "_popup",
		emptyText: "Bitte wählen...",
		height: 250
	}
});

})(jQuery);
