/*
 * util.js - JavaScript Library
 * Copyright (c) 2006-2007 Lucas Ferreira (www.lucasferreira.com)
 *
 * Version: 1.5.1
 */

/* 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();

/* For FireBug */
if(!console)
	var console = { log: function(a){ alert(a); } };
	
/* Delegate class */
function Delegate(obj, func, args)
{
	var f = function()
	{
		var target = arguments.callee.target, func = arguments.callee.func, 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;
}
var _d = Delegate.create = 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) __extends__(document.body, $.extendsDOM);
}
var _c = BodyLoad.onContent;
BodyLoad.init();

/* Prototypes Utils */
function extendObject(obj, ext, over)
{
	for(var p in ext)
		if(!obj[p] || 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;
};
__extends__ = extendObject;

__extends__(String.prototype, {
	
	trim: function() { return this.toString().replace(/^\s*|\s*$/g, ""); },
	
	replaceAll: function(f, r){ return s.split(f).join(r); },
	
	toNumber: function()
	{
		var s = this.toString().replaceAll(".", "").replace(",", ".").replaceAll(",", "");
		return isNaN(new Number(s)) ? 0 : new Number(s);
	},
	
	toObject: function(){ return eval('(' + this.toString() + ')');	}
	
});

if(!Array.prototype.push)
	Array.prototype.push = function(a){ this[this.length] = a; };
	
__extends__(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])(); },
	each: function(f)
	{
		for(var i=0, a = (this || []); i<a.length; i++) Delegate.create(a, f, [i])(); return a;
	},
	run: function(f)
	{
		for(var i=0, a = (this || []); i<a.length; i++) Delegate.create(a[i], f, [i])(); return a;
	},
	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||[]), p=-1; i<a.length && p<0; (a[i]==e?(p=i):1) && i++); return p;
	},
	remove: function(i)
	{
		this.splice(i, 1);
		return this;
	},
	merge: function(a)
	{
		return this.concat(a);
	},
	uniqueValues: function()
	{
		for(var i=0, a=[], b=(this||[]); i < b.length; i++) if(a.find(b[i]) < 0) a.push(b[i]); return a;
	}

});

/* 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);
		
		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);
	},
	
	unloadEvents: function()
	{
		var e = Event.aEvts;
		for(var i=0; i<e.length; i++)
		{
			Event.remove.apply(this, e[i]);
			e[i][0] = null;
		}
	},
	
	cancel: function(evt)
	{
		try {
			evt.preventDefault();
		} catch(e) {
			window.event.returnValue=false;
		}
	}
	
};

/* MISCELANIOUS FUNCTIONS */
function initValue(o)
{
	var o = $target(o);
	if(o.initVal == undefined)
	{
		o.initVal = o.value;
		Event.add(o, "blur", function(e){
			var o = $target(e);
			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){ return ((typeof o == "undefined") || (o==null) || (o.length<1) || false); }

/* AJAX FUNCTIONS */
function Ajax()
{
	if(Ajax.arguments.length > 0)
		return Ajax.getInstace.apply(Ajax, Ajax.arguments);
	
	this.xhr = Ajax.getTransport();
	this.ajax_sign = "ajax=1";
	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"), this.p_url(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.p_url = function(url)
	{
		return [url, this.ajax_sign].join((url.indexOf("?") < 0) ? "?" : "&");
	};
	
	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)
{
	$t("LI", (typeof menu == "string") ? $(menu) : 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 */
var $target = getTargetByEvent = function(e){ return (e=(e||window.event)).target ? e.target : e.srcElement; };

function $()
{
	for(var i=0, merged=false, elements=[], args=(typeof $.arguments[0] == "array" ? $.arguments[0] : $.arguments); i < args.length; i++)
	{
		var nEL = (document.getElementById(args[i]) || (document.all && (nEL=document.all[args[i]])) || document[args[i]] ) || $$(args[i]);
		(!nEL.nodeName && nEL.length && nEL.length > 0) ? (elements = elements.merge(nEL.length > 1 ? nEL : nEL[0])) && (merged=true) : !empty(nEL) ? elements.push(nEL) : 1;
	}
	__extends__.elements((elements=elements.uniqueValues()), $.extendsDOM);
	return !merged ? (elements.length==1 ? elements.first() : elements) : elements;
}
$.extendsDOM = {
	addEvent: function(evt, f, escope)
	{
		Event.add(this, evt, Delegate.create((escope || this), f));
		return this;
	},
	remEvent: function(evt, f, escope)
	{
		Event.remove(this, evt, Delegate.create((escope || this), f));
		return this;
	},
	cancelEvent: function(evt)
	{
		Event.cancel(evt);
		return this;
	},
	e: function(evt, f, escope)
	{
		return this.addEvent(evt, f, escope);
	},
	css: function(css)
	{
		extendObject(this.style, css, true);
		return this;
	},
	addClass: function(c)
	{
		if(this.className.split(" ").find(c) < 0)
		{
			this.className += " " + c;
		}
		return this;
	},
	remClass: function(c)
	{
		var ps = this.className.split(" "), p;
		if((p=ps.find(c)) > -1)
		{
			this.className = ps.remove(p).join(" ");
		}
		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;
	},
	setLeft: function(v)
	{
		this.style.left = v + "px";
		return this;		
	},
	setTop: function(v)
	{
		this.style.top = v + "px";
		return this;		
	},
	getLeft: function()
	{
		return absLeft(this);
	},
	getTop: function()
	{
		return absTop(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);
	},
	parent: function()
	{
		return __extends__(this.parentNode, $.extendsDOM);
	},
	next: function()
	{
		var f = this.nextSibling;
		do
		{
			if(f != this && f.nodeType == 1)
			{
				return __extends__(f, $.extendsDOM);
			}
		}
		while(f = f.nextSibling);
	},
	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);
	},
	magic: function(__node__)
	{
		var o = ( __node__ || this ), f = o.firstChild;
		do
		{
			if(f.nodeType == 1)
			{
				__extends__(f, $.extendsDOM);
				if(f.childNodes && f.childNodes.length > 0) $.extendsDOM.magic(f);
			}
		}
		while(f = f.nextSibling);
		
		return o;
	}
};

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 == "-"||noAttr == "odd:") && ((k++) % 2 == 1))
		{
			nnodes.push(nodes[i]);
		}
		else if(!r && noAttr == "!")
		{
			nnodes.push(nodes[i]);
		}
	}
	return nnodes;
};

function $t(t, p){ return __extends__.elements($$(t, p), $.extendsDOM); }

function $e(el, t)
{
	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('<' + el + ' 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 __extends__(nEl, $.extendsDOM);
}

function absLeft(obj)
{
	var obj = typeof obj == "string" ? $(obj) : (obj || this);
	
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) curleft += obj.x;
	
	return curleft;
}

function absTop(obj)
{
	var obj = typeof obj == "string" ? $(obj) : (obj || this);

	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) curtop += obj.y;
	
	return curtop;
}
