﻿// Portal do Tribunal de Contas da União
// Scripts do Modelo-Padrão do Portal TCU
// Versão 1.00; Atualizada em 27/05/2008.

// Função "Detecta o Navegador" - Início
// Fonte: http://www.quirksmode.org/js/detect.html


function refreshPage(){
var loc = ""+window.location;
loc = loc.substring(loc.indexOf("/",loc.indexOf("//")+2));

var arr = new Array();
arr[0]='Menu Perfis de Usuário';
arr[1]= 'Coluna Pesquisa'
arr[2]= 'Coluna Notícias';
arr[3]= 'Coluna Acesso Restrito';
arr[4]= 'Menu Informações Por';
arr[5]= 'Coluna Áreas Temáticas';
arr[6]= 'Coluna Produtos e Serviços';
arr[7]= 'Coluna Publicações';
if(loc=='/portal/page/portal/TCU/P5'){
	arr = new Array();
	arr[0] = 'Menu Perfis de Usuário';
	arr[1] = 'Área Para o Servidor';
	arr[2] = 'Coluna Destaques 1';
	arr[3] = 'Coluna Publicações';
	arr[4] = 'Coluna Informações Pessoais';
	arr[5] = 'Área Para o Trabalho';
	arr[6] = 'Formulário de Pesquisa Básica';
	arr[7] = 'Coluna Notícias';
	arr[8] = 'Coluna Institucional';
	arr[9] = 'Coluna Áreas Temáticas';
	arr[10] = 'Coluna Produtos e Serviços';
	arr[11] = 'Coluna Publicações';
}


var texto = "";
if (document.layers) { 
  texto = ""+ document;
}else if (parseInt(navigator.appVersion)>=5&&navigator.appName=="Netscape" || document.all) { 
  texto = document.body.innerHTML;
}
var i=0;
var refresh = false;
for(i=0; i<arr.length; i++){
  arr[i] = "<!-- " + arr[i] +" -->";
  if((texto.indexOf(arr[i])<0)){
	refresh = true;
  }

}
if(refresh && loc.indexOf("refreshed")<0 && (loc=="/portal/page/portal/TCU/" || loc=="/portal/page/portal/TCU" || loc=="/TCU" || loc=="/portal/page/portal/TCU/P5") ){
  window.location = ""+window.location +"?refreshed=true";
}

}


// Função "Altera Tamanho da Fonte" - Início
// Fonte: http://scripts.ringsworld.com/e-commerce/enterprise3.01/admin/includes/menu.js.html

	
	function ndeSetTextSize(chgsize,rs)	{
		if (!document.documentElement || !document.body){
			return;
		}
		var newSize;
		var startSize = parseInt(ndeGetDocTextSize());
		if (!startSize)	{
			startSize = 11;
		}

		switch (chgsize){
			case 'incr':
				newSize = startSize + 1; //Aumenta a fonte
				break;
			case 'decr':
				newSize = startSize - 1; //Diminui a fonte
				 break;
			case 'reset':
				if (rs)	{
					newSize = rs; //Retorna ao tamanho padrão
				}
				else{
					newSize = 11;
				}
				break;
			default:
				newSize = parseInt(ndeReadCookie('nde-textsize', true));
				if (!newSize){
					newSize = startSize;
				}
				break;
		}
		if (newSize < 10){ //Para a fonte não ficar muito pequena
			newSize = 10;
		}
		if (newSize > 14){ //Para a fonte não ficar muito grande e desconfigurar o layout
			newSize = 14;
		}
		newSize += 'px';
		document.documentElement.style.fontSize = newSize;

		//Pega o nome da tag paga alterar o tamanho da fonte
        //document.body.style.fontSize = newSize;

		linhas = document.body.getElementsByTagName('div');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('input');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('textarea');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('select');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('p');
			for(i = 0 ; i < linhas.length ; i++){
				if(linhas[i].parentNode.id!="GlobalInternoSlogan" && linhas[i].parentNode.id!="GlobalInternoNome")
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('a');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('h2');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}
		linhas = document.body.getElementsByTagName('h3');
			for(i = 0 ; i < linhas.length ; i++){
			linhas[i].style.fontSize=newSize;
		}

		ndeCreateCookie('nde-textsize', newSize, 365, true);
	}

	function ndeGetDocTextSize(){
		if (!document.body)	{
			return 0;
		}
		var size = 0;
		var body = document.body;
		if (body.style && body.style.fontSize)	{
			size = body.style.fontSize;
		}
		else if (typeof(getComputedStyle) != 'undefined'){
			size = getComputedStyle(body,'').getPropertyValue('font-size');
		}
		else if (body.currentStyle)	{
			size = body.currentStyle.fontSize;
		}
		return size;
	}

	//Cookies

	function ndeCreateCookie(name,value,days,useLang){
		var langString = useLang ? ndeGetLang() : '';
		var cookie = name + langString + '=' + value + ';';

		if (days){
			var date = new Date();
			var ndeMilliSecondsInDay = 86400000; // 24*60*60*1000
			date.setTime(date.getTime()+(days*ndeMilliSecondsInDay));
			cookie += ' expires=' + date.toGMTString() + ';';
		}
		cookie += ' path=/';
		document.cookie = cookie;
	}

	function ndeReadCookie(name, useLang){
		var langString = useLang ? ndeGetLang() : '';
		var nameEQ = name + langString + '=';
		var ca = document.cookie.split(';');

		for(var i = 0; i < ca.length; i++){
			var c = ca[i];
			while (c.charAt(0) == ' ')	{
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0)	{
				return c.substring(nameEQ.length,c.length);
			}
		}
		return null;
	}

	function ndeGetLang(){
		var langString = '';

		if (document.documentElement){
			langString = document.documentElement.lang;
			if (langString != ''){
				langString = '-' + langString;
			}
		}
		return langString;
	}

	// Função "Altera CSS" - Início
// Fonte: http://www.manifesto.blog.br/

	padrao = "esquema_1" ;

	function troca(txt) {
		var i, a, main;
		 for(i=0;(a = document.getElementsByTagName("link")[i]);i++) {
			if (a.getAttribute("type") == "text/css") {
				a.disabled = true ;
				a.setAttribute("rel", "alternate stylesheet") ;
			}
		}
	for(i=0;(a = document.getElementsByTagName("link")[i]);i++) {
			if (a.getAttribute("type") == "text/css" && a.getAttribute("title") == txt) {
				a.disabled = false ;
				a.setAttribute("rel", "stylesheet") ;
			}
		}
	  //setCookie("estilo",txt,"99",null,null,null,null);
	  ndeCreateCookie('estilo', txt, 365, true);


	}


	function checkForUpgrade(){
		var rvValue = -1;

		if (navigator.product == 'Gecko'){
			rvValue = 0;
			 var ua = navigator.userAgent.toLowerCase();
			 var rvStart = ua.indexOf('rv:');
			 var rvEnd = ua.indexOf(')', rvStart);
			 var rv = ua.substring(rvStart+3, rvEnd);
			 var rvParts = rv.split('.');
			 var exp = 1;

			for (var i = 0; i < rvParts.length; i++){
				var val = parseInt(rvParts[i]);
				rvValue += val / exp;
				exp *= 100;
			}
		}

		if (!document.getElementById || ( rvValue >= 0 && rvValue < 1.0)){
			var updateMessageShown = ndeReadCookie('upgrade');
			if (!updateMessageShown){
				ndeCreateCookie('upgrade','1', 90);
				// check if cookie written. If not, don't redirect
				if (ndeReadCookie('upgrade')){
					document.location = '/upgrade.html';
				}
			}
		}
	}

	checkForUpgrade();

	function init(){
		//cssjsmenu('navbar');
		cssjsmenu('nde-config');
		if (document.getElementById){
			var kill = document.getElementById('hoverJS');
			kill.disabled = true;
		}
	}

	// csjsmenu.js
	function elementContains(elmOuter, elmInner){
		while (elmInner && elmInner != elmOuter){
			elmInner = elmInner.parentNode;
		}
		if (elmInner == elmOuter){
			return true;
		}
		return false;
	}

	function getPageXY(elm){
		var point = { x: 0, y: 0 };
		while (elm)	{
			point.x += elm.offsetLeft;
			point.y += elm.offsetTop;
			elm = elm.offsetParent;
		}
		return point;
	}

	function setPageXY(elm, x, y){
		var parentXY = {x: 0, y: 0 };

		if (elm.offsetParent){
			parentXY = getPageXY(elm.offsetParent);
		}

		elm.style.left = (x - parentXY.x) + 'px';
		elm.style.top = (y - parentXY.y) + 'px';
	}

	/* file boundary */

	function cssjsmenu(menuid){
		 var i;
		 var j;
		 var node;
		 var child;
		 var parent;

		// if the browser doesn't even support
		 // document.getElementById, give up now.

		 if (!document.getElementById) {
			return true;
		 }

		 // check for downlevel browsers
		 // Opera 6, IE 5/Mac are not supported

		 var version;
		 var offset;

		 offset = navigator.userAgent.indexOf('Opera');
		 if (offset != -1) {
			version = parseInt('0' + navigator.userAgent.substr(offset + 6), 10);
			 if (version < 7) {
				return true;
			 }
	 	 }

		 offset = navigator.userAgent.indexOf('MSIE');
		 if (offset != -1)	{
		 	if (navigator.userAgent.indexOf('Mac') != -1){
				return true;
		 	}
		 }

		 var menudiv = document.getElementById(menuid);

		 // ul
		 var ul = new Array();

		 for (i = 0; i < menudiv.childNodes.length; i++){
			 node = menudiv.childNodes[i];
			 if (node.nodeName.toUpperCase() == 'UL') {
			 	ul[ul.length] = node;
			 }
		 }

		 // ul > li
		 var ul_gt_li = new Array();

		 for (i = 0; i < ul.length; i++) {
			 node = ul[i];
			 for (j = 0; j < node.childNodes.length; j++) {
				 child = node.childNodes[j];
				 if (child.nodeName.toUpperCase() == 'LI') {
					 ul_gt_li[ul_gt_li.length] = child;
					 child.style.display = 'inline';
					 child.style.listStyle = 'none';
					 child.style.position = 'static';
				 }
		 	}
		 }

		 // ul > li > ul
		 var ul_gt_li_gt_ul = new Array();

		 for (i = 0; i < ul_gt_li.length; i++) {
			 node = ul_gt_li[i];
			 for (j = 0; j < node.childNodes.length; j++) {
				 child = node.childNodes[j];
				 if (child.nodeName.toUpperCase() == 'UL') {
					 ul_gt_li_gt_ul[ul_gt_li_gt_ul.length] = child;
					 child.style.position = 'absolute';
					 child.style.left = '-13em';
					 child.style.visibility = 'hidden';

					 // attach hover to parent li
					 parent = child.parentNode;
		 			 parent.onmouseover = function (e){
						var i;
						var child;
						var point;

						// stop the pure css hover effect
						this.style.paddingBottom = '0';

						for (i = 0; i < this.childNodes.length; i++){
							 child = this.childNodes[i];
							 if (child.nodeName.toUpperCase() == 'UL') {
								 point = getPageXY(this);
								 setPageXY(child, point.x, point.y + this.offsetHeight);
								 child.style.visibility = 'visible';
							 }
		 				}
		 				return false;
					 };
		 			parent.onmouseout = function (e){
						 var relatedTarget = null;
						 if (e)	{
							 relatedTarget = e.relatedTarget;
							 // work around Gecko Linux only bug where related target is null
							 // when clicking on menu links or when right clicking and moving
							 // into a context menu.
							 if (navigator.product == 'Gecko' && navigator.platform.indexOf('Linux') != -1 && !relatedTarget) {
							 	relatedTarget = e.originalTarget;
							 }
		 				}
						else if (window.event){
						 	relatedTarget = window.event.toElement;
						}

						if (elementContains(this, relatedTarget)){
							return false;
						}

						var i;
						var child;
		 				for (i = 0; i < this.childNodes.length; i++){
		 					child = this.childNodes[i];
		 					if (child.nodeName.toUpperCase() == 'UL'){
		 						child.style.visibility = 'hidden';
		 					}
		 				}
		 				return false;
		 			};
		 		}
		 	}
		 }
		 return true;
	}

function inicalizaPagina(){
		//inicializa tamanho texto
		var ck =ndeReadCookie("nde-textsize",true);
		var corrente = ndeGetDocTextSize();
		if(corrente.indexOf("pt")>0)
		  corrente = 0+ parseInt(corrente.substring(0,corrente.length-2));

		if(ck!=null && ck.indexOf("p")>0){
		 var tamanho = parseInt(ck.substring(0,ck.indexOf("p")));
		 ndeSetTextSize("reset",tamanho);
		 /*
		 var diff = Math.abs(tamanho-parseInt(corrente));
		for(i=0; i<diff;i++){
		 if(tamanho>parseInt(corrente))
		   ndeSetTextSize("incr");
		 else
		   ndeSetTextSize("decr");
		}
		*/
		 }
		//estilo
		ck = ndeReadCookie("estilo",true);
		if (ck!=null && ck.indexOf("esquema")>=0){
		  troca(ck);
		}
	}


//Operador ternário:
	//os parâmetros são: condicao ? verdadeiro : falso
	function showtime()	{
		var now = new Date();
		var hours = now.getHours();
		var minutes = now.getMinutes();
		var seconds = now.getSeconds();
		var timeValue = "" + hours; //((hours > 12) ? hours - 12 : hours);
		timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
		//timeValue+= ((seconds < 10) ? ":0" : ":") + seconds;
		//timeValue+= (hours >= 12) ? " P.M." : " A.M.";

		//Atualiza a cada segundo
		//document.clock.face.value = timeValue;
		document.getElementById('CampoData').innerHTML =  DATA +'&nbsp;&nbsp;|&nbsp;&nbsp;'+timeValue+'&nbsp;&nbsp;|&nbsp;&nbsp;'+PER+'&nbsp;';
		timerID = setTimeout("showtime()",1000);
		timerRunning = true;
	}

	function day(){
	//DATA
		hoje = new Date();
		dia = hoje.getDate();
		dias = hoje.getDay();
		mes = hoje.getMonth();
		ano= hoje.getFullYear();
	//	ano = hoje.getYear();
		if (dia < 10)
			dia = "0" + dia;

		function CriaArray (n){
			this.length = n
		}

		NomeDia = new CriaArray(7);
		NomeDia[0] = "Domingo ";
		NomeDia[1] = "Segunda-feira";
		NomeDia[2] = "Ter&ccedil;a-feira";
		NomeDia[3] = "Quarta-feira";
		NomeDia[4] = "Quinta-feira";
		NomeDia[5] = "Sexta-feira";
		NomeDia[6] = "S&aacute;bado";

		NomeMes = new CriaArray(12);
		NomeMes[0] = "Janeiro";
		NomeMes[1] = "Fevereiro";
		NomeMes[2] = "Mar&ccedil;o";
		NomeMes[3] = "Abril";
		NomeMes[4] = "Maio";
		NomeMes[5] = "Junho";
		NomeMes[6] = "Julho";
		NomeMes[7] = "Agosto";
		NomeMes[8] = "Setembro";
		NomeMes[9] = "Outubro";
		NomeMes[10] = "Novembro";
		NomeMes[11] = "Dezembro";

		//Mostra a data
		//return document.write (NomeDia[dias] + ", " + dia + " de " + NomeMes[mes] + " de " + ano);
		 DATA = (NomeDia[dias] + ", " + dia + " de " + NomeMes[mes] + " de " + ano);
	}
    function periodo(){
        var now = new Date();
        var hours = now.getHours();

        if (hours < 12)
           PER = ("Bom dia ");
        else
            if (hours < 18)
               PER = ("Boa tarde ");
            else
               PER = ("Boa noite ");
    }

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
}

// Função "Oculta/Exibe Colunas" - Início

    function ocultaExibe(nomeDiv){

      imageUp       = new Image();
      imageDown     = new Image();

      imageUp.src   = "/portal/page/portal/TCU/imagens/0_B17.jpg";
      imageDown.src = "/portal/page/portal/TCU/imagens/0_B18.jpg";

      // Array que conterá os DIVs correspondentes às colunas Áreas Temáticas, Produtos e Serviços, Publicações e Enquete
      // Todos esses DIVs devem ter o mesmo valor para o atributo nome (name) e para o id (id).
      var arrayDivs  = document.getElementsByName(nomeDiv);

      var varDisplay;

      // Detecta o navegador
      // O IE e Mozilla acessam o valor do atributo STYLE, de uma tag qualquer, de formas diferentes.
      // O retorno para os comandos também é diferente, conforme visto abaixo (Mozilla retorna 'display: none;' e IE 'none').
      BrowserDetect.init();

      // Verifica se o conjunto de colunas está aparente ou oculto
      if ((BrowserDetect.browser == 'Explorer')){
         // IE
         varDisplay = document.getElementById(nomeDiv).style.getAttribute('display');
      }
      else{
         // Mozilla
        varDisplay = document.getElementById(nomeDiv).getAttribute('style');
        varDisplay = varDisplay.substring(varDisplay.indexOf("display:") , varDisplay.indexOf(";",varDisplay.indexOf("display:"))+1);
     }

      // Passa por todos os elementos do arrayDivs
      for (i = 0; i < arrayDivs.length; i++) {
        idElemento = arrayDivs[i].id;

      	if ((varDisplay == 'display: none;') || (varDisplay == 'none')){
            // Troca a imagem "seta para baixo" por "seta para cima"
            document['imgSeta'].src = imageUp.src;
            // Apresenta os DIVs
    		arrayDivs[i].style.display="block";
            // Troca o title da imagem do botão para Recolher
    		document['imgSeta'].title = "Recolher este menu"
      	}
      	else{
            // Troca a imagem "seta para baixo" por "seta para cima"
            document['imgSeta'].src = imageDown.src;
            // Oculta os DIVs
            arrayDivs[i].style.display="none";
            // Troca o title da imagem do botão para Expandir
    		document['imgSeta'].title = "Expandir este menu"
      	}
      }
    }

// Função "Recolhe-Expande Menu" - Início

function recolheExpande(idObjetoDD){

  var elementos    = document.getElementsByTagName('DD'); // Pega todos os elementos do tipo DD na página
  var elementosLen = elementos.length;                    // Pega o tamanho do array elementos
  var idDD;
  var idDDTemp     = idObjetoDD;     					  // Pega o id do objeto recebido pela função
  var varDisplay;

  // Detecta o navegador
  BrowserDetect.init();

  // O IE e Mozilla acessam o valor do atributo STYLE, de uma tag qualquer, de formas diferentes.
  // O retorno para os comandos também é diferente, conforme visto abaixo (Mozilla retorna 'display: none;' e IE 'none').
  if ((BrowserDetect.browser == 'Explorer')){
     // IE
     varDisplay = document.getElementById(idDDTemp).style.getAttribute('display');
  }
  else{
     // Mozilla
     varDisplay = document.getElementById(idDDTemp).getAttribute('style');
  }

  // Se o DD está fechado (display: none;) o abre
  if ((varDisplay == 'display: none;') || (varDisplay == 'none')){
     document.getElementById(idDDTemp).style.display = 'block';
  }
  // Se o DD está aberto o fecha e termina a função
  else{
	 document.getElementById(idDDTemp).style.display = 'none';
	 return;
  }

  // Passa por todos os elementos do tipo DD,
  for (i = 0; i < elementosLen; i++) {
     idDD = elementos[i].id;
     if ((idDD != null) && (TrimJS(idDD) != "")){
        // exceto pelo elemento recebido pela função e fecha o elemento aberto
	    if (idDD != idDDTemp){
 	       document.getElementById(idDD).style.display = 'none';
        }
     }
  }
}

// Fonte: http://www.freecode.com.br/drartigos/artigo.php?cdart=193&id=7
// Script que possui a mesma função usada no "Trim()" do VbScript:
// Retira todos os espaços do inicio e fim da string, se existirem.
function TrimJS(pString){
   Resultado = pString;
   //Retira os espaços do inicio//Enquanto o primeiro caracter for igual à "Espaço"
   //1 caracter do inicio é removido
   if (Resultado.charCodeAt(2-1) == '32'){}
   while (Resultado.charCodeAt(0) == '32'){
      Resultado = pString.substring(i,pString.length);
      i++;
   }
   //Pega a string já formatada e agora retira os espaços do final
   //mesmo esquema, enquanto o ultimo caracter for um espaço, ele retira 1 caracter do final...
   while(Resultado.charCodeAt(Resultado.length-1) == "32"){
      Resultado = Resultado.substring(0,Resultado.length-1);
   }
   return Resultado;
}

var timerID = null;
var timerRunning = false;

function stopclock(){
		if(timerRunning)
		clearTimeout(timerID)
		timerRunning = false;
	}

function startclock(){
		stopclock();
		day();
		periodo();
		showtime();
	}

function mudapagina(x){
    var endereco = x.value;
    if (endereco != "#")
    {
		var url= "" + window.location.href;
  	    url = url.substring(0,url.indexOf("/",url.indexOf("//")+2));

		if(endereco.indexOf("http")==0 || endereco.indexOf(url)==0 || endereco.indexOf("/portal/pls/portal/TCU_CUSTOM.UTIL")==0)
			novapagina = window.open(endereco,"NewPage");
		else
	       window.location = endereco;
    }
}
