Element.implement({
	/*
	Event delegation - instead of attaching events to new elements, attach to parent and use bubbling to fire children events

	Useage:
	$("list").delegateEvent("click","li",function(e) { this==li },false,true);
	// or
	$("list").delegateEvent("click",function (el) { return Element.get(el,'tag')=="li"; },function(e) { this==li },false,true);
	*/
	
	delegateEvent:function (type,selector,fn,preventDefault,stopPropagation) {
		var check=$type(selector)=="function" ? selector : function (target) { return Element.match(target,selector) };
		return this.addEvent(type,function (e) {
			var target=e.target;
			while (target!=document.body) {
				if (check(target)) {
					if (preventDefault) e.preventDefault();
					if (stopPropagation) e.stopPropagation();
					return fn.apply($(target),[e]);
				}
				target=target.parentNode;
			}
		}.bind(this));
	}
});
