var global = new Object();
global = {
	/**Adiciona ../ até alcançar a raiz do site. Útil para se construir caminho relativos a partir da raiz*/
 	RelativeRoot: function(){
		var strHref = window.location.pathname;
		var bar = 0;
		var path = '';
		for(n=0;n!=strHref.length;n++){
			if (strHref.charAt(n)=='/'){
				bar++;
			}
		}

		if( bar < 2 ){
			return path;
		}

		for(n=1;n!=bar;n++){
			path = '../' + path;
		}

		return path;
	},
	isSubDomain: function(){
		var strf = window.location.hostname;
		var p = strf.indexOf('.');
		var sub = strf.substring(0,p);
		var is = (sub!="www" && sub!="gamevicio" ? true : false);
		return is;
	},
	form: {
		CreateQuery: function(formId){
	   		var elements = formId.elements ? formId.elements : document.forms[formId].elements;
	        var pairs = new Array();
		    for (var i = 0; i < elements.length; i++) {
		        if ((name = elements[i].name) && (value = elements[i].value))
		            pairs.push(name + "=" + encodeURIComponent(value));
		    }
		    return pairs.join("&");
		}
	},
	cookie : {
		Read: function(name){
			var cookieValue = "";
			var search = name + "=";
			if(document.cookie.length > 0) {
		    		offset = document.cookie.indexOf(search);
		   		 if (offset != -1) {
					offset += search.length;
		      			end = document.cookie.indexOf(";", offset);
		      			if (end == -1) end = document.cookie.length;
		      			cookieValue = unescape(document.cookie.substring(offset, end))
		    		}
		 	}
			return cookieValue;
		},
		Write: function (name, value, hours, path, domain, secure){
			var cookie = "";
			cookie+= name + "=" + escape(value);
			if(hours != null) {
				expire = new Date((new Date()).getTime() + hours * 3600000);
				expire = "; expires=" + expire.toGMTString();
			}else{
				expire = "";
			}
			cookie+= expire;
			cookie+= ((path) ? "; path=" + path : "");
			cookie+= ((domain) ? "; domain=" + domain : "");
		      cookie+= ((secure) ? "; secure" : "");
			document.cookie = cookie;
		}
	},
	div: {
		Write: function(divId,content){
			if (document.getElementById(divId)){
				document.getElementById(divId).innerHTML = content;
			}
		},
		WriteAdd: function(divId,content){
			document.getElementById(divId).innerHTML+= content;
		},
		Shrink: function(divId,mode){
			switch (mode){
				case 0:
					s = document.getElementById(divId).style.display == "none" ? "" : "none";
					break;
				case 2:
					s = "none";
					break;
				case 1:
					s = "";
					break;
			}
			document.getElementById(divId).style.display = s;
		},
		Read: function(divId){
			if (document.getElementById(divId)){
				return document.getElementById(divId).innerHTML;
			}else{
				return "";
			}
		}
	},
	utf8: {
		encode : function (string) {
	        string = string.replace(/\r\n/g,"\n");
	        var utftext = "";
	        for (var n = 0; n < string.length; n++) {
	            var c = string.charCodeAt(n);
	            if (c < 128) {
	                utftext += String.fromCharCode(c);
	            }
	            else if((c > 127) && (c < 2048)) {
	                utftext += String.fromCharCode((c >> 6) | 192);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }
	            else {
	                utftext += String.fromCharCode((c >> 12) | 224);
	                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }
	        }
	        return utftext;
    	},
	    decode : function (utftext) {
	        var string = "";
	        var i = 0;
	        var c = c1 = c2 = 0;
	        while ( i < utftext.length ) {
	            c = utftext.charCodeAt(i);
	            if (c < 128) {
	                string += String.fromCharCode(c);
	                i++;
	            }
	            else if((c > 191) && (c < 224)) {
	                c2 = utftext.charCodeAt(i+1);
	                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	                i += 2;
	            }
	            else {
	                c2 = utftext.charCodeAt(i+1);
	                c3 = utftext.charCodeAt(i+2);
	                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	                i += 3;
	            }
	        }
	        return string;
	    }
	},
	getUrlVars: function (){
		var vars = [], hash,s;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
		var anchor = hashes.indexOf('#');
		if (anchor>-1){
			hashes = hashes.slice(0,anchor);
		}
		hashes = hashes.split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		var hashes2 = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
		for(var i = 0; i < hashes2.length; i++){
			hash = hashes2[i].split('=');
			vars.push(hash[0]);
			vars['#'+hash[0]] = hash[1];
		}
		return vars;
	},
	evalScripts: function(s){
		var p = b = e = c = g = 0;
		var sBegin = '<script';
		var sEnd = '</script>';
		while((b=s.indexOf(sBegin,p))!=-1){
			e = s.indexOf(sEnd,p);
			if (e==-1){
				break;
			}
			g = s.indexOf('>',b);
			//c = s.substr(b+sBegin.length,e-(b+sBegin.length));
			c = s.substr(g+1,e-(g+1));
			p = e + sEnd.length;
			eval(c);
		}
	},
	event: {
		addLoad: function(func){
			var oldonload = window.onload;
			if (typeof window.onload != 'function'){
		    	window.onload = func;
			} else {
				window.onload = function(){
				oldonload();
				func();
				}
			}
		},
		addScroll: function(func){
			var oldonload = window.onscroll;
			if (typeof window.onscroll != 'function'){
		    	window.onscroll = func;
			} else {
				window.onscroll = function(){
				oldonload();
				func();
				}
			}
		}
	},
	XMLParser: function(stringXML){
		if (window.DOMParser){
		  	parser=new DOMParser();
		  	xmlDoc=parser.parseFromString(stringXML,"text/xml");
		}else{
			// Internet Explorer
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  xmlDoc.async="false";
		  xmlDoc.loadXML(stringXML);
		}
		return xmlDoc.documentElement;
	},
	slashes: {
		add: function(str) {
			str=str.replace(/\\/g,'\\\\');
			str=str.replace(/\'/g,'\\\'');
			str=str.replace(/\"/g,'\\"');
			str=str.replace(/\0/g,'\\0');
			return str;
		},
		strip: function(str) {
			str=str.replace(/\\'/g,'\'');
			str=str.replace(/\\"/g,'"');
			str=str.replace(/\\0/g,'\0');
			str=str.replace(/\\\\/g,'\\');
			return str;
		}
	}
}

gXMLQuery = function(xml){
	var gQuery = new Object();
	gQuery = {
		xml: null,
		setXML: function(xml){
			gQuery.xml = xml;
		},
		getXML: function(){
			return gQuery.xml;
		},
		getValue: function(s){
			return gQuery.Do(s);
		},
		getLength: function(s){
			for(var n=0;n!=500;n++){
				try{
					gQuery.Do(s+'['+n+']');
				}catch(e){
					return (n);
				}
			}
			return n;
		},
		exists: function(s){
			try {
				gQuery.getValue(s);
			}catch(e){
				return false;
			}
			return true;
		},
		Do: function (s){
			var a = s.split('->');
			var o = gQuery.getXML();
			//alert(c[0].tagName);
			for(var n=0;n!=a.length;n++){
				//procurar chave de array
				var si = a[n];
				var p = 0;
				if (si.indexOf("[")!=-1){
					var b = si.indexOf("[");
					var e = si.indexOf("]");
					p = si.substring(b+1,e);
					si = si.substring(0,b);
				}
				//atributo
				var isA = si.indexOf("attributes()")!=-1;
				if (isA){
					break;
				}
				var d = o.childNodes;
				var y = 0;
				for(var x=0;x!=d.length;x++){
					if (d[x].nodeType==1){
						if (d[x].nodeName==si){
							if (y==p){
								break;
							}
							y++;
						}
					}
				}

				try {
					o = o.childNodes[x];
					//teste de validacao, gerará um exception se a tag chamada nao existe
					f = o.getElementsByTagName(si)[0];
				}catch(e){
					return "";
					//alert('Node '+si+' do not exists. Called in '+s);
					//throw('Node '+si+' do not exists. Called in '+s);
				}
			}
			if (isA){
				o = o.getAttribute(a[n+1]);
			}else{
				try {
					//cheat ff limit 4 kb
				if (typeof o.normalize == 'function') o.normalize();
					o = o.firstChild.nodeValue;
				}catch(e){
					return "";
				}
			}
			return o;
		}
		/*Do: function (s){
			var a = s.split('->');
			var o = gQuery.getXML();

			for(var n=0;n!=a.length;n++){
				//procurar chave de array
				var si = a[n];
				var p = 0;
				if (si.indexOf("[")!=-1){
					var b = si.indexOf("[");
					var e = si.indexOf("]");
					p = si.substring(b+1,e);
					si = si.substring(0,b);
				}
				//atributo
				var isA = si.indexOf("attributes()")!=-1;
				if (isA){
					break;
				}
				try {
					o = o.getElementsByTagName(si)[p];
					//teste de validacao, gerará um exception se a tag chamada nao existe
					f = o.getElementsByTagName(si)[0];
				}catch(e){
					//alert('Node '+si+' do not exists. Called in '+s);
					throw('Node '+si+' do not exists. Called in '+s);
				}
			}
			if (isA){
				o = o.getAttribute(a[n+1]);
			}else{
				try {
					//cheat ff limit 4 kb
				if (typeof o.normalize == 'function') o.normalize();
					o = o.firstChild.nodeValue;
				}catch(e){
					return "";
				}
			}
			return o;
		}*/
	}
	gQuery.setXML(xml);
	return gQuery;
}

function gAjax(method,url){
	var ajax = new Object();
	ajax = {
		object: null,
		events: new Array(),
		vars: '',
		method:null,
		url:null,
		IE_FIX: true,
		headerParam: new Array(),
		headerContent: new Array(),
		makeObject: function(method,url){
			ajax.object = ajax._makeObject();
			ajax.setMethod(method);
			if (ajax.IE_FIX){
				url = ajax.fixIEUrl(url);
			}
			ajax.setUrl(url);
			ajax.object.onreadystatechange = ajax.parseEvent;
		},
		open: function(){
			ajax.object.open(ajax.getMethod(), ajax.getUrl());
		},
		setMethod: function(s){
			ajax.method = s;
		},
		getMethod: function(){
			return ajax.method;
		},
		setUrl: function(s){
			ajax.url = s;
		},
		getUrl: function(){
			return ajax.url;
		},
		fixIEUrl: function(url){
			var s = 'r=' + Math.random();
			url+= url.indexOf('?')==-1 ? '?' : '&';
			url+=s;
			return url;
		},
		_makeObject: function(){
			var x;
			var browser = navigator.appName;
			if(browser == "Microsoft Internet Explorer"){
				x = new ActiveXObject("Microsoft.XMLHTTP");
			}else{
				x = new XMLHttpRequest();
			}
			return x;
		},
		setRequestHeader: function(param,content){
			ajax.headerParam.push(param);
			ajax.headerContent.push(content);
			//ajax.object.setRequestHeader(param,content);
		},
		headers: function(){
			for(var n=0;n!=ajax.headerParam.length;n++){
				ajax.object.setRequestHeader(ajax.headerParam[n],ajax.headerContent[n]);
			}
		},
		setVars: function(s){
			ajax.vars = s;
		},
		getVars: function(){
			return ajax.vars;
		},
		send: function(){
			ajax.open();
			ajax.headers();
			ajax.object.send(ajax.getVars());
		},
		addEvent: function(state,script){
			ajax.events[state] = script;
		},
		removeEvent: function(state){
			ajax.events[state] = null;
		},
		parseEvent: function(){
			var s = ajax.object.readyState;
			if (ajax.events[s]){
				eval(ajax.events[s]);
			}
		},
		getResponseText: function(){
			return ajax.object.responseText;
		},
		isResponseXML: function(){
			try {
				var r = ajax.object.responseXML.documentElement;
			}catch (e){
				return false;
			}
			return true;
		},
		getQueryXML: function(){
			var o1 = new gXMLQuery(ajax.getResponseXML());
			return o1;
		},
		getResponseXML: function(){
			return ajax.object.responseXML.documentElement;
		},
		getValueXML: function(query){
			var o1 = new gXMLQuery(ajax.getResponseXML());
			return o1.getValue(query);
		},
		getLengthXML: function(query){
			var o1 = new gXMLQuery(ajax.getResponseXML());
			return o1.getLength(query);
		},
		existsXML: function(query){
			var o1 = new gXMLQuery(ajax.getResponseXML());
			return o1.exists(query);
		}
	}
	ajax.makeObject(method,url);
	return ajax;
}

function gDate(tz,div,mode){
	var g1 = new Object();
	g1 = {
		tz: null,
		setTz: function(s){
			g1.tz=s;
		},
		getTz: function(){
			return g1.tz;
		},
		Start: function(tz,div,mode){
			g1.setTz(tz);
			if (div){
				g1.Show(div,mode);
			}
		},
		string : {
			Month: function(i,short,eng){
				var pt = new Array('Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro');
				var en = new Array('January','February','March','April','May','Jun','July','August','September','October','November','December');
				var s = eng ? en[i] : pt[i];
				if (s){
					s = (short ? s.substring(0,3) : s);
				}else{
					s = '';
				}
				return s;
			},
			Year: function(i,short){
				var s = new String(i);
				s = short ? s.substring(2,4) : s;
				return s;
			}
		},
		Zero: function(s){
			if (parseInt(s)<10){
				s = '0' + s;
			}
			return s;
		},
		getText: function(mode){
			var o = new Date(g1.getTz());
			var c = new Date();
			var d = Math.round(c.getTime()/1000) - Math.round(o.getTime()/1000);
			var s = "";
			//minutos
			if (d<(60*60)){
				var s1 = "";
				if (Math.round(d/60)<2){
					s1 = Math.round(d/60) + " minuto";
				}else{
					s1 = Math.round(d/60) + " minutos";
				}
				s = this.Zero(o.getHours()) + ':' + this.Zero(o.getMinutes()) + ' (' + s1 + ' atrás)';
			}else{
				//horas
				if (d<(60*60*24)){
					if (Math.round(d/(60*60))<2){
						s1 = Math.round(d/(60*60)) + " hora";
					}else{
						s1 = Math.round(d/(60*60)) + " horas";
					}

					s = ( o.getDate()!=c.getDate() ? this.Zero(o.getDate()) + ' ' + g1.string.Month(o.getMonth(),true)+' ' : '' ) + this.Zero(o.getHours()) + ':' + this.Zero(o.getMinutes()) + ' ('+s1+' atrás)';
				}else{
				//dias
					if (d<(60*60*24*7)){
						switch (Math.round(d/(60*60*24))){
							case 1:
								s1 = "Ontem";
								break;
							case 2:
								s1 = "Anteontem";
								break;
							default:
								s1 = Math.round(d/(60*60*24)) + " dias atrás";
								break;
						}
						s = this.Zero(o.getDate()) + ' ' + g1.string.Month(o.getMonth(),true) + ' ' + this.Zero(o.getHours()) + ':' + this.Zero(o.getMinutes()) + ' ('+s1+')';
					}else{
					//semanas
						if (d<(60*60*24*7*4)){
							if (Math.round(d/(60*60*24*7))<2){
								s1 = Math.round(d/(60*60*24*7)) + " semana atrás";
							}else{
								s1 = Math.round(d/(60*60*24*7)) + " semanas atrás";
							}

							s = this.Zero(o.getDate()) + ' ' + g1.string.Month(o.getMonth(),true) + ' ' + ' ('+s1+')';
						}else{
							//meses
							if (d<(60*60*24*7*4*12)){
								if (Math.round(d/(60*60*24*7*4))<2){
									s1 = Math.round(d/(60*60*24*7*4)) + " mês atrás";
								}else{
									s1 = Math.round(d/(60*60*24*7*4)) + " meses atrás";
								}

								s = this.Zero(o.getDate()) + ' ' + g1.string.Month(o.getMonth(),true)+' '+(o.getFullYear()!=c.getFullYear() ? g1.string.Year(o.getFullYear(),false)+' ' : '' ) + '('+s1+')';
							}else{
								//anos
								if (d>(60*60*24*7*4*12)){
									if (Math.round(d/(60*60*24*7*4))<24){
										s1 = Math.floor(d/(60*60*24*7*4*12)) + " ano atrás";
									}else{
										s1 = Math.floor(d/(60*60*24*7*4*12)) + " anos atrás";
									}

									s = this.Zero(o.getDate()) + ' ' + g1.string.Month(o.getMonth(),true) + ' ' + o.getFullYear() + ' ('+s1+')';
							}	}
						}
					}
				}
			}
			switch (mode){
				case "shortLeft":
					var p = s.indexOf(' (');
					s = s.substring(0,p);
					break;
				case "shortRight":
					var p = s.indexOf('(');
					var e = s.indexOf(')');
					s = s.substring(p+1,e);
					break;
				case "shortRightNoWord":
					var p = s.indexOf('(');
					var e = s.indexOf(' atrás');
					s = s.substring(p+1,e);
					break;
			}
			return s;
		},
		Show: function(div,mode){
			var s = this.getText(mode);
			WriteAddDiv(div,s);
		}
	}
	g1.Start(tz,div,mode);
	return g1;
}

function gImage(url){
	var im = new Object();
	im = {
		obj: null,
		url: null,
		events: new Array(),
		setUrl: function(s){
			im.url = s;
		},
		getUrl: function(){
			return im.url;
		},
		load: function(){
			im.obj = new Image();
			im.obj.src = im.getUrl();
			im.enableEvents();
		},
		isLodaded: function(){
			return im.obj.complete;
		},
		enableEvents: function(){
			im.obj.onload = im.onLoad;
			im.obj.onerror = im.onError;
		},
		getHeight: function(){
			return im.obj.height;
		},
		getWidth: function(){
			return im.obj.width;
		},
		getOrientation: function(){
			if (!(im.getWidth()>1)){
				throw('Largura inválida');
			}
			if (!(im.getHeight()>1)){
				throw('Altura inváliada');
			}
			if (im.getHeight()>im.getWidth()){
				return "vertical";
			}
			if (im.getHeight()<im.getWidth()){
				return "horizontal";
			}
			return "square";
		},
		needResizeDimension: function(maxWidth,maxHeight){
			if (maxWidth<1 && maxHeight<1){
				throw('Pelo menos um parâmetro precisa ser preenchido na função');
			}

			if (maxWidth>1){
				if (im.getWidth()>maxWidth){
					return true;
				}
			}
			if (maxHeight>1){
				if (im.getHeight()>maxHeight){
					return true;
				}
			}
			return false;
		},
		getResizedDimension: function(maxWidth,maxHeight,percent){
			if (maxWidth<1 && maxHeight<1 && percent<0.1){
				throw('Pelo menos um parâmetro precisa ser preenchido na função');
			}
			var factor;
			//pega a orientação, além de garantir que as dimensões da mídia são válidas
			var orientation = im.getOrientation();
			if (percent!=null){
				factor = percent;
			}else{
				switch (orientation) {
					case "horizontal":
						if (!(maxWidth>0)){
							throw("A imagem é horizontal e necessita do parâmetro maxWidth");
						}
						factor = (im.getWidth()>maxWidth ? maxWidth/im.getWidth() : 1 );

						if (maxHeight>0){
							if (Math.round(im.getHeight()*factor)>maxHeight){
								factor = (im.getHeight()>maxHeight ? maxHeight/im.getHeight() : 1 );
							}
						}
						break;
					case "vertical":
						if (!(maxHeight>0)){
							throw("A imagem é vertical e necessita do parâmetro maxHeight");
						}
						factor = (im.getHeight()>maxHeight ? maxHeight/im.getHeight() : 1 );
						if (maxWidth>0){
							if (Math.round(im.getWidth()*factor)>maxWidth){
								factor = (im.getWidth()>maxWidth ? maxWidth/im.getWidth() : 1 );
							}
						}
						break;
					case "square":
						if (!(maxWidth>0) && !(maxHeight>0)){
							throw("A imagem é quadrada e necessita do parâmetro maxHeight e/ou maxWidth");
						}
						//pega o menor tamanho
						if (maxHeight<maxWidth){
							factor = (im.getHeight()>maxHeight ? maxHeight/im.getHeight() : 1 );
						}else{
							factor = (im.getWidth()>maxWidth ? maxWidth/im.getWidth() : 1 );
						}
						break;
				}
			}
			var newWidth = Math.round(im.getWidth() * factor);
			var newHeight = Math.round(im.getHeight() * factor);
			var a = new Array(2);
			a["width"] = newWidth;
			a["height"] = newHeight;
			return a;
		},
		getHTMLBasic: function(width,height){
			var s = '<img src="' + im.getUrl() + '" width="' + width + '" height="' +height+'" alt="imagem" />';
			return s;
		},
		getHTMLAdvanced:function(maxWidth,maxHeight){
			var s;

			if (im.needResizeDimension()){
				var a = im.getResizedDimension(maxWidth,maxHeight);
				s = '<a href="' + im.getUrl() + '" title="Clique para ampliar esta imagem">'+im.getHTMLBasic(a["width"],a["height"])+'</a>';
			}else{
				s = im.getHTMLBasic(im.getWidth(),im.getHeight());
			}
			return s;
		},
		write: function(maxWidth,maxHeight,url,done){
			var s;
			if (done == true){
				s = im.getHTMLAdvanced(maxWidth,maxHeight,url);
			}else{
				s = '<a href="'+im.getUrl()+'">'+im.getUrl()+'</a>' + im.getHeight();
			}
			document.write(s);
		},
		GVCode:function(maxWidth,maxHeight){
			im.onLoad = im.write(maxWidth,maxHeight,true);
			im.onError('document.write(<a href="'+im.getUrl()+'">'+im.getUrl()+'</a>');
			im.load();
		},
		onLoad: function(s){
			eval(s);
		},
		onError: function(s){
			eval(s);
		}
	}
	im.setUrl(url);
	return im;
}