/* Util.js JavaScript library Functions by Lucas Ferreira - http://www.lucasferreira.com/
*  Bugs and Reports: panchorf@gmail.com
*  Version: 3.9b */

/* Browser info class */
var Browser = {
	init: function()
	{
		this.os = (navigator.platform || "win").toString().toLowerCase();
		this.nav = (navigator.userAgent || "msie").toString().toLowerCase();
		this.nav_version = (navigator.appVersion || "1.0").toString();
		this.init_time = (new Date()).getTime();
		this.end_time = 0;
	},
	isIE: function(){ return (window.ActiveXObject && document.all && this.nav.indexOf("msie") > -1  && this.nav.indexOf("opera") == -1); },
	isOpera: function(){ return (window.ActiveXObject == undefined && this.nav.indexOf("opera") > -1); },
	isMozilla: function(){ return (this.nav.indexOf('Mozilla') > -1 && parseInt(this.nav_version.substring(0, 1)) >= 5); },
	isWin: function(){ return (this.os.indexOf("win") > -1); },
	isLinux: function(){ return (this.os.indexOf("lin") > -1); },
	isMac: function(){ return (this.os.indexOf("mac") > -1); }
};
Browser.init();

/* Delegate class */
Delegate = { version: "1.6b" };
Delegate.create = function(obj, func, args){
	var f = function(){
		var target = arguments.callee.target;
		var func = arguments.callee.func;
		var args = arguments.callee.args;
		return func.apply(target, (args.length < 1 ? arguments : args));
	};
	extendObject(f, {
		args: (args != undefined && args.length > 0 ? args : new Array()),
		target: obj, func: func
	});
	return f;
};
window.Delegate = Delegate;

/* BodyLoad class */
var BodyLoad = {
	onloads: new Array(),
	add: function(f){ if(typeof f == "function") BodyLoad.onloads.push(f); },
	onLoad: function()
	{
		Browser.end_time = (new Date()).getTime();
		for(var i=0; i<BodyLoad.onloads.length; i++) BodyLoad.onloads[i].call(this);
	},
	init: function()
	{
		if(!window.onload)
		{
			window.onload = BodyLoad.onLoad;
		}
		else
		{
			var oldLoad = window.onload;
			window.onload = function()
			{
				oldLoad();
				Delegate.create(window, BodyLoad.onLoad)();
			}
		}
		if(window.initContentLoad != undefined) BodyLoad.onContent(window.initContentLoad);
	},
	onContent: function(f) //(C)webreflection.blogspot.com
	{
		var a,b=navigator.userAgent,d=document,w=window,
		c="__onContent__",e="addEventListener",o="opera",r="readyState",
		s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,"()}'></scr","ipt>");
		w[c]=(function(o){return function(){w[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(w[c]);
		if(d[e])d[e]("DOMContentLoaded",w[c],false);
		if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))
		(function(){/loaded|complete/.test(d[r])?w[c]():setTimeout(arguments.callee,1)})();
		else if(/MSIE/i.test(b))d.write(s);
	}
};
function initContentLoad()
{
	for(var i=0, a = document.links; i<a.length; i++)
		if(a[i].rel && a[i].rel == "blank") a[i].target = "_blank";
	
	if(document.body) extendObject(document.body, $.extendsDOM);
}
var _c = BodyLoad.onContent;
BodyLoad.init();


/* Prototypes Utils */
function extendObject(obj, ext, over)
{
	if(over == undefined) over = false;
	for (var p in ext)
	{
		if(typeof obj[p] == "undefined" || over) obj[p] = ext[p];
	}
	return obj;
}
extendObject.elements = function(objs, ext, over)
{
	for(var i=0; i<objs.length; i++) extendObject(objs[i], ext, (over || false));
	return objs;
};
if(!Array.prototype.push)
{
	Array.prototype.push = function(a){ this[this.length] = a; };
}

extendObject(String.prototype, {
	
	trim: function() { return this.toString().replace(/^\s*|\s*$/g, ""); },
	
	replaceAll: function(f, r){
		var s = this.toString();
		while(s.indexOf(f) > -1) s = s.replace(f, r);
		return s;
	},
	
	toNumber: function(){
		var s = this.toString().replaceAll(".", "").replace(",", ".").replaceAll(",", "");
		return isNaN(new Number(s)) ? 0 : new Number(s);
	},
	
	toMoeda: function(c){
		if(c == undefined) var c = 2;
		var s = this.toString().split(".");
		if(s.length > 1) s[1] = s[1].substr(0, c); else s[1] = "00";
		while(s[1].length < c) s[1] += "0";
		return s.join(",");
	},
	
	toObject: function(){
		return eval('(' + this.toString() + ')');
	}
	
});

Array.prototype.each = function(f){
	for(var i=0, a = (this || []); i<a.length; i++) Delegate.create(a, f, [i])(); return a;
};
Array.prototype.run = function(f){
	for(var i=0, a = (this || []); i<a.length; i++) Delegate.create(a[i], f, [i])(); return a;

};
extendObject(Array.prototype, {
	first: function(){ return (this.length > 0) ? this[0] : null; },
	last: function(){ return (this.length > 0) ? this[this.length-1] : null; },
	read: function(){ Delegate.create(a=(this || []), arguments[0], [a.length])(); },
	apply: function()
	{
		if((a=arguments).length < 1) return false;

		for(var i=1,f=a[0],args=[]; i<a.length; i++) args.push(a[i]);
		
		this.run(function(i){
			if(!empty(this[f]) && typeof this[f] == "function")
			{
				this[f].apply(this, args);
			}
		});
		
		return this;
	},
	find: function(e)
	{
		for(var i=0, a = (this || []); i<a.length; i++)
		{
			if(a[i] == e) return a[i];
		}
		return false;
	},
	remove: function(i)
	{
		this.splice(i, 1);
		return this;
	},
	merge: function(a)
	{
		this.concat(a)
		return this;
	}

});

/* Event class */
var Event = {

	unloadAdded: false,
	aEvts: new Array(),
	
	add: function(obj, evType, fn, useCapture)
	{
		useCapture = typeof useCapture == "undefined" ? true : useCapture;
		if(typeof obj == "array")
		{
			obj.each(function(i){ Event.add(this[i], evType, fn); });
			return true;
		}
		var obj = (typeof obj == "string") ? $(obj) : obj;
		if(!obj || obj == null) return false;
		if(obj.attachEvent) obj.attachEvent("on" + evType, fn);
		else if(obj.addEventListener) obj.addEventListener(evType, fn, useCapture);
		else obj["on" + evType] = fn;
		
		Event.aEvts.push(typeof Event.add.arguments == "array" ? Event.add.arguments : [obj, evType, fn, useCapture]);
		
		if(!Event.unloadAdded)
		{
			Event.unloadAdded = true;
			Event.add(window, "unload", Event.unloadEvents, false);
		}
	},

	remove: function(obj, evType, func, useCapture)
	{
		useCapture = typeof useCapture == "undefined" ? true : useCapture;
		if(typeof obj == "array")
		{
			obj.each(function(i){ Event.remove(this[i], evType, fn); });
			return true;
		}
		var obj = (typeof obj == "string") ? $(obj) : obj;
		if(!obj || obj == null) return false;		
		if(obj.detachEvent) obj.detachEvent("on" + evType, func);
		if(obj.removeEventListener) obj.removeEventListener(evType, func, useCapture);
		if(obj["on" + evType])
		{
			obj["on" + evType] = function(){};
			delete obj["on" + evType];
		}
	},
	
	unloadEvents: function(){
		for(var i=0; i<(Event.aEvts.length); (Event.remove.apply(this, Event.aEvts[i]), Event.aEvts[i][0]=null), i++);
	}
	
};
window.addEvent = Event.add;
window.remEvent = Event.remove;

/* MISCELANIOUS FUNCTIONS */
function initValue(o){
	var o = getTargetByEvent(o || window.event);
	if(o.initVal == undefined) {
		o.initVal = o.value;
		Event.add(o, "blur", function(e){
			var o = getTargetByEvent(e || window.event);
			if(o.value.length < 1) o.value = o.initVal;
		});
	}
	if(o.value == o.initVal) o.value = "";
}

function getStyle(e, p){
	if(typeof e == "string") var e = $(e);
	if(e.style && e.style[p]) return e.style[p];
	else if(e.currentStyle && e.currentStyle[p]) return e.currentStyle[p];
	else if(document.defaultView && document.defaultView.getComputedStyle)
	{
		return document.defaultView.getComputedStyle(e, "")[p];
	}
	return false;
}

function chr(n){ return (String.fromCharCode(n) || null); }

function empty(o)
{
	if(typeof o == "undefined")
	{
		return true;
	}
	else if(o == null)
	{
		return true;
	}
	else if(o.length < 1)
	{
		return true;
	}
	return false;
}

/* AJAX FUNCTIONS */
function Ajax()
{
	if(Ajax.arguments.length > 0)
	{
		return Ajax.getInstace.apply(Ajax, Ajax.arguments);
	}
	
	this.xhr = Ajax.getTransport();
	this.headers = {};
	this.async = true;
	
	for(var i in this.xhr)
	{
		try {
			if(typeof this.xhr[i] == "function")
				this[i] = Delegate.create(this.xhr, this.xhr[i]);
			else
				this[i] = this.xhr[i];
		} catch(e) {
			continue;
		}
	}
	
	this.onLoad = function(){}
	this.onState = function(){}
	
	this.readState = function()
	{
		try { s = this.xhr.status; } catch(e) { s = 0; }
		try { r = this.xhr.readyState; } catch(e) { r = 0; }
		
		this.onState(r, s);
		
		this.registerProperts();
		
		if(this.xhr.readyState == 4)
		{
			this.readyState = this.xhr.readyState;
			this.status = this.xhr.status;
			this.responseText = this.xhr.responseText;
			this.responseXML = this.xhr.responseXML;
			this.onLoad();
		}
	};
	
	this.registerProperts = function()
	{
		for(var i in this.xhr)
		{
			try {
				if(typeof this.xhr[i] != "function") this[i] = this.xhr[i];
			} catch(e) {
				continue;
			}
		}	
	}
	
	this.setRequestHeader = function(t, v)
	{
		var c = {}; c[t] = v;
		this.setHeaders(c);
	};
	
	this.setHeaders = function(c){ extendObject(this.headers, c); };
	
	this.openAndSend = function(url, method, a, sendPack)
	{
		this.open((method || "GET"), url, (a || this.async));	
		this.xhr.send(sendPack || null);
	};
	
	this.open = function(method, url, a)
	{
		this.xhr.open((method || "GET"), url, (a || this.async));
		for(var h in this.headers) this.xhr.setRequestHeader(h.toString(), this.headers[h]);
		this.xhr.onreadystatechange = Delegate.create(this, this.readState);
	};
	
	this.getXHR = this.x = function(){ return this.xhr; };
	
}
Ajax.getTransport = function()
{
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	for(var i=0; i<prefixes.length; i++){
		try { return new ActiveXObject(prefixes[i] + ".XmlHttp"); } catch(e) { continue; }
	}
	try {
		return new XMLHttpRequest();
	} catch(e){
		return false;
	}
};
Ajax.getInstace = function(url, cfg)
{
	var _instance = new Ajax(), nargs = [url];
	if(cfg != undefined)
	{
		if(typeof cfg != "function")
		{
			for(var i in cfg) _instance[i] = cfg[i];
		}
		else
		{
			_instance["onLoad"] = cfg;
		}
		nargs.push(cfg["method"] != undefined ? cfg["method"] : "GET");
		nargs.push(cfg["async"] != undefined ? cfg["async"] : _instance.async);
		nargs.push(cfg["sendPack"] != undefined ? cfg["sendPack"] : null);		
	}
	_instance.openAndSend.apply(_instance, nargs);
	return _instance;
};

/* FixSFMenu CLASS */
function FixSFMenu(menu)
{
	var menu = (typeof menu == "string") ? $(menu) : menu;
	$t("LI", menu).run(function()
	{
		if(!empty(ul = $t("UL", this))) FixSFMenu.registerEvents(this, ul.last());
	});
}
FixSFMenu.registerEvents = function(li, ul)
{
	li.e("mouseover", function(){ this.addClass("over"); });
	li.e("mouseout", function(){ this.remClass("over"); });
	
	if(!empty(ali=$t("A", li))) ali.first().e("focus", function(){ this.parentNode.addClass("over"); });

	if(!empty(a=$t("A", ul)) && ((a=a.last()).parentLI = li))
		a.e("blur", function(){ this.parentLI.remClass("over"); });
};

/* DOM functions */
function getTargetByEvent(e)
{
	if(typeof(e) == "undefined") var e = window.event;
	source = e.target ? e.target : e.srcElement;
	return source;
}
var $target = getTargetByEvent;

function $(){
	for(var i=0, elements=[], args=(typeof $.arguments[0] == "array" ? $.arguments[0] : $.arguments); i < args.length; i++)
	{
		var ne, e = elements[elements.length] = ( (document.getElementById(args[i]) || (document.all && document.all[args[i]])) || document[args[i]] ) || null;
		e = elements[elements.length-1] = (e == null && (ne = elements[elements.length-1] = $$(args[i])) && ne.length > 0) ? ne : e;
		if(e != null) (e.length && e.length > 0) ? extendObject.elements(e, $.extendsDOM) : extendObject(e, $.extendsDOM);
	}
	return elements.length == 1 ? (elements[0] != null ? elements[0] : []) : elements;
}
$.extendsDOM = {
	addEvent: function(evt, f)
	{
		Event.add(this, evt, Delegate.create(this, f));
		return this;
	},
	remEvent: function(evt, f)
	{
		Event.remove(this, evt, Delegate.create(this, f));
		return this;
	},
	cancelEvent: function(evt)
	{
		try { evt.preventDefault(); } catch(e) { window.event.returnValue=false; }
		return this;
	},
	e: function(evt, f)
	{
		return this.addEvent(evt, f);
	},
	css: function(css)
	{
		extendObject(this.style, css, true);
		return this;
	},
	addClass: function(c)
	{
		if(!(this.className.split(" ").find(c)))
		{
			this.className += " " + c;
		}
		return this;
	},
	remClass: function(c)
	{
		if(this.className.split(" ").find(c))
		{
			this.className = this.className.split(c).join(" ").replaceAll("  ", " ");
		}
		return this;
	},
	toggle: function(t)
	{
		if(t == undefined || t == false)
		{
			this.style.display = (this.style.display && this.style.display == "none" ? "" : "none");
		}
		else
		{
			this.style.visibility = (this.style.visibility && this.style.visibility == "hidden" ? "visible" : "hidden");
		}
		return this;
	},
	show: function()
	{
		this.style.visibility = "visible";
		return this;
	},
	hide: function()
	{
		this.style.visibility = "hidden";
		return this;
	},
	setHeight: function(h)
	{
		this.style.height = h + "px";
		return this;
	},
	setWidth: function(w)
	{
		this.style.width = w + "px";
		return this;
	},
	setSize: function(w, h)
	{
		return this.setWidth(w).setHeight(h);
	},
	getHeight: function()
	{
		return this.offsetHeight;
	},
	getWidth: function()
	{
		return this.offsetWidth;
	},
	top: function(obj)
	{
		if(this.firstChild)
		{
			return this.insertBefore(obj, this.firstChild)
		}
		else return this.append(obj);
	},
	bottom: function(obj)
	{
		if(this.lastChild)
		{
			return this.insertBefore(obj, this.lastChild)
		}
		else return this.append(obj);
	},
	append: function(obj)
	{
		return this.appendChild(obj);
	},
	before: function(obj)
	{ 
		return this.parentNode.insertBefore(obj, this);
	},
	after: function(obj)
	{ 
		return this.parentNode.insertBefore(obj, this.nextSibling);
	},
	remove: function()
	{
		return (this.parentNode.removeChild(this));
	},
	clone: function()
	{
		return this.cloneNode(true);
	}
};

function $$(rule, o)
{
	for(var i = 0, parts = rule.split(" "), nodes = [(o || document)]; i < parts.length; nodes = $$.getSelectedNodes(parts[i], nodes), i++);
	return nodes;
}
$$.getSelectedNodes = function(select, elements)
{
	var nodes = new Array(), element = null;
	if(s = select.match(/^(\w*)\[([!-]?)(\w+)([=~!\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
	{
		return $$.filterByAttr(s, elements);
	}
	if(identify = (/\#([a-z0-9_-]+)/i).exec(select))
	{
		return ((element = $(identify[1])) && !empty(element)) ? [element] : nodes;
	}
	var classname = (/\.([a-z0-9_-]+)/i).exec(select);
	var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
	var classReg = classname ? new RegExp('\\b' + classname[1] + '\\b') : false;
	for(var i=0; i<elements.length; i++)
	{
		for(var j = 0, result = tagName ? ( elements[i].getElementsByTagName(tagName) || (elements[i].all && elements[i].all.tags(tagName)) ) : ( elements[i].getElementsByTagName("*") || elements[i].all ); j < result.length; j++)
		{
			var node = result[j];
			if(classReg && !classReg.test(node.className)) continue;
			nodes[nodes.length] = node;
		}
	}
	return nodes;
};
$$.filterByAttr = function(er, elements)
{
	var tagName = er[1], noAttr = er[2], attrName = er[3], attrOperator = er[4], attrValue = er[5];
	if(attrName.toString().toLowerCase() == "class" && Browser.isIE()) attrName = "className";
	var nodes = $$.getSelectedNodes(tagName, elements);
	var checkFunctions = {
		'=': function(e) { return (new String(e.getAttribute(attrName)).trim() == attrValue); },
		'!': function(e) { return !(new String(e.getAttribute(attrName)).trim() == attrValue); },
		'~': function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); },
		'|': function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); },
		'^': function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); },
		'$': function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); },
		'*': function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); },
		'default': function(e) { return e.getAttribute(attrName); }
	};
	for(var i=0, k=0, nnodes=[]; i<nodes.length; i++)
	{
		var f = typeof (f=checkFunctions[attrOperator]) != "undefined" ? f : checkFunctions['default'];
		if((r=f(nodes[i])) && noAttr != "!" && noAttr != "-")
		{
			nnodes.push(nodes[i]);
		}
		else if(r && noAttr == "-" && ((k++) % 2 == 1))
		{
			nnodes.push(nodes[i]);
		}
		else if(!r && noAttr == "!")
		{
			nnodes.push(nodes[i]);
		}
	}
	return nnodes;
};

function $t(t, p)
{
	return extendObject.elements($$(t, p), $.extendsDOM);
}

function $c(c, p)
{
	return extendObject.elements($$("." + c, p), $.extendsDOM);
}

function $tc(t, c, p)
{
	return extendObject.elements($$([t, c].join("."), p), $.extendsDOM);
}

function $e(el, t)
{
	if(!document.createElement) return false;
	var nEl = document.createElement(el.toString());
	if(typeof t == "object" && !t.nodeType)
	{
		for(var a in t)
		{
			if(a == "text")
			{
				nEl.appendChild(document.createTextNode(t[a]));
			}
			else if(a == "name")
			{
				if(Browser.isIE()) nEl = document.createElement('<' + t + ' name="' + t[a] + '">');
				nEl.setAttribute("name", t[a]);
			}
			else
			{
				nEl[(a == "class" ? "className" : a)] = t[a];
			}
		}
	}
	else if(typeof t == "string")
	{
		nEl.appendChild(document.createTextNode(t));
	}
	else if(typeof t == "undefined"){}
	else
	{
		nEl.appendChild(t);
	}
	return extendObject(nEl, $.extendsDOM);
}

