
function EscondeFlyHome(){
	document.getElementById('flyhome').style.display='none';
}


function abreJanela(caminho,janela,parametros){
	MM_openBrWindow(caminho,janela,parametros);
	janelaNova.focus();
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  janelaNova=window.open(theURL,winName,features);
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
//

document.write('<link rel="stylesheet" href="../../css/default.css" type="text/css">')


function popup(arquivo,w,h) {
	window.open(arquivo, "pop", "toolbar=0,location=0,directories=0,status=0,menubar=no,scrollbars=no,resizable=no,width="+w+",height="+h+"");
}

function demonstracoes(arquivo) {   
	window.open(arquivo,'pdf','width=700,height=500,top=10,left=10,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes');
}

function trim(str)
{
	return str.replace(/^\s*/, "").replace(/\s*$/, "");
}


// máscara de campos
// uso: onkeydown="FormataCampo(this,event,'##/##/####')"
function FormataCampo(Campo,teclapres,mascara, sai) {

	if (sai == "S" && consistente == "N") {
		if (obrigatorio == "N" && Campo.value.length > 0) {
			obrig_fixo = "S";
			Consist(Campo.maxLength, Campo);
			obrig_fixo = "N";
		}
		if (obrigatorio == "S" || Campo.value.length > 0) {
			if (sai == "S") {
				if (Campo.value.length != mascara.length) {
					alert('O campo precisa estar neste formato:\n\n       '+ mascara);
					Campo.value = "";
				}
				erro = "S";
				return false;
			}
		}
	}
	if (sai == "S" && obrigatorio == "N" && Campo.value.length > 0) {
		obrig_fixo = "S";
		Consist(Campo.maxLength, Campo);
		obrig_fixo = "N";
		if (consistente == "N") {
			alert('O campo precisa estar neste formato:\n\n       '+ mascara);
		}
	}


	strtext = Campo.value;
	tamtext = strtext.length;
	tammask = mascara.length;
	arrmask = new Array(tammask);
	for (var i = 0 ; i < tammask; i++) {
		arrmask[i] = mascara.slice(i,i+1)
	} 

	//alert(teclapres.keyCode );
	if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))) {
		if ((teclapres.keyCode >= 35 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)||(teclapres.keyCode == 16)){
			Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)		
		} else {
			Detona_Event(Campo,strtext)
		}
	} else {
		if ((arrmask[tamtext] == "A")) {
			charupper = event.valueOf()
			Detona_Event(Campo,strtext)
			masktext = strtext + charupper 
			Campo.value = masktext
		}
	}
}
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){
	if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){
		separador = arrpos
		masktext = strtext + separador
		Campo.value = masktext
	}
}
function Detona_Event(Campo,strtext){
	event.returnValue = false
	if (strtext != "") {
		Campo.value = strtext
	}
}

function soNumeros(e){
	var key;
	var keychar;

	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}

	keychar = String.fromCharCode(key);

	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==27) ) {
		return true;
	} else if ((("0123456789").indexOf(keychar) > -1)) {
		return true;     
	} else {
		return false;
	}
}
//Impede que caracterec não numéricos entrem em campos de formulário html
//Usar onChange
function soNumerico(tammax){
	event.srcElement.maxLength=tammax;
	if (event.srcElement.value.length+1>tammax) { 
		event.KeyCode=0;
	}
	if ( (event.keyCode >= 48) && (event.keyCode <= 57)) {
		return true;
	} else {
		if (event.keyCode != 8){
			 event.keyCode = 0;
			 return false;
		 }
	}
}
function isNumeric(valor){
	var strValor = new String(valor);
	arrValor = strValor.split('');
	for(i=0;i<arrValor.length;i++){
		if ((("0123456789.").indexOf(arrValor[i]) < 0)) {
			return (false);
		}
	}
	return (true);
}

//validacao de radio buttons sem saber quantos sao
	function checa(nform) {
	marcado = -1;
	resposta = "";
	if(nform.length) {
		for (i=0; i<nform.length; i++) {
			if (nform[i].checked) {
				//caso algum item do radioButton esteja selecionado, marcado deixa de valer -1
				marcado = i;
				resposta = nform[i].value;
			}
		}
	}else{
		resposta = nform.checked?nform.value:'';
	}
	return resposta;
}

//Testa se uma data é valida
//Retorna true caso a data seja válida, e false caso não.
function isDate(Data){
    strData = new String(Data);   
    //Verifica se a data veio formatada com / ou -
    if (strData.indexOf('/') >= 0)    {
        arrData = strData.split('/');
    }else if(strData.indexOf('-') >= 0){
        arrData = strData.split('-');
    }else{
        arrData = new Array()
    }   
    //Se contém os três valores de dia, mês e ano ou ano, mês e dia
    if(arrData.length == 3){
        //Testa de os valores de dia mês e ano não foram passados vazios
        if(arrData[0] != '' &&  arrData[1] != ''  && arrData[2] != '' ){
            //Cria objeto de data considerando que a data estava no padrão americano
            objData = new Date(arrData[0],arrData[1]-1,arrData[2]);
            //Se a data for inválida, tenta criar objeto de data com padrão brasileiro
            if(isNaN(objData)){
                objData = new Date(arrData[2],arrData[1]-1,arrData[0]);
            }   
            //Testa o objeto de data. Se a data inicial não era válida o objeto será NaN
            if(isNaN(objData)){
                bolRetorno = false;
            } else {//Se for válida
				bolData = true;
				 var dia = arrData[0];
				 var mes = arrData[1];
				 var ano = arrData[2];
				 if (ano % 4 == 0)  var ano_bi = true
				 else var ano_bi = false;

				 if (mes >= 1 && mes <= 12){
				   if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 ){
					 if (dia < 1 || dia > 31){
					   bolData = false;
					 }
				   }
				   else if (mes == 4 || mes == 6 || mes == 9 || mes == 11 ){
					 if (dia < 1 || dia > 30){
					   bolData = false;
					 }           
				   }
				   else if (mes == 2 && ano_bi ){
					 if (dia < 1 || dia > 29){
					   bolData = false;
					 }          
				   } 
				   else { 
					 if (dia < 1 || dia > 28){
					   bolData = false;
					 }           
				   }
				 } else{
					   bolData = false;
				 }


				if(bolData){
					bolRetorno = true;
				} else {
					bolRetorno = false;
				}
//                alert(objData);
            }
        } else {//Se dia, mês ou ano foram vazios
            bolRetorno = false;
        }
    } else {
            bolRetorno = false;
    }
//        alert(objData);
    return bolRetorno;   
}
/*
//Verifica se CPF é válido
//Se for válido, retorna TRUE, caso contrário retorna FALSE
function isCpf (numcpf)
{
	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = "";
	numcpf1="";
	len = numcpf.length; x = len -1;
	// var numcpf = "12345678909";
	for (var i=0; i <= len - 3; i++) {
		y = numcpf.substring(i,i+1);
		soma = soma + ( y * x);
		x = x - 1;
		texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ;
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++) {
		soma = soma + (numcpf1.substring(i,i+1) * x);
		x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	//alert ("Digito Verificador : " + dig1 + "" + dig2);
	if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
		return true;
	}
	return false;
}
*/


//################################################################################
//################################################################################
//################################################################################

/**
 * @author Márcio d'Ávila
 * @version 1.01, 2004
 *
 * PROTÓTIPOS:
 * método String.lpad(int pSize, char pCharPad)
 * método String.trim()
 *
 * String unformatNumber(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */


var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formatação e zeros à esquerda da string
 * de número fornecida.
 * @param String pNum
 *      String de número fornecida para ser desformatada.
 * @return String de número desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 *      String fornecida para ser formatada.
 * @param boolean pUseSepar
 *      Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 *      Indica se a string fornecida é um CNPJ.
 *      Caso contrário, é CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 dígitos verificadores para o número-efetivo pEfetivo de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-efetivo fornecido é CNPJ (default = false).
 * @param String pEfetivo
 *      String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida é de um CNPJ.
 *      Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida é um CPF válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digitos) return false;

	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida é um CNPJ válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


/**
 * Testa se a String pCpfCnpj fornecida é um CPF ou CNPJ válido.
 * Se a String tiver uma quantidade de dígitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpfCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ válido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj
//################################################################################
//################################################################################
//################################################################################
//Testa se string passada é email ou não
//Retorna falso se não for email, caso contrario retorna verdadeiro
function isEmail(value){
	value = new String(value)
	 p=value.indexOf('@');
	if (p<1 || p==(value.length-1)){
		return false;
	} else {
		if (value.indexOf('.',p+2)<1 || value.length < (p+4)){
			return false
		} else {
			return true;
		}
	}
}

//Impede que caracterec não numéricos entrem em campos de formulário html. Permite formato moeda (0,00)
//Usar onChange
function soMoney(tammax){
	event.srcElement.maxLength=tammax;
	if (event.srcElement.value.length+1>tammax) { 
		event.KeyCode=0;
	}
	if ( (event.keyCode >= 48) && (event.keyCode <= 57 ) || (event.keyCode == 44)) {
		if (event.keyCode == 44){
			if (event.srcElement.value.indexOf(",") > -1) {			
				event.keyCode = 0;
				return false;
			}
		}
		return true
	} else {
		if (event.keyCode != 8){
			 event.keyCode = 0;
			 return false;
		 }
	}
}
/**
 * Verifica se um CNPJ ou CPF eh valido.
 *
 * @param  sText String com o CNPJ ou CPF a ser verificado
 * @return true se o CNPJ ou CPF for valido; false caso contrario
 */
function isValidCPFCGC(sText) {
var flgStatus;

flgStatus = true;
sText = new String(sText).toString();
if(sText.length == 11) {
  // CPF
  for(i=0;((i<=(sText.length-1))&& flgStatus); i++) {
	val = sText.charAt(i);
	
if((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") &&
	   (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {
	  flgStatus = false;
	  }
	}
  if(flgStatus) {
	soma = 0;
	for(i=0;i<=8;i++) {
	  val = eval(sText.charAt(i));
	  soma = soma + (val*(i+1));
	  }
	resto = soma % 11;
	if(resto>9) {
	  dig = resto-10;
	  } else {
		  dig = resto;
		  }
	if(dig != eval(sText.charAt(9))) {
	  flgStatus = false;
	  } else {
		  soma = 0;
		  for(i=0;i<=7;i++) {
			val = eval(sText.charAt(i+1));
			soma = soma + (val*(i+1));
			}
		  soma = soma + (dig * 9);
		  resto = soma % 11;
		  if(resto>9) {
			dig = resto-10;
			} else {
				dig = resto;
				}
		  if (dig != eval(sText.charAt(10))) {
			flgStatus = false;
			}
		  }
	}
  } else if(sText.length == 14) {
		   // CGC-CNPJ
		   for(i=0;((i<=(sText.length-1))&& flgStatus); i++) {
			 val = sText.charAt(i);
			 
if((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") &&
				(val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {
			   flgStatus = false;
			   }
			 }
		   if(flgStatus) {
			 m2 = 2;
			 soma1 = 0;
			 soma2 = 0;
			 for(i=11;i>=0;i--) {
			   val = eval(sText.charAt(i));
			   m1 = m2;
			   if (m2<9) {
				 m2 = m2+1;
				 } else {
					 m2 = 2;
					 }
			   soma1 = soma1 + (val * m1);
			   soma2 = soma2 + (val * m2);
			   }  // fim do for de soma

			 soma1 = soma1 % 11;
			 if (soma1 < 2) {
			   d1 = 0;
			   } else {
				   d1 = 11-soma1;
				   }

			 soma2 = (soma2 + (2 * d1)) % 11;
			 if (soma2 < 2) {
			   d2 = 0;
			   } else {
				   d2 = 11-soma2;
				   }
			 if (!((d1==sText.charAt(12)) && (d2==sText.charAt(13)))) {
			   flgStatus = false;
			   }
			 }
		   } else {
			   // Inválido
			   flgStatus = false;
			   }

return(flgStatus);
}

function aviso(strMensagem, objCampo, strTitulo, intTipo){
	try{
//		erro=1/0;
		strTitulo=strTitulo==''?'Erro no preenchimento do formulário!':strTitulo;
		intTipo=intTipo==''?1:intTipo;
		balloonTooltip.show(strTitulo,strMensagem,intTipo,objCampo);
	}catch(e){
		alert(strMensagem);
	}finally{
		try{
			objCampo.focus();
		}catch(e){

		}
	}
}
