function $(obj) {
	return document.getElementById(obj);
}

function mostrar(obj, abaprincipal, numaba) {
    var primeiro = $(abaprincipal + '1');
    var segundo = $(abaprincipal + '2');
    var terceiro = $(abaprincipal + '3');
    if (primeiro) primeiro.style.display = 'none';
    if (segundo) segundo.style.display = 'none';
    if (terceiro) terceiro.style.display = 'none';

    var aba = document.getElementById(abaprincipal+numaba);
    if (aba) aba.style.display = 'block';

    var locli = document.getElementById(abaprincipal);
    var lis = locli.getElementsByTagName('li');

    for (var i=0; i<lis.length; i++)
    {
        lis[i].setAttribute('class', '');
        lis[i].className = '';
    }

    lis[numaba-1].setAttribute('class', 'selecionado');
    lis[numaba-1].className = 'selecionado';
    $(abaprincipal).innerHTML = locli.innerHTML;
}


// Início Validação de Formulário

function validacao(formulario){

for(i=0;i<=formulario.length-1;i++){
	if ((formulario[i].type=="textarea")||(formulario[i].type=="file")||(formulario[i].type=="hidden")||(formulario[i].type=="text")||(formulario[i].type=="password")){
		if ((formulario[i].wmsg!="")&&(formulario[i].wmsg!=undefined)){
			if (formulario[i].email=="sim"){
				if((formulario[i].value=="")||(formulario[i].value.indexOf('@')==-1)||(formulario[i].value.indexOf('.')==-1)){
					alert(formulario[i].wmsg);
					try{
						formulario[i].focus();
					}
					catch(e){
						}				
				    return false
				}	
			}else{
				if(formulario[i].value==""){
					alert(formulario[i].wmsg);
					try{
						formulario[i].focus();
					}
					catch(e){

						}
				
					return false
				}
			}
		}
	}	
}
}

// Fim Validação de Formulário


function criaMascara(_RefObjeto, _Modelo)
{
	var valorAtual = _RefObjeto.value;        
	var valorNumerico = '';
	var nIndexModelo = 0;
	var nIndexString = 0;
	var valorFinal = '';
	var adicionarValor = true;
    
     
	// limpa a string valor atual para verificar 
	// se todos os caracteres são números
	for (i=0;i<_Modelo.length;i++){
		if (_Modelo.substr(i,1) != '#'){
			valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
  		}
 	}
      
 	// verifica se todos os caracteres são números
 	for (i=0;i<valorAtual.length;i++){
  		if (!isNaN(parseFloat(valorAtual.substr(i,1)))){
			valorNumerico = valorNumerico + valorAtual.substr(i,1);
  		}
 	}
      
 	// aplica a máscara ao campo informado usando
 	// o modelo de máscara informado no script
 	for (i=0;i<_Modelo.length;i++){
  		if (_Modelo.substr(i,1) == '#'){
    			if (valorNumerico.substr(nIndexModelo,1) != ''){
				valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
				nIndexModelo++;nIndexString++;
    			} 
    			else {
        			adicionarValor = false;
    			}
  		}
  		else {
     			if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != ''){
  				valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
				nIndexString++;
     			}
  		}
 	}
    
 	_RefObjeto.value = valorFinal 
}


function soNums(e,args)
{        
//  onKeyPress ="return (soNums(event,'(/){,}.'));"
	var valid_chars    = new Array();
   	if (document.all){
		var evt = event.keyCode;
	}
	else{
		var evt = e.charCode;
	}
   	var chr= String.fromCharCode(evt);
   	
	if (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ){return true;}
   	return false;
}


// Início Pop-up com e sem scrollbar
function abrir(url, width, height)
{
	var lado = (screen.width - width) / 2;
	var topo = (screen.height - height) / 2;
	window.open(url,'_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,top='+topo+',left='+lado+',width=' + width + ',height=' + height)
}

function abrirnb(url, width, height)
{
	var lado = (screen.width - width) / 2;
	var topo = (screen.height - height) / 2;
	window.open(url,'_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,top='+topo+',left='+lado+',width=' + width + ',height=' + height)
}
// Fim Pop-up com e sem scrollbar


// Início funções by Hargon

function trocaImagem(id,subid){
	var boxesContainer = $(id);
	var childs = boxesContainer.childNodes;

	for(var i = 0; i < childs.length; i++) {
		var node = childs[i];		
		if(node.tagName == "IMG")
			$(node.id).src = '../imagens/botoes/'+node.id+'.gif';
	}
	
	$(subid).src = '../imagens/botoes/' + subid + '_b.gif';
}

function trocaExibe(id,subid){
	var boxesContainer = $(id);
	var childs = boxesContainer.childNodes;

	for(var i = 0; i < childs.length; i++) {
		var node = childs[i];		
		if(node.tagName == "DIV")
			$(node.id).style.display = 'none';
	}
	
	$(subid).style.display = 'block';
}

function alteraImg(resultado,imagem){
	$(resultado).src = imagem;
}

var mcomboGeral = 0;
function mostrarCombo(camada){
	if (mcomboGeral == 0){
		new Effect.BlindDown(camada);
		mcomboGeral = 1;
	}else{
		new Effect.BlindUp(camada);
		mcomboGeral = 0;
	}
}
function mostrarComboJQuery(camada){
	if (mcomboGeral == 0){		
		$j('#'+camada).show('fast');
		mcomboGeral = 1;
	}else{
		$j('#'+camada).hide('slow');
		mcomboGeral = 0;
	}
}

function escolheCombo(formulario,campo,codigo,nome,tipo){
	if (tipo != 1){
		new Effect.BlindUp('div_cd'+campo);
	}else{
		$j('#div_cd'+campo).hide('slow');
	}
	mcomboGeral = 0;
	document.forms[formulario].elements['txtcd'+campo].value = codigo;
	document.forms[formulario].elements['optcd'+campo].value = nome;
}

function ContaCaracteres(tamanho,form,campo){
   	var campo = document.forms[form].elements[campo];
	intCaracteres = tamanho - campo.value.length;
	if (intCaracteres > 0){
	      	return true;
	}
	else {
		campo.value = campo.value.substr(0,tamanho);
      		return false;
   	}
}

// Fim funções by Hargon



// Função de mascara de moeda
function Moeda(fld, e) 
{
	if (window.event.keyCode >= 48 && window.event.keyCode <= 57)
	{ 
		var milSep = "."; 
		var decSep = ","; 
		var sep = 0; 
		var key = ''; 
		var i = j = 0; 
		var len = len2 = 0; 
		var strCheck = '0123456789'; 
		var aux = aux2 = ''; 
		var whichCode = (window.Event) ? e.which : e.keyCode; 

		if (whichCode == 13) 
			return true; 

		key = String.fromCharCode(whichCode); 

		if (strCheck.indexOf(key) == -1) 
			return false; 

		len = fld.value.length; 

		for (i = 0; i < len; i++) 
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
		break; 

		aux = ''; 

		for (; i < len; i++) 
			if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
				aux += fld.value.charAt(i); 

		aux += key; 
		len = aux.length; 

		if (len == 0) 
			fld.value = ''; 

		if (len == 1) 
			fld.value = '0'+ decSep + '0' + aux; 

		if (len == 2) 
			fld.value = '0'+ decSep + aux; 

		if (len > 2){ 
			aux2 = ''; 

		for (j = 0, i = len - 3; i >= 0; i--){ 
			if (j == 3){ 
				aux2 += milSep; 
				j = 0; 
			} 
			aux2 += aux.charAt(i); 
			j++; 
		} 

		fld.value = ''; 
		len2 = aux2.length; 

		for (i = len2 - 1; i >= 0; i--) 
			fld.value += aux2.charAt(i); 
		fld.value += decSep + aux.substr(len - 2, len); 
	} 

	return false; 

	} 
	else 
	{
		if (e.keyCod != 8) { // backspace
			e.keyCode = 0;
		}
	}
}


// Função de mascara e bloqueio de teclas não numéricas
function formata(valor)
{
	if (window.event.keyCode >= 48 && window.event.keyCode <= 57)
	{ 
		if (document.getElementById(valor).value.length == 2 || document.getElementById(valor).value.length == 5 ){
			document.getElementById(valor).value += "/";
		}	
	}
	else {
		if (window.event.keyCod != 8) { // backspace
			window.event.keyCode = 0;
			alert("Utilize apenas números!");
		}
	}
}


function favoritos(titulo, url)
{
	if ((navigator.appName=="Microsoft Internet Explorer") && (parseInt(navigator.appVersion)>=4)) {
		window.external.AddFavorite(url,titulo);		
	}
	else if (window.sidebar) {
		window.sidebar.addPanel(titulo, url,"");
	}
	else if(window.opera && window.print) {
		return true;
	}
}

function paginainicial(url){
	$("lnkPgnInicial").style.behavior='url(#default#homepage)'; 
	$("lnkPgnInicial").setHomePage(url);
	return false;
}


function gerarswf(arquivo,largura,altura,id,variaveis){
    document.writeln('    <object id="globalnav-object" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + largura + '" height="' + altura + '" id="' + id + '" name="' + id + '">');
    document.writeln('        <param name="movie" value="' + arquivo + '" />');
    document.writeln('        <param name="FlashVars" value="loc=en_US&htmlApp=false&gatewayURL=gwurl&' +variaveis+ '" />');
    document.writeln('        <param name="menu" value="true" />');
    document.writeln('        <param name="quality" value="high" />');
    document.writeln('        <param name="salign" value="tl" />');
    document.writeln('        <param name="scale" value="noscale" />');
    document.writeln('        <param name="wmode" value="transparent" />');
    document.writeln('        <embed id="globalnav-embed" src="' + arquivo + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" flashvars="loc=en_US&htmlApp=false&gatewayURL=gwurl&' +variaveis+ '" bgcolor="#ffffff" menu="false" quality="high" salign="tl" scale="noscale" id="' + id + '" width="' + largura + '" height="' + altura + '"></embed>');
    document.writeln('    </object>');
}

function removeElementById(remele) {
	remele = document.getElementById(remele);
	if (remele.parentNode && remele.parentNode.removeChild(remele)) {
		remele.parentNode.removeChild(remele);
	}
}

var largura = 0;
var altura = 0;
var topo = 0;
var larguraP = 0;

function lightboxHrg(valor,url,largurax,alturax){		
	if (valor == 0){
		$j('<div id="light" ></div>').appendTo('body');
		$j("#light").attr('className', 'conteudoLightbox');
		$j("#light").css({background: '#FFF url(' + ctt_url + '/imagens/loading.gif) center center no-repeat'});

		$j('<div id="fade" ></div>').appendTo('body');
		$j("#fade").attr('className', 'overlayFundoLightbox');
		$j('#fade').show();

		$j('<iframe id="carregaPagina" frameBorder="0" ></iframe>').appendTo('#light');
		$j('#carregaPagina').attr({ 
									src : url,
									width : '100%',
									height : '95%',
									marginWidth : '0',
									marginHeight : '0',
									name : 'carregaPagina'
								 });
		$j('#carregaPagina').hide();

		$j('#fade').click (function(){ lightboxHrg(1); });		
		$j('#fade').css('height',screen.height);

		$j('#carregaPagina').load(function() {  $j('#carregaPagina').show();
												$j("#light").css('background','#FFF'); 
										} );

		$j('<img id="botaoFecharLightBox" />').appendTo('#light');
		$j('#botaoFecharLightBox').attr({ 
										   name: 'botaoFecharLightBox', 
										   border: '0',
										   className: 'linkcursor', 
										   src: ctt_url + '/imagens/closelabel.gif',
										   margin: '0', 
										   align: 'right', 
										   alt: ''
										 });

		$j('#botaoFecharLightBox').click (function(){ lightboxHrg(1); });

		var larguraImagem = largurax;
		var alturaImagem = alturax;
		
		if (larguraImagem > screen.width){
			larguraImagem = larguraImagem - 120;
		}else if (larguraImagem == 0){
			larguraImagem = 300;
			alturaImagem = 200;
		}
		
		$j('#light').css('width',larguraImagem + 20);
		$j('#light').css('height',alturaImagem + 30);

		topo = (($j('html').height() + $j('html').scrollTop()) / 2) - alturaImagem/2;
		larguraP = (screen.width - larguraImagem) / 2 + 'px';

		$j('#light').css('top',topo);
		$j('#light').css('left',larguraP);

		
		$j('#light').fadeIn('fast');

	}else{
		$j('#light').hide('fast');
		$j('#fade').fadeOut('slow');

		$j('#light').empty();
		$j('#light').remove();
		$j('#fade').remove();
	}
}


/*
**************************************
* Event Listener Function v1.4       *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/enter-as-tab [rev. #2]

function enterAsTab(f, a){	
    addEvent(f, "keypress", function(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13 && (a || !/textarea|select/i.test(o.type))){
            for(i = l = (f = o.form.elements).length; f[--i] != o;);
            for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly || f[j].type.toLowerCase() == "hidden"););
            e.preventDefault(), j != i && f[j].focus();
        }
    });
}

function enterFormulario(f, a){	
    addEvent(f, "keypress", function(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13){
            document.forms[0].submit();
        }
    });
}