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 (fn,args) {
		var result=[];
		for (var i=0,l=this.length;i<l;i++) {
			if (this[i] && this[i][fn]) result.push(args ? this[i][fn].pass(args, this[i])() : this[i][fn]());
		}
		return result;
	}
});

Window.implement({
	$E:function(selector) {
		return this.document.getElement(selector);
	},
	$ES:function(selector) {
		return this.document.getElements(selector);
	}
});
Element.implement({
	setHTML:function() {
		var html=Array.join(arguments,"");
		this.set("html",Element.execHTML(html));
		return this;
	},
	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); },

	setSelection:function (b) {
		if (Browser.engine.trident || Browser.engine.presto) this[(b?"remove":"add")+"Event"]("selectstart",$returnFalse);
		if (Browser.engine.gecko) this.style.MozUserSelect=b?"":"none";
		if (Browser.engine.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;
	},

	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); },
	show:function () { return this.set("display",true); },
	hide:function () { return this.set("display",false); },
	// overrides toQueryString 
	toQueryString: function(){
		var queryString=[];
		this.getElements('input, select, textarea',false).each(function(el){
			if (!el.name || el.disabled) return;
			
			var value;
			if (el.tagName.toLowerCase() == 'select') value=Element.getSelected(el).map(function(opt){
				return opt.value;
			});
			else if (el.type == 'radio' || el.type == 'checkbox') {
				if (!el.checked) value=el.type == 'radio' ? null : "";
				else value=el.value;
			}
			else value=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 (html,options) {
	if (options===true) {
		options={ multipleElements:true };
	}
	options=$extend({
		js:true,
		css:true,
		callback:$empty
	},options);

	html=html || "";
	
	html=Element.execHTML(html,options.callback);

	var div=new Element("div").set("html",html);
	if (options.multipleElements) return div.getChildren();
	else {
		if (div.childNodes.length>1) return div;
		else return div.getFirst();
	}
};

// executes all external resources and returns the rest of the html
// supports callback when all external resources are loaded
Element.execHTML=function (html,callback) {
	var srcRx=/\ssrc=('|"|)(.*?)\1/gi,
		hrefRx=/\shref=('|"|)(.*?)\1/gi;
	var src;
	var inlineScripts=[],
		externalScripts=[],externalCss=[];

	html=html.replace(/\s*<script([^>]*?)>([\s\S]*?)<\/script>\s*/gi,function(all,attrs,content) {
		if (src=srcRx.exec(attrs)) externalScripts.push(src[2]);
		else inlineScripts.push(content);
		return '';
	})
	.replace(/\s*<link([^>]*?)\srel=('|"|)stylesheet\1([^>]*?)>\s*/gi,function(all,attrs1,attrs2) {
		if (relStylesheetRx.test(all)) 
		if (src=hrefRx.exec(attrs+" "+attrs2)) externalCss.push(src[2]);
		return '';
	}).trim();

	inlineScripts=inlineScripts.join("\n");

	var externalFilesCount=externalScripts.length+externalCss.length;
	
	var onLoad=function () {
		if (callback) callback();
		if (inlineScripts.length) $exec(inlineScripts);
	}.create({delay:10});

	var checkIfDone=function checkIfDone() {
		externalFilesCount--;
		if (externalFilesCount<=0) onLoad();
	};

	var javascriptLoader=Element.execHTML.javascript || Asset.javascript,
		cssLoader=Element.execHTML.css || Asset.css;
	
	if (externalFilesCount>0) {
		var opts=callback ? { onload:checkIfDone } : null;
		externalScripts.each(function (item) { javascriptLoader(item,opts); });
		externalCss.each(function (item) { cssLoader(item,opts); });
	}
	else onLoad();
	
	return html;
};

// patch
Asset._oldCss=Asset.css;
$extend(Asset,{
	css: function(source, properties){
		properties = $extend({
			onload: $empty
		}, properties);

		// Create a style element instead of a link element
		var style_node = new Element('style', $merge({
			'media': 'screen', 'type': 'text/css'
		}, properties)).inject(document.head);
		// Not sure why this is needed, but it is
		style_node.onload = properties.onload;
		delete properties.onload;
		
		if (source.indexOf("data:")==0) return Asset._oldCss(source);

		// Fetch CSS using XHR
		var request = new Request({
				method: 'get',
				url: source,
				style_node:style_node,
				onSuccess:function( css_text ){
					// Set the CSS
					// From http://yuiblog.com/blog/2007/06/...
					if (this.styleSheet) {
						this.styleSheet.cssText = css_text;
					} else {
						this.appendChild(document.createTextNode(css_text));
					}
					this.onload();
				}.bind( style_node )
			}
		);
		request.send();

		return style_node;
	}
});

$extend(Element.prototype,{
	clone: function(contents, keepid){
		switch ($type(this)){
			case 'element':
				var attributes={};
				for (var j=0, l=this.attributes.length; j < l; j++){
					var attribute=this.attributes[j], key=attribute.nodeName.toLowerCase();
					if (Browser.Engine.trident && (/input/i).test(this.tagName) && (/width|height/).test(key)) continue;
					var value=(key == 'style' && this.style) ? this.style.cssText : attribute.nodeValue;
					if (!$chk(value) || key == 'uid' || (key == 'id' && !keepid)) continue;
					if (value != 'inherit' && ['string', 'number'].contains($type(value))) attributes[key]=value;
				}
				var element=new Element(this.nodeName.toLowerCase(), attributes);
				if (contents !== false){
					for (var i=0, k=this.childNodes.length; i < k; i++){
						if (/script/i.test(this.childNodes[i].tagName)) continue; // this is the change

						var child=Element.clone(this.childNodes[i], true, keepid);
						if (child) element.grab(child);
					}
				}
				return element;
			case 'textnode': return document.newTextNode(this.nodeValue);
		}
		return null;
	}
});
function $clone(o) {
	if(typeof(o)!="object") return o;
	if(o==null) return o;
	var newO={};
	for (var i in o) newO[i]=$clone(o[i]);
	return newO;
}

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;
	}
});

// make static object to have events
Events.makeObjectEventable=function (obj) { $extend(obj,Events.prototype); };

// make static object to have options get/set
Options.makeObjectOptionable=function (obj) { $extend(obj,Options.prototype); };

// make any class to have options get/set as a static member
Options.makeClassOptionable=function (cls) {
	cls.setOptions=function () {
		Options.prototype.setOptions.apply(cls.prototype,arguments);
	};
};

$(document.body);
