jQuery.extend({
	isDescendantOf: function (descendant, ancestor) {
		while (descendant) {
			if (descendant === ancestor) return true;
			descendant = descendant.parentNode;
		}
	}
});

/* NOTE: This does NOT work in the same way as bind("mouseenter", handler) or
   bind("mouseleave", handler). */
jQuery.fn.extend({
	mouseenter: function (handler) {
		this.each(function (idx, element) {
			$(element).mouseover(function (event) {
				var leaving = event.relatedTarget;
				if (!$.isDescendantOf(leaving, element)) {
					handler(event);
				}
				event.stopPropagation();
			});
		});
	},
	mouseleave: function (handler) {
		this.each(function (idx, element) {
			$(element).mouseout(function (event) {
				var entering = event.relatedTarget;
				if (!$.isDescendantOf(entering, element)) {
					handler(event);
				}
				event.stopPropagation();
			});
		});
	}
});

