function $returnFalse() { return false; }

Function.implement({
	callOnce:function (bind) {
		if (!this.$alreadyCalled) this.call(bind);
		this.$alreadyCalled=true;
	},
	resetCall:function () {
		this.$alreadyCalled=null;
	},
	// use -- Math.cos.memoize(inValue)
    memoize: function(){
        var args = $A(arguments);
        return ((this.memoized || (this.memoized={}))[args] || (this.memoized[args]=this.apply(this, args)));
    }
});

Array.implement({
	removeDuplicates:function () {
		// TODO to implement
		return this;
	},
	pluck:function (property) {
		var a=[];
		this.each(function (o) { a.push(o?o[property]:null); });
		return a;
	},
	invoke:function (method,args) {
		var a=[];
		this.each(function (o) { a.push(o[method].apply(o,args || [])); });
		return a;
	}
});

//Element.prototype.$oldEmpty=Element.prototype.empty;

Window.implement({
	$E:function(selector) {
		return this.document.getElement(selector);
	},
	$ES:function(selector) {
		return this.document.getElements(selector);
	}
});
Element.implement({
	/*
	empty:function () {
		var tag=this.get("tag");
		if (["table","tbody","thead","tfoot","tr"].contains(tag)) return this.removeChildren();
		else return Element.prototype.$oldEmpty.call(this);
	},
	*/
	setHTML:function() {
		var html=Array.join(arguments,"");

		var tag=this.get("tag");
		var tableIdx=-1;
		switch (tag) {
			case "table":
				html="<table>"+html+"</table>";
				tableIdx=1;
				break;
			case "tbody": case "thead": case "tfoot":
				html="<table><"+tag+">"+html+"</"+tag+"></table>";
				tableIdx=2;
				break;
			case "tr":
				html="<table><tbody><tr>"+html+"</tr></tbody></table>";
				tableIdx=3;
				break;
		}
		
		html=html.trim().stripScripts(true);

		if (tableIdx>-1) {
			var div=new Element("div").set("html",html);
			var child=div;
			for (var i=0;i<=tableIdx;i++) child=child.firstChild;
			this.removeChildren().grab(child);
		}
		else this.innerHTML=html;
		return this;
	},
	show:function () {
		return this.set("display",true);
	},
	hide:function () {
		return this.set("display",false);
	},
	setVisibility:function (visible) {
		return this.set("visibility",visible);
	},
	visible:function () {
		return this.get("visibility");
	},

	toggle:function () {
		this.set("display","toggle");
	},

	hover:function (over,out) {
		return this.addEvent("mouseenter",over).addEvent("mouseleave",out);
	},
	setHoverClass:function (className) {
		if (!className) className="over";
		// only on ie6 since :hover is not working
		return Browser.Engine.trident4 ?
			this.hover(
				function () { this.addClass(className); },
				function () { this.removeClass(className); }
			) : this;
	},

	setSelection:function (b) {
		if (window.ie || window.opera) this[(b?"remove":"add")+"Event"]("selectstart",$returnFalse);
		if (window.gecko) this.style.MozUserSelect=b?"":"none";
		if (window.webkit) this.style.KhtmlUserSelect=b?"":"none";
		return this;
	},
	
	removeTextNodes:function () {
		if (this._removedTextNodes) return;
		$A(this.childNodes).each(function (o) {
			if (o.nodeType===3) {
				if (/^\s+$/.test(o.data)) o.parentNode.removeChild(o);
			}
			else $(o).removeTextNodes();
		});
		this._removedTextNodes=true;
		return this;
	},

	removeChildren:function () {
		while (this.hasChildNodes()) this.removeChild(this.lastChild);
		return this;
	},

	findParent:function (predicate) {
		var el=this;
		while (!predicate($(el)) && el && el!=document.documentElement) el=el.parentNode;
		return el===document.documentElement ? null : el;
	},

	replaceClass:function (oldClass,newClass) {
		this.removeClass(oldClass).addClass(newClass);
	},

	retrieveOrStore:function (key,getValueFunction) {
		if (!this.retrieve(key)) this.store(key,getValueFunction.call(this));
		return this.retrieve(key);
	},

	addReplacingEvent:function (type,fn) {
		return this.addEvent(type,function (e) {
			e.stop();
			fn.call(this,e);
		});
	},
	effects:function(options) {
		return new Fx.Morph(this,options);
	},
	effect:function(property,options) {
		options=$extend({property:property},options);
		return new Fx.Tween(this,options);
	},
	
	/*
	Event delegation - instead of attaching events to new elements, attach to parent and use bubbling to fire children events

	Useage:

	<ul id="list">
		<li>Foo</li>
		<li>Bar</li>
		<li>Bar</li>
	</ul>

	$("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!=this && target!=null) {
				if (check(target)) {
					if (preventDefault) e.preventDefault();
					if (stopPropagation) e.stopPropagation();
					return fn.apply($(target),[e]);
				}
				target=target.parentNode;
			}
		}.bind(this));
	},
	
	getThisOrParent:function (selector) {
		return Element.match(this,selector) ? this : this.getParent(selector);
	},
	getThisOrChild:function (selector) {
		return Element.match(this,selector) ? this : this.getElement(selector);
	},

	toQueryString: function(){
		var queryString = [];
		this.getElements('input, select, textarea').each(function(el){
			if (!el.name || el.disabled) return;
			var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
			$splat(value).each(function(val){
				queryString.push(el.name + '=' + encodeURIComponent(val));
			});
		});
		return queryString.join('&');
	}
});

Element.Properties.extend({
	visibility:{
		set:function (visible) {
			if (visible==="toggle") {
				this.set("visibility",!this.get("visibility"));
				return;
			}
			if (visible) this.removeClass("visibility-hidden").setStyle("visibility","");
			else this.addClass("visibility-hidden").setStyle("visibility","hidden");
		},
		get:function () {
			// check all parents for one that's not visible
			var p=this;
			while (p && p.get("tag")!="body" && p.getStyle("display")!="none" && p.getStyle("visibility")!="hidden") {
				p=p.getParent();
			}
			return p && p.get("tag")=="body";
		}
	},
	display:{
		set:function (visible) {
			if (visible==="toggle") {
				this.set("display",!this.get("display"));
				return;
			}
			if (visible) this.removeClass("display-none").setStyle("display","");
			else this.addClass("display-none").setStyle("display","none");
		},
		get:function () {
			return this.get("visibility");
		}
	}
});

Element.fromMarkup=function (markup,multipleElements) {
	var div=new Element("div").setHTML((markup || "").trim());
	if (multipleElements) return div.getChildren();
	else {
		if (div.childNodes.length>1) return div;
		else return div.getFirst();
	}
};

String.implement({
	escapeHtml:function (isHtml) { 
		var str=this;
		if (!isHtml) str=str.replace(/>/g,"&gt;").replace(/</g,"&lt;");
		else str=str.replace(/\r?\n/g,"<br/>");
		str=str.replace(/"/g,"&quot;").replace(/'/g,"&#39;");
		return str;
	}
});

Events.makeObjectEventable=function (obj) {
	$extend(obj,Events.prototype);
};
Options.makeObjectOptionable=function (obj) {
	$extend(obj,Options.prototype);
};
Options.makeClassOptionable=function (cls) {
	cls.setOptions=function () {
		Options.prototype.setOptions.apply(cls.prototype,arguments);
	};
};

$(document.body);