﻿// 针对$写的扩展方法
function $(a,op){
	if(window==this)
		return new $(a,op);
	this.get(this.search(a,op?(op.constructor==Array?op:[op]):null));
	if($.browser.msie&&parseFloat($.appStr.split("msie")[1].trim())<7){
		for(var i=0;i<this.length;i++){
			if(this[i].isElement)
				continue;
			$.extend(this[i],Object.prototype);
		}
	}
	return this;
}
$.prototype={
	get:function(n){
		if(n&&n.constructor==Array){
			this.length=0;
			[].push.apply(this,n);
			return this;
		}
		return this[n];
	},
	search:function(a,op){
		if(typeof a=="object")return [a];
		op=op||[document];
		a=a.trim();
		if(a.charAt(0)=="#"){
			var o=document.getElementById(a.slice(1));
			return o?[o]:[];
		}
		var m=a.replace(/\[[^\]]+\]/g,function($1){return $1.replace("/","&&")}).split("/");
		for(var i=0;i<m.length;i++){
			var s=m[i].trim().replace("&&","/"),p1=s.indexOf("["),tag=p1<0?s:s.slice(0,p1),attr=tag==s?"":s.slice(p1+1,-1),p2=tag.indexOf("="),tAttr=p2<0?tag:tag.slice(0,p2),tVal=tAttr==tag?"":tag.slice(p2+1).replace(/^(\'|\")|(\'|\")$/g,""),oa=[],tp=arguments.length==3?[]:null;
			if(i==0&&s.charAt(0)=="@")
				op=$.checkAttr(op,tAttr.slice(1),tVal==""?null:tVal);
			else{
				for(var j=0;j<op.length;j++){
					oa=$.merge(oa,s=="*"?$.children(op[j]):op[j].getElementsByTagName(tAttr));
					if(tVal!="")
						oa=$.checkAttr(oa,"nodeValue",tVal);
					if(attr!="")
						oa=arguments.callee(attr,oa,1);
					if(tp&&oa.length>0){
						tp.push(op[j]);
						oa=[];
					}
				}
				op=tp||oa;
			}
		}
		return op;
	},
	each:function(fn,args){return $.each(this,fn,args)}
}
$.extend = function(obj,op) {
	if (op==null) {
		op=obj;
		obj=this;
	}
	for (var i in op) {
		obj[i]=op[i];
	}
	return obj;
}
$.appStr=navigator.userAgent.toLowerCase();
$.emptyFunc=function(){};
$.readyFn=[];
$.isReady = false;
$.extend({
	$:function(obj){
		if (arguments.length > 1) {
			for (var i = 0, objs = [], length = arguments.length; i < length; i++)
				objs.push($(arguments[i]));
			return objs;
		}
		return typeof obj=="string"?document.getElementById(obj):obj
	},
	appfn:function(obj){
		obj=this.$(obj);
		if(obj&&!obj.isElement)
			$.extend(obj,Object.prototype);
		return obj;
	}
})
$.extend({
	browser:{
		msie:/msie/.test($.appStr)&&!/opera/.test($.appStr),
		mozilla:/mozilla/.test($.appStr)&&!/(compatible|webkit)/.test($.appStr),
		safari:/webkit/.test($.appStr),
		opera:/opera/.test($.appStr),
		firefox:/firefox/.test($.appStr)
	},
	children:function(o,oa){
		oa=oa||[];
		var a=o.childNodes;
		for(var i=0;i<a.length;i++)
			if(a[i].nodeType==1){
				oa.push(a[i]);
				$.children(a[i],oa);
			}
		return oa;
	},
	merge:function(a1,a2){
		var a=[],flag;
		for(var i=0;i<a1.length;i++)
			a[i]=a1[i];
		i=0;
		while(i<a2.length){
			flag=true;
			for(var j=0;j<a1.length;j++)
				if(a1[j]==a2[i])
					flag=false;
			if(flag)a.push(a2[i]);
			i++;
		}
		return a;
	},
	checkAttr:function(a,type,val){
		var oa=[];
		for(var i=0;i<a.length;i++){
			if(type=="class"||type=="className") {
				attr=a[i].className;
			} else {
				attr=a[i].getAttribute(type);
			}
			if(attr){
				if(val==null)
					oa.push(a[i]);
				else if((new RegExp("\\b("+(val)+")\\b")).test(attr))
					oa.push(a[i]);
			}
		}
		return oa;
	},
	each:function(obj,fn,args){
		if (obj.length==null) {
			for(var i in obj) {
				fn.apply(obj[i],args||[i,obj[i]]);
			}
		} else {
			for(var i=0;i<obj.length;i++) {
				if(fn.apply(obj[i],args||[i,obj[i]])===false) {
					break;
				}
			}
		}
		return obj;
	},
	ready:function(fn){
		// Attach the listeners
		bindReady();
		fn=fn&&fn.constructor==Function?fn:function(){if(typeof fn=="string")eval(fn)};
		// If the DOM is already ready
		if ( $.isReady )
			// Execute the function immediately
			fn.apply( document );

		// Otherwise, remember the function for later
		else
			// Add the function to the wait list
			$.readyFn.push( fn );
	},
	_ready:function(){
		// Make sure that the DOM is not already loaded
		if ( !$.isReady ) {
			// Remember that the DOM is ready
			$.isReady = true;

			// If there are functions bound, to execute
			if ( $.readyFn ) {
				// Execute all of them
				$.each( $.readyFn, function(){
					this.apply( document );
				});

				// Reset the list of functions
				$.readyFn = null;
			}
			// Remove event listener to avoid memory leak
			if ( $.browser.mozilla || $.browser.opera )
				document.removeEventListener( "DOMContentLoaded", $._ready, false );
		}
	}
})
$.extend({
	toXml:function(str){
		if($.browser.msie){
			var xml=new ActiveXObject("Microsoft.XMLDOM");
			xml.loadXML(str);
			xml.setProperty("SelectionLanguage","XPath");
		}
		else
			var xml=new DOMParser().parseFromString(str,"text/xml");
		return xml.documentElement;
	},
	text:function(node,expr){
		var ol=this.nodes(node,expr);
		return ol.length>0?ol[0].text:null;
	},
	nodes:function(node,expr){
		try{
			if($.browser.msie)
				return node.selectNodes(expr);
			else{
				var xpe=new XPathEvaluator(),nsr,res,r,ol=[];
				nsr=xpe.createNSResolver(node.ownerDocument==null?node.documentElement:node.ownerDocument.documentElement);
				res=xpe.evaluate(expr,node,nsr,0,null);
				while(r=res.iterateNext()){
					r.text=r.textContent;
					ol.push(r);
				}
				return ol;
			}
		}catch(e){return []}
	}
})
if(!$.browser.msie) {
	HTMLElement.prototype.click = function() {
		var evt = this.ownerDocument.createEvent('MouseEvents');
		evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
		this.dispatchEvent(evt);
	};
}
if($.browser.firefox){
	window.constructor.prototype.__defineGetter__("event",function(){var o=arguments.callee.caller;var e;while(o!=null){e=o.arguments[0];if(e&&(e.constructor==Event||e.constructor==MouseEvent))return e;o=o.caller;}return null;});
	Element.prototype.__defineGetter__("xml",function(){return new XMLSerializer().serializeToString(this)});
	HTMLElement.prototype.__defineGetter__("xml",function(){return this.getAttribute("xml")});
	HTMLElement.prototype.__defineSetter__("xml",function(o){this.setAttribute("xml",o)});
}
$.extend(String.prototype,{
	trim:function(){return this.replace(/^\s*|\s*$/g,"")},
	ltrim:function(char) {
		if (!char) {
			char = " \t\n\r";
		}
		var space = new String(char);
		var str = new String(this);
		if (space.indexOf(str.charAt(0)) != -1) {
			var j = 0,i = str.length;
			while (j < i && space.indexOf(str.charAt(j)) != -1) {
				j++;
			}
			str = str.substring(j,i);
		}
		return str;
	},
	rtrim:function(char) {
		if (!char) {
			char = " \t\n\r";
		}
		var space = new String(char);
		var str = new String(this);
		if (space.indexOf(str.charAt(str.length - 1)) != -1) {
			var i = str.length - 1;
			while (i >= 0 && space.indexOf(str.charAt(i)) != -1) {
				i--;
			}
			str = str.substring(0,i + 1);
		}
		return str;
	},
	inStr:function(s1,s2){s2=s2||",";return (s2+this+s2).indexOf(s2+s1+s2)!=-1?true:false},
	len:function(){return this.replace(/[^\x00-\xFF]/g,"**").length},
	skipHtml:function(){return this.replace(/\<|\>|\"|\'|\&/g,function(s){return s=="<"?"& lt;":(s==">"?"& gt;":(s=="\""?"& quot;":(s=="'"?"& #39;":(s=="&"?"& amp;":""))))})},
	toArray:function(s1){return this.split(s1==null?"":s1)},
	toNum:function(){return /^\d+$/g.test(this)?this*1:this;}
})
$.extend(Array.prototype,{
	aSort:function(){return this.sort(function(){return Math.random()>0.5?-1:1})}
})
$.extend(Math,{
	max2:function(){return arguments.length>1?Math.max.apply(null,arguments):Math.max.apply(null,arguments[0])}
})
$.extend(Number.prototype,{
	toMoney:function(){
		var n=this+"",idx=n.indexOf("."),n1=idx<0?n:n.slice(0,idx),n2=idx<0?".00":n.slice(idx),i=n1.length%3;
		n1=(i==1?"00":(i==2?"0":""))+n1;
		i=n2.slice(1).length;
		n2+=(i==0?"00":(i==1?"0":""));
		n2=i>2?n2.slice(0,3):n2;
		return n1.replace(/(\d{3})/g,",$1").replace(/^,0*/g,"")+n2;
	}
})
$.extend(Object.prototype,{
	isElement:function(){return this.nodeType&&this.nodeName?true:false},
	superClass:function(){return this.isElement!=null&&this.isElement()?null:this.constructor.toString().match(/function (\w+)\(.+/)[1]},
	show:function(type){
		if(this.each)this.each(function(){this.show(type)});
		if(this.isElement==null||!this.isElement()||(type&&!"visibility,display".inStr(type)))return;
		type=type||"display";
		this.style[type]=type=="display"?"block":"visible";
	},
	hide:function(type){
		if(this.each)this.each(function(){this.hide(type)});
		if(this.isElement==null||!this.isElement()||(type&&!"visibility,display".inStr(type)))return;
		type=type||"display";
		this.style[type]=type=="display"?"none":"hidden";
	},
	remove:function(){
		var obj=this;
		obj.isElement!=null&&obj.isElement()?obj.parentNode.removeChild(obj):(obj.each?obj.each(function(){obj.remove()}):delete obj);
		obj=null;
		try{
			CollectGarbage();
		}catch(e){}
	},
	leave:function(){
		if(this.each)this.each(function(){this.leave()});
		if(this.isElement!=null&&this.isElement())this.style.left="-9000px";
	},
	getWidth:function(){if(this.isElement!=null&&this.isElement())return this==document?Math.max(this.body.clientWidth,this.documentElement.clientWidth):this.offsetWidth},
	getHeight:function(){if(this.isElement!=null&&this.isElement())return this==document?Math.max(this.body.clientHeight,this.documentElement.clientHeight):this.offsetHeight},
	getAttr:function(type){if(this.isElement==null||!this.isElement()||type==null)return;type=type.trim();return type=="class"?this.className:this.getAttribute(type)},
	setAttr:function(attr){
		if(this.each)this.each(function(){this.setAttr(attr)});
		if(this.isElement==null||!this.isElement())return;
		attr=attr.split(";");
		for(var i=0;i<attr.length;i++){
			var a=attr[i].split(":");
			this.setAttribute(a[0].trim(),a[1].trim());
		}
	},
	getFilter:function(type){
		var o=this.each&&this[0]?this[0]:this;
		if(o.isElement==null||!o.isElement()||type==null)return;
		var filter={alpha:"-moz-opacity"};
		if($.browser.msie){
			val=this.getStyle("filter");
			if(type=="alpha"){
				val=val.slice(val.indexOf("opacity=")+8,-1)
				val=isNaN(parseInt(val))?1:parseInt(val)/100;
			}
		}
		else
			val=this.getStyle(filter[type]);
		return val;
	},
	setFilter:function(type,val){
		if(this.each)this.each(function(){this.setFilter(type,val)});
		if(this.isElement==null||!this.isElement())return;
		var filter={alpha:"-moz-opacity"};
		if($.browser.msie){
			if(type=="alpha")
				this.setStyle("filter:alpha(opacity="+(val*1)+")");
		}
		else
			this.setStyle(filter[type]+":"+(val*1/100));
	},
	getStyle:function(type){
		var o=this.each&&this[0]?this[0]:this;
		if(o.isElement==null||!o.isElement()||type==null)return;
		type=type.trim();
		if(type=="float")type=o.style.styleFloat!=undefined?"styleFloat":"cssFloat";
		if(o.currentStyle)
			return o.currentStyle[type.replace(/-[a-z]/g,function($1){return $1.slice(1).toUpperCase()})];
		else if(document.defaultView&&document.defaultView.getComputedStyle){
			if(type=="styleFloat"||type=="cssFloat")type="float";
			var css=document.defaultView.getComputedStyle(o,null);
			return css?css.getPropertyValue(type):null;
		}
		return null;
	},
	setStyle:function(css){
		this.each?this.each(function(){this.setStyle(css)}):null;
		if(this.isElement==null||!this.isElement())return;
		css=css.split(";");
		for(var i=0;i<css.length;i++){
			var a=css[i].split(":");
			if(!a[1]||a[1]=="null"||a[1]=="undefined")continue;
			this.style[a[0].trim().replace(/-[a-z]/g,function($1){return $1.slice(1).toUpperCase()})]=a[1].trim();
		}
	},
	addClass:function(name){
		if(this.each)this.each(function(){this.addClass(name)});
		if(this.isElement==null||!this.isElement())return;
		var s=this.className;
		this.className=s==null?name:s.trim()+" "+name;
	},
	removeClass:function(name){
		if(this.each)this.each(function(){this.removeClass(name)});
		if(this.isElement==null||!this.isElement())return;
		var s=this.className||"",name=name.split(" ");
		for(var i=0;i<name.length;i++)
			s=s.replace(new RegExp("\\s*"+name[i]),"");
		this.className=s;
	},
	removeAttr:function(name){
		if(this.each)this.each(function(){this.removeClass(name)});
		if(this.isElement!=null&&this.isElement()){
			var a=name.trim().split(",");
			for(var i=0;i<a.length;i++)
				this.removeAttribute(a[i].trim());
		}
	},
	removeStyle:function(name){
		if(this.each)this.each(function(){this.removeStyle(name)});
		if(this.isElement!=null&&this.isElement()){
			var a=name.trim().split(",");
			for(var i=0;i<a.length;i++)
				this.style[a[i]]="none";
		}
	},
	listen:function(type,fn){
		if(type==null||fn==null)return;
		if(this.each)this.each(function(){this.listen(type,fn)});
		if(this.isElement())
			$.browser.msie?this.attachEvent(type,fn):this.addEventListener(type.slice(2),fn,false);
	},
	removeListen:function(type,fn){
		if(type==null||fn==null)return;
		if(this.each)this.each(function(){this.removeListen(type,fn)});
		if(this.isElement())
			$.browser.msie?this.detachEvent(type,fn):this.removeEventListener(type.slice(2),fn,false);
	},
	empty:function(){
		if(this.each)this.each(function(){this.empty()});
		if(this.isElement==null||!this.isElement())return;
		while(this.firstChild)
			this.removeChild(this.firstChild);
	},
	append:function(str,oRefer){
		if(this.each)this.each(function(){this.append(str,oRefer)});
		if(this.isElement==null||!this.isElement())return;
		var oDiv=document.createElement("div"),tBx=this,oRefer=oRefer||null,oName=this.tagName.toLowerCase(),ol=[];
		var selIndex=0;
		if("table,tbody".inStr(oName)){
			oDiv.innerHTML="<table>"+str+"</table>";
			ol=oDiv.childNodes[0].tBodies[0].rows;
			if(oName=="table"){
				if(!this.tBodies[0])
					this.appendChild(document.createElement("tbody"));
				tBx=this.tBodies[0];
			}
		}else if(oName=="select"){
			oDiv.innerHTML="<select>"+str+"</select>";
			ol=oDiv.childNodes[0].options;
			for(var i=0;i<ol.length;i++){
				if(typeof ol[i].getAttribute("selected")=="string"||ol[i].getAttribute("selected")){
					selIndex=i;
					break;
				}
			}
		}
		else if("div,span,body,label,ul,li,p,em,ul".inStr(oName)){
			oDiv.innerHTML=str;
			ol=oDiv.childNodes;
		}
		while(ol.length>0)
			tBx.insertBefore(ol[0],oRefer);
		if(oName=="select")
			window.setTimeout(function(){tBx.selectedIndex=selIndex},10);
	},
	fill:function(str){if(this.empty==null)return;this.empty();this.append(str)},
	getOffsetPos:function(){
		if(this.isElement==null||!this.isElement())return;
		var x=this.offsetLeft,y=this.offsetTop,obj=this,w=this.getStyle("width"),h=this.getStyle("height");
		while(obj=$.appfn(obj.offsetParent)){
			if(w=="auto"||w=="100%"){
				w=obj.getStyle("width");
			}
			if(h=="auto"||w=="100%"){
				h=obj.getStyle("height");
			}
			x+=obj.offsetLeft;
			y+=obj.offsetTop;
		}
		return {x:x-(this.parentNode?this.parentNode.scrollLeft:0),y:y-(this.parentNode?this.parentNode.scrollTop:0),w:parseInt(w),h:parseInt(h)}
	},
	sendAjax:function(url,options){if(typeof url!='string')return;
		var obj=this,idx=url.indexOf("?"),uri=idx==-1?url:url.slice(0,idx),mode=options.method?options.method.toUpperCase():("xml,htm,html,tml,.js,css,txt,.as,xsl".inStr(uri.slice(-3))?"GET":"POST");
		var ajaxEvents=['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
		var isSuccess=function(){
			return obj.ajax.status=="undefined"||obj.ajax.status==0||(obj.ajax.status>=200&&obj.ajax.status<300);
		}
		var setHeader=function(){
			var headers=["X-Requested-With","XMLHttpRequest","If-Modified-Since","Sun,3 Jun 1973 00:00:00 GMT"];
//			if(mode=="POST"){
				headers.push("Content-type","application/x-www-form-urlencoded;charset=utf-8");
				if(this.overrideMimeType)
					headers.push("Connection","close");
//			}
			if(options.requestHeaders)
				headers.push.apply(headers,options.requestHeaders);
			for(var i=0;i<headers.length;i+=2)
				this.setRequestHeader(headers[i],headers[i+1]);
		}
		var ready=function(status){
			var event=ajaxEvents[status];
			if(status==4){
				try{
					(options["on"+this.status]||options["on"+(isSuccess()?"Success":"Failure")]||$.emptyFunc).apply(this,[]);
				}catch(e){}
			}
			try{
				(options["on"+event]||$.emptyFunc).apply(this,[]);
			}catch(e){}
			if(event=="Complete")
				this.onreadystatechange=$.emptyFunc;
		}
		if(!options["onSuccess"])options.onSuccess=function(){obj.fill(this.responseText);}
		obj.ajax=$.browser.msie?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
		try{
			obj.ajax.open(mode,mode=="GET"?url:(idx==-1?url:uri),true);
			setHeader.apply(obj.ajax,[]);
			obj.ajax.send(mode=="GET"?null:(idx==-1?"":url.slice(idx+1)));
		}catch(e){alert("ajax:"+e)}
		$.ajaxs=$.ajaxs||[];//save ajax object
		$.ajaxs.push(obj.ajax);
		if(options.onLoadInit)options.onLoadInit.apply(obj.ajax,[]);
		obj.ajax.onreadystatechange=function(){
			if(obj.ajax.responseXML!=null&&typeof obj.ajax.responseXML.setProperty!="undefined"){
				obj.ajax.responseXML.setProperty("SelectionLanguage","XPath");
			}
			ready.apply(obj.ajax,[obj.ajax.readyState]);
		}
	}
})

var readyBound = false;

function bindReady(){
	if ( readyBound ) return;
	readyBound = true;

	// If Mozilla is used
	if ( $.browser.mozilla || $.browser.opera )
		// Use the handy event callback
		document.addEventListener( "DOMContentLoaded", $._ready, false );

	// If Safari or IE is used
	// Continually check to see if the document is ready
	else {
		(function(){
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				if ( $.browser.msie || document.readyState != "loaded" && document.readyState != "complete" )
					document.documentElement.doScroll("left");
			} catch( error ) {
				return setTimeout( arguments.callee, 0 );
			}

			// and execute any waiting functions
			$._ready();
		})();

		// trying to always fire before onload
		document.onreadystatechange = function() {
			if (document.readyState == 'complete') {
				document.onreadystatechange = null;
				$._ready();
			}
		};

	}

	// A fallback to window.onload, that will always work
	$.browser.msie?document.attachEvent("onload",$._ready):document.addEventListener("load",$._ready,false);
}