////////////////////////////////////////////////////////////////////////////////
// Resoluçao SEPLAG 40/2008 / Implementações de acessibilidade                //
// Isabela Gonzaga Glória                                                     //
// Breno Damas M. Ribeiro - http://ribeirobreno.com.br                        //
// Desenvolvimento Web - PRODEMGE                                             //
// Última versão em: 18/11/2011                                               //
// Charset: ISO-8859-1                                                        //
////////////////////////////////////////////////////////////////////////////////

(function(w, d){
	////////////////////////////////////////////////////////////////////////////////
	// Utilidades!                                                                //
	////////////////////////////////////////////////////////////////////////////////
	var temCookie=false;
	if(d.cookie) {
		d.cookie='cookieteste=true; path=/';
		if(d.cookie.indexOf('cookieteste')>=0) {
			temCookie=true;
			var ag=new Date;
			ag.setTime(ag.getTime()-24*60*60*1000);
			d.cookie = 'cookieteste=0; expires='+ag.toUTCString()+'; path=/';
		}
		if(!temCookie) {
			alert('Seu browser não aceita cookies...\nPara ativar no Firefox:\n'+
				' - Vá em Ferramentas > Opções > Privacidade (cadeado) > Cookies\n'+
				' - Certifique-se de que este site tenha permissão para gerar cookies');
		}
	}
	function leCookie(sn) {
		if(!temCookie) {
			return null;
		}
		var dc=d.cookie;
		var prefix=sn+"=";
		var begin=dc.indexOf("; "+prefix);
		if (begin==-1) {
			begin=dc.indexOf(prefix);
			if (begin!=0) return null;
		} else begin+=2;
		var end=dc.indexOf(";",begin);
		if (end==-1) end=dc.length;		
		return unescape(dc.substring(begin+prefix.length,end));		
		return 9;
	
	}

	////////////////////////////////////////////////////////////////////////////////
	// Alteraçao de Tamanho de Fontes                                             //
	////////////////////////////////////////////////////////////////////////////////
	var Fonte = {
		padrao:12,
		atual:12,
		max:22,
		min:9,
		varia:2,
		niveis:3,
		unidade:"px",
		vidaCookie:259200000000,
		ref:false,
		Textos:{
			maior:"Aumentar Fonte",
			menor:"Diminuir Fonte",
			medio:"Fonte Normal"
		},
		inicia:function () {
		//elemento de referencia
			Fonte.ref = d.getElementById("conteudo");
			if(!Fonte.ref) Fonte.ref = d.body;
		//fonte no elemento referencia
			var padrao = Fonte.calcPadrao();
			Fonte.padrao = padrao;
		//variacao aceitavel
			var diff = Fonte.niveis * Fonte.varia;
		//  maximo
			Fonte.max = diff + padrao;
		//  minimo
			var min = padrao - diff;
			if(min >= Fonte.min) 
				Fonte.min = min;

		//detecta fonte atual
			var cookie = leCookie("fonte");
			Fonte.atual = cookie ? parseFloat (cookie, 10) : Fonte.padrao;

		//ajusta o documento
			Fonte.ajustar();

		//cria opções
			var b = d.getElementById("barraAcesso");
			var cBt = d.createElement('span');
			var bt = d.createElement('a');
			bt.innerHTML=Fonte.Textos.maior;
			bt.title=Fonte.Textos.maior;
			bt.onclick = function(){ Fonte.aumentar(); return false; };
			bt.className = "aumentar";
			bt.href = "aumentar";
			bt.accessKey = "2";
			bt.tabIndex = "4";
			cBt.appendChild(bt);

			bt = d.createElement('a');
			bt.innerHTML=Fonte.Textos.menor;
			bt.title=Fonte.Textos.menor;
			bt.onclick = function(){ Fonte.diminuir(); return false; };
			bt.className = "diminuir";
			bt.href = "diminuir";
			bt.accessKey = "3";
			bt.tabIndex = "5";
			cBt.appendChild(bt);

			bt = d.createElement('a');
			bt.innerHTML=Fonte.Textos.medio;
			bt.title=Fonte.Textos.medio;
			bt.onclick = function(){ Fonte.volta(); return false; };
			bt.className = "padrao";
			bt.href = "padrao";
			bt.accessKey = "\'";
			cBt.appendChild(bt);
			cBt.className = "fontes";
			b.insertBefore(cBt, d.getElementById("fontes"));
		},
		aumentar:function () {
			if(Fonte.atual < Fonte.max){
				Fonte.atual += Fonte.varia;
				Fonte.ajustar();
			}
		},
		diminuir:function () {
			if(Fonte.atual > Fonte.min){
				Fonte.atual -= Fonte.varia;
				Fonte.ajustar();
			}
		},
		ajustar:function () {
		//cookie
			var dexp = new Date();
			dexp.setTime(dexp.getTime()+Fonte.vidaCookie);
			var sCookie="fonte="+Fonte.atual+"; expires="+dexp.toGMTString()+"; path=/";
			d.cookie=sCookie;
		//dom
			Fonte.ref.style.fontSize = Fonte.atual+Fonte.unidade;
		},
		volta:function () {
			Fonte.atual = Fonte.padrao;
			Fonte.ajustar();
		},
		calcPadrao:function () {
			if (!d.getElementById) return false;
			var x = Fonte.ref;
		//DOM
			if (w.getComputedStyle) var y = d.defaultView.getComputedStyle(x,null).getPropertyValue('font-size');
		//IE
			else if (x.currentStyle) var y = x.currentStyle.fontSize;
			var u = y.substring(y.length-2,y.length);
			var v = parseFloat(y, 10);
			//alert('u:'+u+'\nf.u:'+Fonte.unidade);
			if(u != Fonte.unidade) {
				//alert(parseFloat(y, 10)+"|"+u+"|"+y);
				//corrigir: unidade sempre será "em" neste ponto
				//Fonte.atual /= Fonte.padrao;
				//Fonte.max /= Fonte.padrao;
				//Fonte.min /= Fonte.padrao;
				//Fonte.varia /= Fonte.padrao;
				//alert(v+'\n'+Fonte.padrao+'\n'+(Math.round(100*Fonte.padrao*v)/100));
				v = Math.round(100*Fonte.padrao*v)/100;
				//alert('f.p:'+Fonte.padrao+'\nf.a:'+Fonte.atual+'\nf.m:'+Fonte.max+'\nf.n:'+Fonte.min+'\nf.v:'+Fonte.varia+'\nf.u:'+Fonte.unidade+'\nu:'+u);
				//Fonte.padrao = 1;
				//Fonte.unidade = u;
			}
			return v;
		},
		_PXEM:function (valor, origem, destino, base) {
		alert('alff\n'+valor+'\n'+origem+'\n'+destino+'\n'+base);
			if(origem!=destino) {
				if(origem == 'px') {
					valor *= base;
				} else {
					valor /= base;
				}
			}
			return valor;
		}
	};

	////////////////////////////////////////////////////////////////////////////////
	// Alteraçao de Folhas de Estilos                                             //
	// Baseado em: http://www.alistapart.com/stories/alternate/                   //
	////////////////////////////////////////////////////////////////////////////////
	Layout = {
		vidaCookie:259200000000,
		setAtiva: function (title) {
			var i, a, l, t, main;
			l = d.getElementsByTagName("link");
			for(i=0, t=l.length; i<t; ++i) {
				a = l[i];
				if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
					a.disabled = true;
					if(a.getAttribute("title") == title) a.disabled = false;
				}
			}
		},
		getAtiva: function () {
			var i, a, l, t;
			l = d.getElementsByTagName("link");
			for(i=0, t=l.length; i<t; ++i) {
				a = l[i];
				if(a.getAttribute("rel").indexOf("style") != -1
					&& a.getAttribute("title")
					&& !a.disabled) return a.getAttribute("title");
			}
			return null;
		},
		getPreferida: function () {
			var i, a, l, t;
			l = d.getElementsByTagName("link");
			for(i=0, t=l.length; i<t; ++i) {
				a = l[i];
				if(a.getAttribute("rel").indexOf("style") != -1
					&& a.getAttribute("rel").indexOf("alt") == -1
					&& a.getAttribute("title")
				) return a.getAttribute("title");
			}
			return null;
		},
		mudar: function (titulo) {
			Layout.setAtiva(titulo);

			var dexp = new Date();
			dexp.setTime(dexp.getTime()+Layout.vidaCookie);
			var sCookie="style="+titulo+"; expires="+dexp.toGMTString()+"; path=/";
			d.cookie=sCookie;

			return (Layout.getAtiva()==null);
		},
		circular: function () {
		// bool Layout::circular(HTMLLinkElement link, String titulo0, String titulo1, ...)
			var c = arguments.length;
			if(c<=1) {
				return false;
			} else {
				var v, a, i, l, p = -1;
				v = arguments;
				l = v[0];
				a = Layout.getAtiva();
				for(i=1; i<c && p<0; ++i) {
					if(a==v[i]) {
						p = i + 1;
					}
				}
				if(p>=c) p = 1;
				var n = p + 1;
				if(n>=c) n = 1;
				l.href = l.href.replace(/\?.*/i, '?'+v[n]);
				return Layout.mudar(v[p]);
			}
		},
		inicia: function () {
			var cookie = leCookie("style");
			var title = cookie ? cookie : Layout.getPreferida();
			Layout.setAtiva(title);
		}
	};

	////////////////////////////////////////////////////////////////////////////////
	// Eventos                                                                    //
	////////////////////////////////////////////////////////////////////////////////
	Eventos = {
		URLBase: '/',
		parar:function (e) {
			if(!e) e=w.event;
			if(!e) throw 'Evento inválido! Parando com um erro.';
			tecla=(e.keyCode)?e.keyCode:((e.which)?e.which:null);
			switch(tecla) {
			case 112: //F1
			case 113: //F2
			case 114: //F3
			case 115: //F4
			case 116: //F5
			case 117: //F6
			case 118: //F7
			case 119: //F8
			case 120: //F9
			case 121: //F10
			case 122: //F11
			case 123: //F12
			case 16: //Shift esq
			case 17: //Ctrl esq
			case 18: //Alt esq
			case 27: //ESC
			case 8: //BackSpace
			case 9: //Tab
				if(!e.preventDefault) {
					if(e.keyCode) e.keyCode=65;
					if(e.which) e.which=65;
				}
			default:
				break;
			};
			if(e.stopPropagation) e.stopPropagation();
			if(e.preventDefault) {
				e.preventDefault();
			} else {
				e.cancelBubble=true;
				e.returnValue=false;
			}
			return false;
		},
		ajustarTarget: function () {
		// Corrige links p/ abrir nova janela
			var ln = d.getElementsByTagName('a');
			for(var i = 0, t = ln.length; i<t; ++i) {
				if(ln[i].rel.toLowerCase()=='external') {
					ln[i].target = "_blank";
				}
			}
		// Corrige forms p/ abrir em outra janela
			ln = d.getElementsByTagName('form');
			var reC = /target([^\s"]+)/i;
			var a = [];
			for(var i = 0, t = ln.length; i<t; ++i) {
				a = reC.exec(ln[i].className);
				if(a && a.length>0) {
					ln[i].target = a[1];
				}
			}
		},
		aoCarregar: function (e) {
			Layout.inicia();
			Fonte.inicia();
			Eventos.ajustarTarget();
			Eventos.criaClicks();
		},
		aoTeclar: function (e) {
			if(!e) e=w.event;
			var tecla=(e.keyCode)?e.keyCode:((e.which)?e.which:null);
			if((tecla >= 48 && tecla<=57) || tecla==192){
				var elem = (e.target) ? e.target : e.srcElement;
				var invalidos = [
					"INPUT",
					"SELECT",
					"OPTION",
					"TEXTAREA"
				];
				var valido = true;
				for (var i = 0, t = invalidos.length; i < t && valido; ++i) {
					if(elem.tagName.toUpperCase() == invalidos[i]) 
						valido = false;
				}
				//alert(elem.tagName);
				if(valido) {
					switch(tecla) {
					case 192: //' + ctrl - Letra padrão
						if(e.ctrlKey)
							Fonte.volta();
						break;
					case 48: //0 - Menu
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.location.hash = "mainmenu";
						break;
					case 49: //1 - Conteudo
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.location.hash = "conteudo";
						break;
					case 50: //2 - Aumentar letra
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						Fonte.aumentar();
						break;
					case 51: //3 - Diminuir letra
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						Fonte.diminuir();
						break;
					case 52: //4 - Maior Contraste 
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						Layout.mudar('Contraste');
						break;
					case 53: //5 - Menor Contraste
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						Layout.mudar('Autor');
						break;
					case 54: //6 - Ajuda
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.location.href = Eventos.URLBase+"ajuda";
						break;
					case 55: //7 - Mapa do Site 
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.location.href = Eventos.URLBase+"mapa-do-site";
						break;
					case 56: //8 - Fale Conosco
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.location.href = Eventos.URLBase+"fale-conosco";
						break;
					case 57: //9 - Busca
						if(!(e.ctrlKey || e.shiftKey || e.altKey))
						w.setTimeout(function (){
							w.location.hash = "mod_search_searchword"; 
							var cb = d.getElementById("mod_search_searchword");
							cb.focus();
						}, 100);
						break;
					default:
					//alert(tecla);
						break;
					};
				}
			}
		},
		clkContraste: [
			function (e) {
				return Layout.circular(this, 'Autor','Contraste')?true:Eventos.parar(e);
			},
			function (e) {
				return Layout.mudar('Contraste')?true:Eventos.parar(e);
			},
			function (e) {
				return Layout.mudar('Autor')?true:Eventos.parar(e);
			}
		],
		// simula o funcionamento de: el.addEventListener(ev, f)
		// attachEvent em que o "this" funciona conforme deveria!
		eventoIE: function (el, ev, f) {
			el.attachEvent('on'+ev, function() { f.call(el, w.event); });
		},
		criaClicks: function () {
			var l = [
				d.getElementById('altContraste'),
				d.getElementById('contraste'),
				d.getElementById('autor')
				];
			if (w.addEventListener) {
				for(var i=0, t=l.length; i<t; ++i) {
					if(l[i]) l[i].addEventListener('click', Eventos.clkContraste[i], false);
				}
			} else if (w.attachEvent) {
				for(var i=0, t=l.length; i<t; ++i) {
					Eventos.eventoIE(l[i], 'click', Eventos.clkContraste[i]);
				}
			} else {
				for(var i=0, t=l.length; i<t; ++i) {
					if(l[i]) l[i].onclick=Eventos.clkContraste[i];
				}
			}
		},
		criaOuvintes: function () {
			if (w.addEvent) {//Mootools?
				w.addEvent('domready', Eventos.aoCarregar);
			} else if (w.addEventListener) {
				w.addEventListener('load', Eventos.aoCarregar, false); 
			} else if (w.attachEvent) {
				w.attachEvent('onload', Eventos.aoCarregar);
			} else {
				w.onload = Eventos.aoCarregar;
			}
			// !!! IE!
			if (w.addEventListener) {
				w.addEventListener('keyup', Eventos.aoTeclar, false); 
			} else if (d.attachEvent) {
				d.attachEvent('onkeyup', Eventos.aoTeclar);
			} else {
				w.onkeyup = Eventos.aoTeclar;
			}
		}
	};

	////////////////////////////////////////////////////////////////////////////////
	// Inicializando                                                              //
	////////////////////////////////////////////////////////////////////////////////
	w.Eventos = Eventos;
	w.Fonte = Fonte;
	w.Layout = Layout;
	//go!
	Eventos.criaOuvintes();
})(window, document);
/* js compressor v1.5 - Breno Ribeiro (http://ribeirobreno.com.br/) */
