/*!
 * jBr JavaScript Framework v1.0.0
 *
 * Copyright 2010, Filipe Alves Santana
 *
 * Baseado em jProton e jQuery
 *
 * Date: Mon Set 20 14:31:43 2010 -0300
 */

/*
classe = function(){
	this.f = 22;
	
	this.ap = function(){
		return this;
	}
	
	this.low = function(){
		return this;
	}
}

var t = new classe();


t.ap();
t.low();
t.ap().low().low().ap().......ap().f = 50;
*/

(function(){
window.jBr = function(s,c){
	return new $.set().select(s,c);
}
var $ = jBr,
set,
el,
ajax,
$r,
readyBound=false,
readyList = [],
DOMContentLoaded;

$.set = function(){};
set = $.set.prototype = [];
el = $.el = {};
ajax = $.ajax = function(o){
	return this.ajax.request(o);
};


$.extend = set.extend = el.extend = function(){
	var alvo=this,t=alvo,fonte,p,i=0;
	if(arguments.length>1){
		i++;
		alvo = t = arguments[0];
	}
	for(;fonte=arguments[i++];){
		for(var pp in fonte){
			p = fonte[pp];
			if(pp.charAt(0)!='@'){
				if(p&&p.splice){
					var tp = t[pp];
					t[pp] = tp&&tp.splice?tp.concat(p):[].concat(p);
				}else if(p&&(typeof p=='object')){
					t[pp] = $.extend(t[pp]||{},p);
				}else t[pp] = p;
				continue;
			}
			if(pp=='@init')p.call(t);
		}
	}
	return alvo;
}
// *********************** //
//Number
$.extend(Number.prototype,{
isNaN:function(){return isNaN(this);},
abs:function(){return Math.abs(this);},
round:function(){return Math.round(this);},
floor:function(){return Math.floor(this);},
ceil:function(){return Math.ceil(this);},
pow:function(ex){return Math.pow(this,ex);},
sqrt:function(){return Math.sqrt(this);},
max:function(a){return Math.max(this,a);},
min:function(a){return Math.min(this,a);},
fmt:function(d,sm,sd){
	d = d||0;
	if(typeof sm!='string')sm = '.';
	if(typeof sd!='string')sd = ',';
	var num,dec,ns,ds;
	num = ('0'+this+'.0').match(/(\d+).(\d+)/);
	dec = num[2];
	num = num[1].Int(10)+'';
	neg = this<0;
	ns = num.reverse().explode(3).join(sm).reverse();
	ds = dec.rpad('0',d).subs(0,d);
	return (neg?'-':'')+ns+sd+ds;
}
});
//String
$.extend(String.prototype,{
trim:function(s,n){
	var r = this.replace(/^\s*|\s*$/g,'');
	if(s)r = r.replace(/[ \t]{2,}/g,' ');
	if(n){
		r = r.replace(/\r?\n/g,'\n').split('\n');
		$.each(r,function(i){r[i] = this.trim();});
		r = r.join('\n');
	}
	return r;
},
ltrim:function(){return this.replace(/^\s+\s/g,'');},
rtrim:function(){return this.replace(/\s+\s$/g,'');},
explode:function(l){
	if(typeof l=='number'){
		var r = [],i=0,p=0;
		while(p<this.length)r[i++] = this.subs(p,p+=l);
		return r;
	}
	return this.split(' ');
},
reverse:function(){return this.split('').reverse().join('');},
sort:function(fn){return this.split('').sort(fn).join('');},
low:function(){return this.toLowerCase();},
upp:function(){return this.toUpperCase();},
tag:function(c){
	var a = ['À|Á|Â|Ã|Ä|Å','à|á|â|ã|ä|å|ª|@','ß','Ç|¢','ç','È|É|Ê|Ë|€','è|é|ê|ë|\\&','Ì|Í|Î|Ï','ì|í|î|ï','£','Ñ','ñ','Ò|Ó|Ô|Õ|Ö','ò|ó|ô|õ|ö|º','§|\\$','†','Ù|Ú|Û|Ü','ù|ú|û|ü','\\*','Ý','ý|ÿ','¹','²','³','"|\'|\\?|!|\\.|:|,|;|´|`|~|\\^','-|\\||\\|/|\\(|\\)|\\[|\\]|\\{|\\}','\\s+','[^\\w-]'],
	b = ['A','a','B','C','c','E','e','I','i','L','N','n','O','o','S','t','U','u','x','Y','y','1','2','3','',' ','-','_'],
	r = this;
	$.each(a,function(i){r = r.replace(new RegExp(a[i],'g'),b[i]);});
	if(c===1)return r.low();
	if(c===2)return r.upp();
	return r;
},
ucf:function(r){
	r = !r?this.low():this;
	var c = r.ltrim().charAt(0);
	return r.replace(c,c.upp());
},
ucw:function(s,n,l,r){
	if(!l)l = 3;
	var w = this.trim(!s,!n).explode();
	$.each(w,function(i,v){if(v.length>=l)w[i] = v.ucf(r);});
	return w.join(' ');
},
lpad:function(c,q){
	var v = this;
	for(var i=v.length; i<q; i++)v = c+v;
	return v;
},
rpad:function(c,q){
	var v = this;
	for(var i=v.length; i<q; i++)v += c;
	return v;
},
subs:function(i,f){
	if(i<0)i += this.length;
	if(f<0)f += this.length;
	if(!f&&f!==0)return this.substring(i);
	return this.substring(i,f);
},
Int:function(b){
	var n = parseInt(this,b);
	return n?n:0;

},
Float:function(){
	var n = parseFloat(this);
	return n?n:0;
}
});
//Date
$.extend(Date,{
bi:function(a){
	return a%400==0||(a%4==0&&a%100!=0)?1:0;
},
dm:function(a){
	return [31,28+this.bi(a),31,30,31,30,31,31,30,31,30,31];
}
});
$.extend(Date.prototype,{
sem:['Domingo','Segunda-feira','Terça-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sábado'],
mes:['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
bi:function(){
	return Date.bi(this.getFullYear());
},
dm:function(){
	return Date.dm(this.getFullYear())[this.getMonth()];
},
mk:function(mk,mk2,dt){
	if(this.getTime().isNaN()&&typeof mk2=='string')mk = mk2;
	if(dt!=null)this.setTime(new Date(dt).getTime());

	var a,_m,m,d,h,y,s,sm,r=mk;
	a = this.getFullYear();
	_m = m = this.getMonth();
	m += 1;
	d = this.getDate();
	h = this.getHours();
	y = this.getMinutes();
	s = this.getSeconds();
	sm = this.getDay();

	if(m<10)m = '0'+m;
	if(d<10)d = '0'+d;
	if(h<10)h = '0'+h;
	if(y<10)y = '0'+y;
	if(s<10)s = '0'+s;

	if(mk==1)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a;
	if(mk==2)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' '+h+':'+y+':'+s;
	if(mk==3)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' '+h+':'+y;
	if(mk==4)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' '+h+'h'+y;
	if(mk==5)r = h+':'+y+':'+s;
	if(mk==6)r = h+':'+y;
	if(mk==7)r = h+'h'+y;
	if(mk==8)r = d+'/'+m+'/'+a;
	if(mk==9)r = d+'/'+m+'/'+a+' '+h+':'+y+':'+s;
	if(mk==10)r = d+'/'+m+'/'+a+' '+h+':'+y;
	if(mk==11)r = d+'/'+m+'/'+a+' '+h+'h'+y;
	if(mk==12)r = a+'-'+m+'-'+d;
	if(mk==13)r = a+'-'+m+'-'+d+' '+h+':'+y+':'+s;
	if(mk==14)r = a+'-'+m+'-'+d+' '+h+':'+y;
	if(mk==15)r = a+'-'+m+'-'+d+' '+h+'h'+y;
	if(mk==16)r = d+'/'+m+'/'+a+' às '+h+':'+y+':'+s;
	if(mk==17)r = d+'/'+m+'/'+a+' às '+h+':'+y;
	if(mk==18)r = d+'/'+m+'/'+a+' às '+h+'h'+y;
	if(mk==19)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' às '+h+':'+y+':'+s;
	if(mk==20)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' às '+h+':'+y;
	if(mk==21)r = this.sem[sm]+', '+d+' de '+this.mes[_m]+' de '+a+' às '+h+'h'+y;
	if(mk==22)r = d+' de '+this.mes[_m]+' de '+a+' às '+h+':'+y+':'+s;
	if(mk==23)r = d+' de '+this.mes[_m]+' de '+a+' às '+h+':'+y;
	if(mk==24)r = d+' de '+this.mes[_m]+' de '+a+' às '+h+'h'+y;
	if(mk==25)r = d+' de '+this.mes[_m]+' de '+a;
	if(mk==26)r = d+' de '+this.mes[_m]+' de '+a+' '+h+':'+y+':'+s;
	if(mk==27)r = d+' de '+this.mes[_m]+' de '+a+' '+h+':'+y;
	if(mk==28)r = d+' de '+this.mes[_m]+' de '+a+' '+h+'h'+y;
	if(mk==30)r = ''+a+m+d+h+y+s;
	return r;
}
});
//Array
$.extend(Array.prototype,{
each:function(fn,r){
	$.each(this,fn,(r===1?this:r));
	return this;
}
});
// *********************** //
$.extend({
emptyFn:function(){},
agent:navigator.userAgent.low(),
platform:navigator.platform.low(),
XHTMLNS:'http://www.w3.org/1999/xhtml',
isOpera:function(){
	return(this.agent.indexOf('opera')!=-1);
},
isIE:function(b){
	var a='msie';
	if(this.isNum(b))var a=a+' '+b;
	return(this.agent.indexOf(a)!=-1&&!this.isOpera());
},
isNum:function(a){
	return(typeof a=='number');
},
id:function(){
	var c = [];
	$.each(arguments,function(i,v){
		if(typeof v=='string'){
			if(document.getElementById)v=document.getElementById(v);
			else if(document.all)v=document.all[v];
			else if(document.layers)v=document.layers[v];
			else if(document[v])v=document[v];
		}
		if(v.nodeType==1)c.push(v);
	});
	if(c.length==1)return c[0];
	return c;
},
on:function(e){
	if(!$.isFn(this.e[e]))return this;
	var ag=[];
	$.each(arguments,function(i,v){ag[i] = v;});
	this.e[e].apply(this,ag);
	return this;
},
isFn:function(o){
	return typeof o=='function'&&(!Function.prototype.call||typeof o.call=='function')?true:false;
},
encode:function(o,r){
	o = o||{};
	r = r||null;
	var x='';
	$.feach(o,function(k,v){
		if(!/string|number|boolean/.test(typeof v))return;
		x += escape(k)+'='+escape(v)+'&';
	});
	return x?x.replace(/&$/,''):r;
},
XMLHttpRequest:function(){
	if(typeof XMLHttpRequest!='undefined')return new XMLHttpRequest();
	var a = ['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];
	for(var i=0,v; v=a[i]; i++){
		try{
			return new ActiveXObject(v);
		}catch(e){}
	}
	return null;
},

before:function(el,ref){
	if(!el.splice)el = [el];
	for(var i=0,o;o=el[i++];)ref.parentNode.insertBefore(o,ref);
},
after:function(el,ref){
	if(!el.splice)el = [el];
	for(var i=el.length,o;o=el[--i];)ref.parentNode.insertBefore(o,ref.nextSibling);
},
append:function(pai,el){
	if(!el.splice)el = [el];
	for(var i=0,o;o=el[i++];)pai.appendChild(o);
},
prepend:function(pai,el){
	if(!pai.firstChild)$.append(pai,el);
	else $.before(el,pai.firstChild);
},
removeAll:function(el){
	if(!(el&&el.NodeType==1))return;
	while(el.hasChildNodes())el.removeChild(el.lastChild);
},
filho:function(o,el){
	if(!el)el = '';
	var r = [];
	if(!o)return r;
	if(o&&o.nodeType!==1)return r;
	for(var i=0,j=0,v; v=o.childNodes[i]; i++){
		if(v.nodeType!=1)continue;
		if(el&&(','+el+',').indexOf(','+v.nodeName.low()+',')<0)continue;
		r[j++] = v;
	}
	return r;
},
center:function(o,p,a){
	if(!p)p = document.documentElement;
	var t = ((p.clientHeight/2)+p.scrollTop)-(o.offsetHeight/2);
	var l = ((p.clientWidth/2)+p.scrollLeft)-(o.offsetWidth/2);
	if(!a){
		if(t<p.scrollTop+15)t = p.scrollTop+15;
		if(l<p.scrollLeft+15)l = p.scrollLeft+15;
	}
	el.css(o,{top:t+'px',left:l+'px'});
},
each:function(o,fn,r){
	if(!o)return;
	if(!fn)return;
	if(!o.slice&&!(typeof o=='object'&&'length' in o))o = [o];
	var i=0,v;
	for(;v=o[i];)if(fn.call(r||v,i++,v))break;
},
feach:function(o,fn,r){
	if(!o)return;
	if(!fn)return;
	var k,v,i=0;
	for(k in o)if(fn.call(r||[k],k,o[k],i++))break;
},
hash:function(){
	var h='',id,hs = function(){
		var _h = window.document.location.hash;
		_h = _h?_h.subs(1):'';
		if(_h!=h){
			h = _h;
			if(window.hashchange)window.hashchange();
		}
	};
	if('onhashchange' in window&&(!$.isIE()||$.isIE()>7)){
		window.onhashchange = function(){
			if(window.hashchange)window.hashchange();
		};
	}else id = setInterval(hs,500);
	hs();
},
addEvent:function(el,ev,fn){
	if(el.attachEvent){//IE
		el.attachEvent('on'+ev,fn);
	}else if(el.addEventListener){//Gecko/W3C
		el.addEventListener(ev,fn,true);
	}else{
		el['on'+ev] = fn;
	}
},
removeEvent:function(el,ev,fn){
	if(el.detachEvent){//IE
		el.detachEvent('on'+ev,fn);
	}else if(el.removeEventListener){//Gecko/W3C
		el.removeEventListener(ev,fn,true);
	}else{
		el['on'+ev] = null;
	}
},
stopEvent:function(e){
	e = e||window.event;
	if($.isIE()){
		e.cancelBubble = true;
		e.returnValue = false;
	}else{
		e.preventDefault();
		e.stopPropagation();
	}
	return false;
},
mouse:{x:0,y:0,fn:null,e:{},
	on:$.on,
	move:function(i){
		var _ = this;
		var fn = function(e){
			var e = e||window.event;
			if(e.pageX!=null||e.pageY!=null){
				_.x = e.pageX;
				_.y = e.pageY;
			}else if(e.clientX!=null||e.clientY!=null){
				_.x = e.clientX+document.body.scrollLeft-document.body.clientLeft;
				_.y = e.clientY+document.body.scrollTop-document.body.clientTop;
			}
			_.on('move');
		}
		if(i)$.addEvent(document,'mousemove',fn);
		else $.removeEvent(document,'mousemove',fn);
		return this;
	}
},
form:function(f,a,b){
	if(typeof f=='string')f = document.forms[f];
	if(!f||f.nodeType!=1||f.nodeName.low()!='form')return f;
	var t;
	if(a==null)a = 1;
	if(b==null)b = 1;
	$.each(f,function(i,v){
		if(!(t=v.nodeName)||!/textarea|input/.test(t=t.low())||(t=='input'&&v.type.low()!='text'))return;
		v.value = v.value.trim(a,b);
	});
	return f;
},
solic:function(s){
	if(s)alert('Uma solicitação está em andamento, aguarde.');
	return s;
},
xml:function(x,tipo,pai,rt){
	if(tipo===1){
		if(!x||!('getElementsByTagName' in x))return null;
		return $.xml(x.getElementsByTagName('*')[0],2);
	}
	if(!x||x.nodeType!=1)return null;
	var r = {},xn = x.nodeName.low(),xf = $.filho(x);
	if(tipo===2){
		r = function(a){
			if(a===1)return x;
			if(a===2)return xn;
			if(typeof a=='string')return x.getAttribute(a);
			return tp;
		};
		var tp = {num:{},dts:{},tms:{}};
		$.feach(tp,function(k,v){
			var _ = r('__'+k);
			if(_)$.each(_.split(';'),function(){
				var c = this.split(':');
				v[c[0]] = {};
				$.each(c[1].split(','),function(){
					v[c[0]][this] = 1;
				});
			});
		});

		rt = pai = r;
	}
	if(!xf.length){
		if(x.firstChild&&x.firstChild.nodeValue)return x.firstChild.nodeValue;
		return '';
	}
	$.each(xf,function(i,v){
		var n = v.nodeName.low();
		if(!r[n]){
			r[n] = [];
			r[n].pai = pai;
			r[n].paix = x;
			r[n].pain = xn;
			r[n].rt = rt;
			r[n].rtx = rt(1);
			r[n].rtn = rt(2);
		}
		var i2 = r[n].length;
		r[n][i2] = function(){
			return $.xml(v,0,this[i2],rt);
		};
		$.each(v.attributes,function(){
			var vl = this.value,an = this.name.low();
			if(rt().num[n]&&rt().num[n][an])vl = vl.Float();
			if(rt().dts[n]&&rt().dts[n][an])vl = new Date(vl.replace(/-/,'/'));
			if(rt().tms[n]&&rt().tms[n][an])vl = new Date(vl.Int()*1000);
			r[n][i2][an] = vl;
		});
	});
	return r;
},
isReady:false,
ready:function(){
	if(!$.isReady){
		if(!document.body)return setTimeout($.ready,13);
		$.isReady = true;
		if(readyList){
			var fn,i=0;
			while((fn=readyList[i++]))fn.call(document,$);
			readyList = null;
		}
	}
},
bindReady:function(){
	if(readyBound)return;
	readyBound = true;
	if(document.readyState==='complete')return $.ready();
	if(document.addEventListener){
		document.addEventListener('DOMContentLoaded',DOMContentLoaded,false);
		window.addEventListener('load',$.ready,false);
	}else if(document.attachEvent){
		document.attachEvent('onreadystatechange',DOMContentLoaded);
		window.attachEvent('onload',$.ready);
		var toplevel = false;
		try{
			toplevel = window.frameElement==null;
		}catch(e){}
		if(document.documentElement.doScroll&&toplevel)doScrollCheck();
	}
},
tmp:function(s,d){
	$.feach(d,function(k,v){
		s = s.replace(new RegExp('\\[!'+k+'!\\]','g'),v);
	});
	return s.replace(/\[!!/,'[!').replace(/!!\]/,'!]');
},
setCookie:function(n,v,e,p,d,s){
	var nome = n?n:'';
	var valor = v?v:'';
	var dt = new Date();
	dt.setTime(dt.getTime()+((60*60*1000)*e));
	var expira = e?'; expires='+dt.toGMTString():'';
	var local = p?'; path='+p:'';
	var dominio = d?'; domain='+d:'';
	var seguro = s?'; secure':'';
	document.cookie = nome+'='+escape(valor)+expira+local+dominio+seguro;
},
getCookie:function(n,v){
	var id,ca = {},r = v?'':null;
	$.each(document.cookie.split('; '),function(i,v){
		ca[v.subs(0,(id=v.indexOf('='))>-1?id:null)] = unescape(id==-1?'':v.subs(id+1));
	});
	if(n in ca)r = ca[n];
	return r;
}
});
// *********************** //



set.extend({
	_lastSet:null,
	_chain:function(e){
		var r = new $().copy(e);
		r._lastSet = this;
		return r;
	},
	s:'',
	select:function(s,c){
		var t = typeof s;
		if(!s)return this;
		if($.isFn(s))return $r.ready(s);
		if(s==='body'&&!c){
			this[0] = document.body;
			this.s = 'body';
			this.length = 1;
		}else if(t=='string'){
			return this.copy(query.select(s,c));
			this.s = s;
		}else if(t=='object'){
			if(s.nodeName)this.push(s);
			else if(s.length)return this.copy(s);
		}
		return this; 
	},
	ready:function(fn){
		$.bindReady();
		if($.isReady)fn.call(document,$);
		else if(readyList)readyList.push(fn);
		return this;
	},
	each:function(fn,r){
		$.each(this,fn,(r===1?this:r));
		return this;
	},
	copy:function(a){
		if(a){
			if(a.splice)this.push.apply(this,a);
			else for(var i=0,ai;ai=a[i++];)this.push(ai);
		}
		return this;
	},
	add:function(s,c){
		return this._chain(this).select(s,c);
	},
	find:function(s){
		return this._chain().select(s,this);
	},
	filter:function(s){
		return this._chain().copy(query.filter(this,s));
	},
	not:function(s){
		return this._chain().copy(query.filter(this,s,true));
	},
	len:function(){
		var l = 0;
		this.each(function(){l++;});
		return l;
	},
	parent:function(){
		this.each(function(i){this[i] = this[i].parentNode;},this);
		return this;
	},
	next:function(s){
		for(var i=0,l=this.length; i<l; i++)while((this[i]=this[i].nextSibling)&&this[i].nodeType!=1);
		return s?this.filter(s):this;
	},
	prev:function(s){
		for(var i=0,l=this.length; i<l; i++)while((this[i]=this[i].previousSibling)&&this[i].nodeType!=1);
		return s?this.filter(s):this;

	},
	end:function(){
		return this._lastSet||new $.set();
	},
	att:function(n,v){
		if(v==null&&typeof n=='string')return el.att(this[0],n);
		this.each(function(){el.att(this,n,v);});
		return this;
	},
	val:function(v){
		if(v==null)return el.val(this[0]);
		this.each(function(){el.val(this,v);});
		return this;
	},
	valc:function(v){
		if(v==null)return el.valc(this[0]);
		this.each(function(){el.valc(this,v);});
		return this;
	},
	valr:function(v){
		if(v==null){
			var r='';
			this.each(function(){if(this.checked)r = this.value;});
			return r;
		}
		this.each(function(){if(this.value==v)this.checked = true;});
		return this;
	},
	html:function(v,p){
		if(v==null)return this[0]?this[0].innerHTML:undefined;
		this.each(function(){
			if(p===1)this.innerHTML = v+this.innerHTML;
			else if(p===2)this.innerHTML += v;
			else this.innerHTML = v;
		});
		return this;
	},
	before:function(e){
		this.each(function(){el.before(e,this);});
		return this;
	},
	after:function(e){
		this.each(function(){el.after(e,this);});
		return this;
	},
	append:function(e){
		this.each(function(){el.append(e,this);});
		return this;
	},
	prepend:function(e){
		this.each(function(){el.prepend(e,this);});
		return this;
	},
	rChild:function(e){
		this.each(function(){el.rChild(this,e);});
		return this;
	},
	rAll:function(){
		this.each(function(){el.rAll(this);});
		return this;
	},
	txt:function(v){
		if(v==null)return el.txt(this[0]);
		this.each(function(){el.txt(this,v);});
		return this;
	},
	cls:function(v){
		if(v==null)return el.cls(this[0]);
		this.each(function(){el.cls(this,v);});
		return this;
	},
	hCls:function(n){
		return el.hCls(this[0],n);
	},
	aCls:function(n){
		this.each(function(){el.aCls(this,n);});
		return this;
	},
	rCls:function(n){
		this.each(function(){el.rCls(this,n);});
		return this;
	},
	tCls:function(n){
		this.each(function(){el.tCls(this,n);});
		return this;
	},
	css:function(n,v){
		if(v==null&&typeof n=='string')return el.css(this[0],n);
		this.each(function(){el.css(this,n,v);});
		return this;
	},
	posY:function(){
		return el.posY(this[0]);
	},
	posX:function(){
		return el.posX(this[0]);
	},
	clientW:function(){
		return el.clientW(this[0]);
	},
	offsetW:function(){
		return el.offsetW(this[0]);
	},
	scrollW:function(){
		return el.scrollW(this[0]);
	},
	width:function(){
		return el.scrollW(this[0]);
	},
	clientH:function(){
		return el.clientH(this[0]);
	},
	offsetH:function(){
		return el.offsetH(this[0]);
	},
	scrollH:function(){
		return el.scrollH(this[0]);
	},
	height:function(){
		return el.scrollH(this[0]);
	},
	on:function(t,fn){
		return this.each(function(){$.event.add(this,t,fn);});
	},
	un:function(t,fn){
		return this.each(function(){$.event.remove(this,t,fn);});
	}
});



$r = $();
if(document.addEventListener){
	DOMContentLoaded = function(){
		document.removeEventListener('DOMContentLoaded',DOMContentLoaded,false);
		$.ready();
	};
}else if(document.attachEvent){
	DOMContentLoaded = function(){
		if(document.readyState==='complete'){
			document.detachEvent('onreadystatechange',DOMContentLoaded);
			$.ready();
		}
	};
}
function doScrollCheck(){
	if($.isReady)return;
	try{
		document.documentElement.doScroll('left');
	}catch(e){
		setTimeout(doScrollCheck,1);
		return;
	}
	$.ready();
}



el.extend({
	att:function(e,n,v){
		var fn = function(k,v){
			e.setAttribute(k,v+'');
		}
		if(e){
			if(v!=null&&typeof n=='string')fn(n,v);
			else{
				if(typeof n=='object')$.feach(n,fn);
				else return e.getAttribute(n)||'';
			}
		}else return undefined;
	},
	cls:function(e,v){
		if(v==null)return e.className;
		e.className = v;
	},
	hCls:function(e,n){
		return (' '+e.className+' ').indexOf(' '+n+' ')!=-1;
	},
	aCls:function(e,n){
		if((' '+e.className+' ').indexOf(' '+n+' ')==-1)e.className = e.className?e.className+' '+n:n; 
	},
	rCls:function(e,n){
		e.className = (' '+e.className+' ').replace(new RegExp('(\\S*)\\s+'+n+'\\s+(\\S*)','g'),'$1 $2').trim();
	},
	tCls:function(e,n){
		if((' '+e.className+' ').indexOf(' '+n+' ')>=0)this.rCls(e,n);
		else this.aCls(e,n);
	},
	opacity:function(e,a,v){
		if(a==1)a = .99999;
		e.style.opacity = a+'';
		e.style.filter = 'alpha(opacity='+(a*100)+')';
		if(v===1)e.style.visibility = a?'':'hidden';
		else if(v===2)e.style.display = a?'':'none';
	},
	css:function(e,n,v){
		var fn = function(k,v){
			if(k=='opacity')el.opacity(e,v,0);
			else e.style[k] = v;
		}
		if(e){
			if(v!=null&&typeof n=='string')fn(n,v);
			else{
				if(typeof n=='object')$.feach(n,fn);
				else return window.getComputedStyle?// Tenta o modo Mozilla
				document.defaultView.getComputedStyle(e,null)[n]||e.style[n]:// Ou então, tenta a propriedade style
				e.currentStyle?// Tenta o modo IE
				e.currentStyle[n]||// Se não der certo,
				e.style[n]:// tenta a propriedade style. Senão,
				undefined;// Não foi possível recuperar o estilo
			}
		}else return undefined;
	},
	posY:function(e){
		var t = 0;
		while(e){
			t += e.offsetTop;
			e = e.offsetParent;
		}
		return t;
	},
	posX:function(e){
		var t = 0;
		while(e){
			t += e.offsetLeft;
			e = e.offsetParent;
		}
		return t;
	},
	clientW:function(e){
		return e.clientWidth;
	},
	offsetW:function(e){
		return e.offsetWidth;
	},
	scrollW:function(e){
		return e.scrollWidth;
	},
	clientH:function(e){
		return e.clientHeight;
	},
	offsetH:function(e){
		return e.offsetHeight;
	},
	scrollH:function(e){
		return e.scrollHeight;
	},
	val:function(e,v){
		if(!e)return undefined;
		var tag=e.nodeName.toLowerCase(),type=e.type,r='';
		if(v==null){
			if(tag!='select')return e.value;
			r = [];
			for(var i=0;o=e.options[i++];)if(o.selected)r.push(o.value);
			return e.multiple?r:r[0];
		}
		var vt = typeof v;
		if(vt=='object'){
			if(tag=='input'&&(type=='checkbox'||type=='radio')){
				e.checked = false;
				$.each(v,function(){if(e.value==this)e.checked = true;});
			}else if(tag=='select'){
				$.each(e.options,function(i,o){
					if(e.multiple)o.selected = false;
					$.each(v,function(){if(o.value==this)o.selected = true;});
				});
			}
		}else if(vt=='boolean'&&tag=='input'&&(type=='checkbox'||type=='radio'))e.checked = v;
		else e.value = v;
	},
	valc:function(e,v){
		if(!e)return undefined;
		if(e.nodeName.low()!='input'||e.type!='checkbox')return this.val(e,v);
		if(v==null)return e.checked?1:0;
		e.checked = v?true:false;
	},
	txt:(function(){
		var t = typeof document.textContent!='undefined'?'textContent':'innerText';
		var txt = function(e,v){
			return e?v!=null?e[t]=v:e[t]:undefined;
		}
		return txt;
	})(),
	before:function(e,r){
		if(!r)return;
		r.parentNode.insertBefore(e,r);
	},
	after:function(e,r){
		if(!r)return;
		if(r.nextSibling)r.parentNode.insertBefore(e,r.nextSibling);
		else this.append(e,r.parentNode);
	},
	append:function(e,p){
		if(!p)return;
		p.appendChild(e);
	},
	prepend:function(e,p){
		if(!p)return;
		if(!p.firstChild)this.append(e,p);
		else this.before(e,p.firstChild);
	},
	rChild:function(e,f){
		if(!e||e.nodeType!=1)return;
		if(!f){
			f = e;
			e = e.parentNode;
		}
		e.removeChild(f);
	},
	rAll:function(e){
		if(!e||e.nodeType!=1)return;
		while(e.hasChildNodes())this.rChild(e,e.lastChild);
	}
});







/**
 * Namespace responsável pela manipulação de eventos. Adaptado a partir de: 
 * [[http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html|Quirksmode]].
 *  
 * @name $.event
 * @namespace
 */
/**#@+ @extends event */
$.event = function(){
	var _events = [];
	var addEventListener = typeof document.addEventListener!='undefined';
	var attachEvent = typeof document.attachEvent!='undefined';
	return{
		add:function(e,type,fn){
			if(fn==null&&typeof type=='string'){
				if(fn=e['on'+type])fn.call(e);
				$.each(_events,function(i,v){
					if(v.e==e&&v.type==type)v.fn.call(v.e);
				});
				return;
			}
			if(typeof type=='string'){
				var _t = type;
				type = {};
				type[_t] = fn;
			}
			$.feach(type,function(type,fn){
				_events.push({e:e,type:type,fn:fn});
				if(addEventListener)e.addEventListener(type,fn,false);
				else if(attachEvent){
					e['e'+type+fn] = fn;
					e[type+fn] = function(){e['e'+type+fn](window.event);}
					e.attachEvent('on'+type,e[type+fn]);
				}
			});
		},
		remove:function(e,type,fn){
			var l,fs = fn.toString();
			$.each(_events,function(i,v){
				if(v.e==e&&v.type==type&&(v.fn==fn||v.fn.toString()==fs)){
					l = _events.splice(i,1)[0];
					return 1;
				}
			});
			for(var i=0,li; li=_events[i]; i++)if(li.e==e&&li.type==type&&(li.fn==fn||li.fn.toString()==fs)){
				l = _events.splice(i,1)[0];
				break;
			}
			if(l){
				fn = l.fn;
				if(addEventListener)e.removeEventListener(type,fn,false);
				else if(attachEvent){
					e.detachEvent('on'+type,e[type+fn]);
					e[type+fn] = null;
					e['e'+type+fn] = null;
				}
			}
		},
		removeAll:function(){
			for(var i=0;li=_events[i++];)this.remove(li.e,li.type,li.fn);
		}
	}
}();



$.extend(ajax,function(){
	var _r = [], _t = $.XMLHttpRequest(),_callback = null,_s = ['Uninitialized','Loading','Loaded','Interactive','Complete'],
	_send = function(){
		var r = _r.shift(),d;
		_t.open(r.type,r.url,r.async);
		_t.setRequestHeader('X-Requested-With','XMLHttpRequest');
		if(d=$.serialize(r.data))_t.setRequestHeader('Content-Type',r.contentType);
		_t.onreadystatechange = function(){ 
			_sc(r); 
		}; 
		_t.send(d);
	},
	_sc = function(o){
		var fn,s = _getS(); 
		if(fn=o['on'+s])fn.call(o,_getR(o),_t);
		if(s=='Complete'){
			_t.onreadystatechange = function(){};
			var suc = _t.status==200,res = _getR(o);
			if(fn=o['onUpdate'])fn.call(o,res,_t);
			if(fn=o['on'+(suc?'Success':'Failure')])fn.call(o,res,_t);
			if(_r.length)setTimeout(function(){_send();},10);
		}
	},_getR = function(o){
		var type = o.dataType;
		if(_t.status!=200)return _t.statusText;
		else if(type=='text')return _t.responseText;
		else if(type=='html')return _t.responseText;
		else if(type=='xml')return $.xml(_t.responseXML,1);
		else if(type=='json')return eval('('+_t.responseText+')');
	},_getS = function(){
		return _s[_t.readyState];
	};

	return{
    /**
     * Realiza uma requisição ajax.
     * 
     * @param {Object}   options               Opções da requisição.  
     * @param {String}   options.url           URL a ser requisitada.
     * @param {String}   options.type          Tipo de requisição ("get" ou "post"). O padrão é "get".
     * @param {Boolean}  options.async         Indica se a requisição é assíncrona. O padrão é "true".   
     * @param {String}   options.dataType      Dado requisitado ("text", "html", "xml" ou "json"). O padrão é "text".
     * @param {String}   options.contentType   ContentType a ser usado. O padrão é "application/x-www-form-urlencoded".  
     * @param {Function} options.onLoading     Função a ser executada antes da requisição ser enviada.
     * @param {Function} options.onLoaded      Função a ser executada logo que a requisição for enviada.
     * @param {Function} options.onInteractive Função a ser executada durante o recebimento da requisição.
     * @param {Function} options.onComplete    Função a ser executada ao completar a requisição.
     * @param {Function} options.onUpdate      Função a ser executada após completar a requisição.
     * @param {Function} options.onSuccess     Função a ser executada ao completar a requisição com sucesso.
     * @param {Function} options.onError       Função a ser executada ao completar a requisição com erro.
     */      
		request:function(o){
			o = o||{};
			o.type = o.type&&o.type.low()||'get';
			o.async = o.async||true;
			o.dataType = o.dataType||'text'; 
			o.contentType = o.contentType||'application/x-www-form-urlencoded';
			_r.push(o);
			var s = _getS();
			if(s=='Uninitialized'||s=='Complete')_send();
		}  
	}
}());


// Extensão ajax para $.Set. Requer extensão dom de $.Set.
set.extend({ 
  /**#@+
   * @function
   * @memberOf $.Set
   * @extends ajax
   */

  /**
   * Realiza requisição ajax e carrega o conteúdo nos elementos selecionados.
   *    
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   * @name load
   */
	load:function(url,data,callback){
		var d = data||null, fn = callback||null;
		if((typeof data=='function')&&(typeof callback=='undefined')){
			d = null;
			fn = data;
		}
		ajax.request({url:url,data:d,onSuccess:fn,elements:this,onUpdate:function(r,_t){$(this.elements).html(r);}});
		return this;
	}
});


// Extensão ajax para $.
$.extend({
  /**#@+
   * @function
   * @memberOf $
   * @extends ajax
   */

  /**
   * Serializa.
   * 
   * @name serialize
   * @param {Object} data Desc
   */
	serialize:function(data){
		var r = [''],rl = 0;
		if(data){
			if(typeof data=='string')r[rl++] = data;
			else if(data.innerHTML&&data.elements){
				for(var i=0,el,l=(el=data.elements).length; i<l; i++)if(el[i].name){
					r[rl++] = encodeURIComponent(el[i].name); 
					r[rl++] = '=';
					r[rl++] = encodeURIComponent(el[i].value);
					r[rl++] = '&';
				}
			}else for(param in data){
				r[rl++] = encodeURIComponent(param); 
				r[rl++] = '=';
				r[rl++] = encodeURIComponent(data[param]);
				r[rl++] = '&';
			}
		}
		return r.join('').replace(/&$/,"");
	},

  /**
   * Realiza uma requisição ajax do tipo "get", retornando texto.
   *    
   * @name get
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   */
	get:function(url,data,callback){
		var u = url||null,d = data||null,fn = callback||null,e = {};
		if(typeof callback=='undefined'){
			if(typeof data=='undefined'&&typeof url=='object'){
				e = url;
				u = null;
			}else{
				d = null;
				fn = data;
			}
		}
		ajax.request($.extend({url:u,data:d,onSuccess:fn},e));
	},

  /**
   * Realiza uma requisição ajax do tipo "get", retornando JSON.
   *
   * @name getJSON
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   */
	getJSON:function(url,data,callback,_){
		var u = url||null,d = data||null,fn = callback||null,e = {};
		if(typeof callback=='undefined'){
			if(typeof data=='undefined'&&typeof url=='object'){
				e = url;
				u = null;
			}else{
				d = null;
				fn = data;
			}
		}
		ajax.request($.extend({url:url,data:d,dataType:'json',onSuccess:fn},e));
	},

  /**
   * Realiza uma requisição ajax do tipo "get", retornando XML.
   *
   * @name getXML
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   */
	getXML:function(url,data,callback,_){
		var u = url||null,d = data||null,fn = callback||null,e = {};
		if(typeof callback=='undefined'){
			if(typeof data=='undefined'&&typeof url=='object'){
				e = url;
				u = null;
			}else{
				d = null;
				fn = data;
			}
		}
		ajax.request($.extend({url:url,data:d,dataType:'xml',onSuccess:fn},e));
	},

  /**
   * Realiza uma requisição ajax do tipo "post".
   *
   * @name post
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   */
	post:function(url,data,callback,_){
		var u = url||null,d = data||null,fn = callback||null,e = {};
		if(typeof callback=='undefined'){
			if(typeof data=='undefined'&&typeof url=='object'){
				e = url;
				u = null;
			}else{
				d = null;
				fn = data;
			}
		}
		ajax.request($.extend({url:url,type:'post',data:d,onSuccess:fn},e));
	},

  /**
   * Realiza uma requisição ajax do tipo "post", retornando XML.
   *
   * @name postXML
   * @param {String}   url       URL a ser requisitada.
   * @param {Data}     data      Dados a serem enviados.
   * @param {Function} callback  Função de retorno.
   */
	postXML:function(url,data,callback,_){
		var u = url||null,d = data||null,fn = callback||null,e = {};
		if(typeof callback=='undefined'){
			if(typeof data=='undefined'&&typeof url=='object'){
				e = url;
				u = null;
			}else{
				d = null;
				fn = data;
			}
		}
		ajax.request($.extend({url:url,type:'post',data:d,dataType:'xml',onSuccess:fn},e));
	},

  /**
   * Carrega um script dinamicamente.
   *    
   * @name loadScript
   * @param {String}   url       URL do script.
   */
	loadScript:function(url){
		var script = document.getElementById('dynamicScript');
		if(script)script.parentNode.removeChild(script);
		script = document.createElement('script');
		script.setAttribute('src',url);
		script.setAttribute('id','dynamicScript');
		script.setAttribute('type','text/javascript');
		document.documentElement.firstChild.appendChild(script);
	},

  /**
   * Carrega JSON remotamente (JSONP).
   *    
   * @name loadJSONP
   * @param {String}   url       URL dos dados.
   * @param {String}   jsonp     Nome da função de retorno do servidor. O 
   *                             padrão é "callback".
   * @param {Function} callback  Função de retorno.
   */
	loadJSONP:function(url,jsonp,callback){
		var j = jsonp||'callback',fn = callback||$.emptyFn,
		script = document.getElementById('dynamicScript');
		if((typeof jsonp=='function')&&(typeof callback=='undefined')){
			j = 'callback';
			fn = jsonp;
		}
		if(script)script.parentNode.removeChild(script);
		ajax._callback = fn;
		script = document.createElement('script');
		script.setAttribute('src',url+'&'+j+'=$.ajax._callback');
		script.setAttribute('id','dynamicScript');
		script.setAttribute('type','text/javascript');
		document.documentElement.firstChild.appendChild(script);
	}
});














/**
 * Namespace responsável pela seleção de elementos através de seletores CSS. 
 * Baseado em 
 * [[http://extjs.com/deploy/ext/docs/output/Ext.DomQuery.html|DomQuery]].
 * 
 * @name $.query
 * @namespace
 */
/** @ignore */
$.query = function(){
  /**#@+ 
   * @private 
   * @function
   * @memberOf $.query
   * @extends core
   */

  var cache = {}, 
    simpleCache = {}, 
    reTrim = /^\s+|\s+$/g,
    reTemplate = /\{(\d+)\}/g,
    reMode = /^(\s?[\/>+~]\s?|\s|$)/,
    reTag = /^(#)?([\w-\*]+)/,
    reNth = /(\d*)n\+?(\d*)/, 
    reNth2 = /\D/,

    // This is for IE MSXML which does not support expandos.
    // IE runs the same speed using setAttribute, however FF slows way down
    // and Safari completely fails so they need to continue to use expandos.
    isIE = !!window.ActiveXObject,
    key = 30803;

  // this eval is stop the compressor from
  // renaming the variable to something shorter
  eval("var batch = 30803;");

  function _quickId(e, mode, context, val){
    if(e == context){
      var d = context.ownerDocument || context;
      return d.getElementById(val);
    }
    e = _getNodes(e, mode, "*");
    return _byId(e, val);
  };

  var _byId = function(e, val){
    if(e.tagName || e == document)
      e = [e];

    var r = new Array(), rl = -1;
    for(var i = 0, ei; ei = e[i]; i++)
      if(ei && ei.id == val){
        r[++rl] = ei;
        return r;
      }
    return r;
  };

  var _byTag = function(e, val){
    if(e.tagName || e == document)
      e = [e];

    var r = new Array(), rl = -1;
    val = val.toLowerCase();
    for(var i = 0, ei; ei = e[i]; i++)
      if(ei.nodeType == 1 && ei.tagName.toLowerCase()==val)
        r[++rl] = ei;

    return r;
  };

  var _byClass = function(e, val){
    if(!val)
      return e;

    var r = new Array(), rl = -1;
    for(var i = 0, ei; ei = e[i]; i++)
      if((' '+ei.className+' ').indexOf(val) != -1)
        r[++rl] = ei;

    return r;
  };

  var _byAttr = function(e, attr, op, val){
    var r = new Array(), rl = -1, f = query.operators[op];
    for(var i = 0, ei, a; ei = e[i]; i++){
      if(attr == "class" || attr == "className")
        a = ei.className;
      else if(attr == "for")
        a = ei.htmlFor;
      else if(attr == "href")
        a = ei.getAttribute("href", 2)
      else
        a = ei.getAttribute(attr);

      if((f && f(a, val)) || (!f && a))
        r[++rl] = ei;
    }
    return r;
  };

  var _byPseudo = function(e, name, val){
    return query.pseudos[name](e, val);
  };

  var _getNodes = function(e, mode, name){
    var r = new Array(), rl = -1;
    if(!e)
      return r;

    name = name || "*";
    if(typeof e.getElementsByTagName != "undefined")
      e = [e];

    if(!mode){
      for(var i = 0, ei, n; ei = e[i]; i++){
        n = ei.getElementsByTagName(name);
        for(var j = 0, nj; nj = n[j]; j++)
          r[++rl] = nj;
      }
    }else if(mode == "/" || mode == ">"){
      var utag = name.toUpperCase();
      for(var i = 0, ei, n; ei = e[i]; i++){
        n = ei.children || ei.childNodes;
        for(var j = 0, nj; nj = n[j]; j++)
          if(nj.nodeName == utag || nj.nodeName == name  || name == '*')
            r[++rl] = nj;

      }
    }else if(mode == "+"){
      var utag = name.toUpperCase();
      for(var i = 0, ei; ei = e[i]; i++){
        while((ei = ei.nextSibling) && ei.nodeType != 1);
        if(ei && (ei.nodeName == utag || ei.nodeName == name || name == '*'))
          r[++rl] = ei;
      }
    }else if(mode == "~"){
      for(var i = 0, ei; ei = e[i]; i++){
        while((ei = ei.nextSibling) && (ei.nodeType != 1 || 
              (name == '*' || ei.tagName.toLowerCase()!=name)));
        if(ei)
          r[++rl] = ei;
      }
    }
    return r;
  };

  var _unique = function(e){
    if(!e)
      return new Array();

    var len = e.length, i, r = e, ei;
    if(!len||typeof e.nodeType!="undefined"||len==1)
      return e;

    if(isIE&&typeof e[0].selectSingleNode!="undefined"){
      var d = ++key;
      e[0].setAttribute("__unique", d);
      var r = [e[0]], rl = 0;
      for(var i = 1, ei; ei = e[i]; i++)
        if(!ei.getAttribute("__unique") != d){
          ei.setAttribute("__unique", d);
          r[++rl] = ei;
        }
  
      for(var i = 0; ei = e[i]; i++)
        ei.removeAttribute("__unique");
  
      return r;
    }

    var d = ++key;
    e[0].__unique = d;
    for(i = 1, ei; ei = e[i]; i++){
      if(ei.__unique != d)
        ei.__unique = d;
      else{
        r = new Array(), rl = -1;
        for(var j = 0; j < i; j++)
          r[++rl] = e[j];

        for(j = i+1; ej = e[j]; j++)
          if(ej.__unique != d){
            ej.__unique = d;
            r[++rl] = ej;
          }
        return r;
      }
    }
    return r;
  };

  var _diff = function(e, e2){
    if(!e.length)
      return e2;

    if(isIE && e[0].selectSingleNode) {
      var d = ++key, ei;
      for(var i = 0; ei = e[i]; i++)
        ei.setAttribute("__diff", d);
  
      var r = new Array(), rl = -1;
      for(var i = 0; ei = e2[i]; i++)
        if(ei.getAttribute("__diff") != d)
          r[++rl] = ei;
  
      for(var i = 0; ei = e[i]; i++)
        ei.removeAttribute("__diff");
  
      return r;
    }

    var d = ++key;
    for(var i = 0; ei = e[i]; i++)
      ei.__diff = d;

    var r = new Array(), rl = -1;
    for(var i = 0; ei = e2[i]; i++)
      if(ei.__diff != d)
        r[++rl] = ei;

    return r;
  };

  var _next = function(e){
    while((e = e.nextSibling) && e.nodeType != 1);
    return e;
  };

  var _prev = function(e){
    while((e = e.previousSibling) && e.nodeType != 1);
    return e;
  };

  /**#@-*/
  /**#@+ @extends core */
  return /** @lends $.query */ {
    /**
     * Compiles a selector/xpath query into a reusable function. The returned function
     * takes one parameter "context" (optional), which is the context node from where the query should start.
     * @param {String} selector The selector/xpath query
     * @param {String} type (optional) Either "select" (the default) or "simple" for a simple selector match
     * @return {Function}
     */
    compile: function(selector, type){
      type = type || "select";

      var s = selector, ls,
        rules = query.rules,
        mm, tm, rm, matched, fl = 0, 
        f = ["var fn=function(c){\nvar mode; var e=c||document; ++batch;\n"];

      // accept leading mode switch
      mm = s.match(reMode);
      if(mm && mm[1]){
        f[++fl] = 'mode="'+mm[1].replace(reTrim, "")+'";';
        s = s.replace(mm[1], "");
      }

      // strip leading slashes
      while(s.substr(0, 1)=="/")
        s = s.substr(1);

      while(s && ls != s){
        ls = s;
        tm = s.match(reTag);
        if(type == "select"){
          if(tm){
            if(tm[1] == "#")
              f[++fl] = 'e = _quickId(e, mode, c, "'+tm[2]+'");';
            else
              f[++fl] = 'e = _getNodes(e, mode, "'+tm[2]+'");';

            s = s.replace(tm[0], "");
          }else if(s.substr(0, 1) != '@')
            f[++fl] = 'e = _getNodes(e, mode, "*");';

        }else
          if(tm){
            if(tm[1] == "#")
              f[++fl] = 'e = _byId(e, "'+tm[2]+'");';
            else
              f[++fl] = 'e = _byTag(e, "'+tm[2]+'");'

            s = s.replace(tm[0], "");
          }

        while(!(mm = s.match(reMode))){
          matched = false;
          for(var j = 0; rm = rules[j]; j++){
            var m = s.match(rm.re);
            if(m){
              f[++fl]=rm.select.replace(reTemplate, function(e,i){return m[i];});
              s = s.replace(m[0], "");
              matched = true;
              break;
            }
          }
          // prevent infinite loop on bad selector
          if(!matched)
            throw 'Error parsing selector, parsing failed at "' + s + '"';
        }
        if(mm[1]){
          f[++fl] = 'mode="'+mm[1].replace(reTrim, "")+'";';
          s = s.replace(mm[1], "");
        }
      }
      f[++fl] = "return _unique(e);\n}";
      eval(f.join(""));
      return fn;
    },

    /**
     * Selects a group of elements.
     * @param {String} selector The selector/xpath query (can be a comma separated list of selectors)
     * @param {Node} context (optional) The start of the query (defaults to document).
     * @return {Array}
     */
	select: function(selector,context){
		context = context||document;
		if(typeof context=="string")context = document.getElementById(context);
		var selectors = selector.split(","),len = selectors.length,results = new Array();
		for(var i=0; i<len; i++){
			var s = selectors[i].replace(reTrim,"");
			if(!cache[s])if(!(cache[s]=query.compile(s)))throw s + " is not a valid selector";
			var result = cache[s](context);
			if(result&&result!=document)results = results.concat(result);
		}
		if(len>1)return _unique(results);
		return results;
	},

    /**
     * Returns true if the passed element(s) match the passed simple selector (e.g. div.some-class or span:first-child)
     * @param {String/HTMLElement/Array} e An element id, elvalent or array of elements
     * @param {String} selector The simple selector to test
     * @return {Boolean}
     */
	is:function(e,ss){
		if(typeof e=="string")e = document.getElementById(e);
		var isArray = !!e.splice,result = query.filter(isArray?e:[e],ss);
		return isArray?(result.length==e.length):(result.length>0);
	},

    /**
     * Filters an array of elements to only include matches of a simple selector (e.g. div.some-class or span:first-child)
     * @param {Array} e An array of elements to filter
     * @param {String} selector The simple selector to test
     * @param {Boolean} nonMatches If true, it returns the elements that DON'T match
     * the selector instead of the ones that match
     * @return {Array}
     */
	filter:function(e,ss,nonMatches){
		ss = ss.replace(reTrim,"");
		if(!simpleCache[ss])simpleCache[ss] = query.compile(ss,"simple");
		var result = simpleCache[ss](e);
		return nonMatches?_diff(result,e):result;
	},

    /**
     * Collection of matching regular expressions and code snippets.
     */
	rules:[
		{
			re:/^\.([\w-]+)/,
			select:'e = _byClass(e, " {1} ");'
		},{
			re:/^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,
			select:'e = _byPseudo(e, "{1}", "{2}");'
		},{
			re:/^\[([\w-]+)(?:(.?=)["']?(.+?)["']?)?\]/,
			select:'e = _byAttr(e, "{1}", "{2}", "{3}");'
		},{
			re:/^#([\w-]+)/,
			select:'e = _byId(e, "{1}");'
		}
	],

    /**
     * Collection of operator comparison functions. The default operators are =, !=, ^=, $=, *=, %=, |= and ~=.
     * New operators can be added as long as the match the format <i>c</i>= where <i>c</i> is any character other than space, &gt; &lt;.
     */
	operators:{
		"=":function(attr,val){
			return attr==val;
		},
		"!=":function(attr,val){
			return attr!=val;
		},
		"^=":function(attr,val){
			return attr&&attr.substr(0,val.length)==val;
		},
		"$=":function(attr,val){
			return attr&&attr.substr(attr.length-val.length)==val;
		},
		"*=":function(attr,val){
			return attr&&attr.indexOf(val)!==-1;
		},
		"%=":function(attr,val){
			return(attr%val)==0;
		},
		"|=":function(attr,val){
			return attr&&(attr==val||attr.substr(0,val.length+1)==val+'-');
		},
		"~=": function(attr,val){
			return attr&&(' '+attr+' ').indexOf(' '+val+' ')!=-1;
		}
	},

    /**
     * Collection of "pseudo class" processors. Each processor is passed the current nodeset (array)
     * and the argument (if any) supplied in the selector.
     */
    pseudos: {
      "first-child": function(e){
        var r = new Array(), rl = -1, n;
        for(var i = 0, ei; ei = n = e[i]; i++){
          while((n = n.previousSibling) && n.nodeType != 1);
          if(!n)
            r[++rl] = ei;
        }
        return r;
      },

      "last-child": function(e){
        var r = new Array(), rl = -1, n;
        for(var i = 0, ei; ei = n = e[i]; i++){
          while((n = n.nextSibling) && n.nodeType != 1);
          if(!n)
            r[++rl] = ei;
        }
        return r;
      },

      "nth-child": function(e, val) {
        var r = new Array(), rl = -1, m = reNth.exec(val == "even" && "2n" || 
          val == "odd" && "2n+1" || !reNth2.test(val) && "n+" + val || val),
          f = (m[1] || 1) - 0, l = m[2] - 0;
        for(var i = 0, ei; ei = e[i]; i++){
          var p = ei.parentNode;
          if (batch != p._batch) {
            var j = 0;
            for(var n = p.firstChild; n; n = n.nextSibling)
              if(n.nodeType == 1)
                 n.nodeIndex = ++j;

            p._batch = batch;
          }
          if (f == 1) {
            if (l == 0 || ei.nodeIndex == l)
              r[++rl] = ei;

          } else if ((ei.nodeIndex + l) % f == 0)
            r[++rl] = ei;
        }

        return r;
      },

      "only-child": function(e){
        var r = new Array(), rl = -1;;
        for(var i = 0, ei; ei = e[i]; i++)
          if(!_prev(ei) && !_next(ei))
            r[++rl] = ei;

        return r;
      },

      "empty": function(e){
        var r = new Array(), rl = -1;
        for(var i = 0, ei; ei = e[i]; i++){
          var n = ei.childNodes, j = -1, nj, empty = true;
          while(nj = n[++j])
            if(nj.nodeType == 1 || nj.nodeType == 3){
              empty = false;
              break;
            }

          if(empty)
            r[++rl] = ei;
        }
        return r;
      },

      "contains": function(e, val){
        var r = new Array(), rl = -1;
        for(var i = 0, ei; ei = e[i]; i++)
          if((ei.textContent||ei.innerText||'').indexOf(val) != -1)
            r[++rl] = ei;

        return r;
      },

      "nodeValue": function(e, val){
        var r = new Array(), rl = -1;
        for(var i = 0, ei; ei = e[i]; i++)
          if(ei.firstChild && ei.firstChild.nodeValue == val)
            r[++rl] = ei;

        return r;
      },

      "checked": function(e){
        var r = new Array(), rl = -1;
        for(var i = 0, ei; ei = e[i]; i++)
          if(ei.checked == true)
            r[++rl] = ei;

        return r;
      },

      "not": function(e, val){
        return query.filter(e, val, true);
      },

      "any": function(e, val){
        var r = new Array(), rl = -1, s, ss = val.split('|');
        for(var i = 0, ei; ei = e[i]; i++)
          for(var j = 0; s = ss[j]; j++)
            if(query.is(ei, s)){
              r[++rl] = ei;
              break;
            }

        return r;
      },

      "odd": function(e){
        return this["nth-child"](e, "odd");
      },

      "even": function(e){
        return this["nth-child"](e, "even");
      },

      "nth": function(e, val){
        return e[val-1] || new Array();
      },

      "first": function(e){
        return e[0] || new Array();
      },

      "last": function(e){
        return e[e.length-1] || new Array();
      },

      "has": function(e, val){
        var r = new Array(), rl = -1, s = query.select;
        for(var i = 0, ei; ei = e[i]; i++)
          if(s(val, ei).length > 0)
            r[++rl] = ei;

        return r;
      },

      "next": function(e, val){
        var r = new Array(), rl = -1, is = query.is;
        for(var i = 0, ei; ei = e[i]; i++){
          var n = _next(ei);
          if(n && is(n, val))
            r[++rl] = ei;
        }
        return r;
      },

      "prev": function(e, val){
        var r = new Array(), rl = -1, is = query.is;
        for(var i = 0, ei; ei = e[i]; i++){
          var n = _prev(ei);
          if(n && is(n, val))
            r[++rl] = ei;
        }
        return r;
      }
    }
  }
}();

// Atalho para $.query
var query = $.query;
})();
window.$ = window.jBr;













