/**************************************************************************************************************/

// notas
// 25/08/2005 - Rafael Trindade - criado duas novas funcoes
// 08/11/2005 - Rafael Trindade - criada a funcoes PararProcesso
// 09/11/2005 - Rafael Trindade - criada um grupo de funcoes para vObj. Criada mais funcoes (gB + rE).
// 15/02/2006 - Rafael Trindade - adicionada as funcoes Event, PermiteNumerosComexcecoes, Refatoradas funcoes (gE + gB)
// 02/06/2006 - Rafael Trindade - foi criado uma colecao de funcoes relacionadas a utilizacao de cookies
// 27/06/2006 - Magno Oliveira/Rafael Trindade - prototype de redimensionamento do menu javascript ResizeMenu.Init()
// 13/07/2006 - Rafael Trindade - adicionada a funcao shObj(), agora a mesma encontra-se centralizada

  var nav   = navigator.userAgent.toLowerCase();
  var op    = nav.indexOf("opera") !=- 1;
  var ie    = nav.indexOf("msie") !=- 1;
  var ie5   = nav.indexOf("msie 5") !=- 1;
  var ie501 = nav.indexOf("msie 5.0") !=- 1;
  var ko    = nav.indexOf("konqueror") !=- 1;
  var sa    = nav.indexOf("safari") !=- 1;
  var ca    = nav.indexOf("camino") !=- 1;
  var ge    = nav.indexOf("gecko") !=- 1; // garante linha abaixo
  var ff    = nav.indexOf("firefox") != -1;
  var ns6   = document.getElementById && !document.all ? 1 : 0;


// funcao : Captura evento cross-browser
// autor  : Rafael Trindade
Event = function(e) { return window.event ? e.keyCode : e.which ? e.which : e.charCode; }

o = String.prototype;
// funcao: Substitui replace nativo do JS
// autor : Rafael Trindade
o.$_replace = o.replace;
o.replace = function (a, b) {
    if (a instanceof RegExp) return this.$_replace(a, b);
    else return this.split(a).join(b);
}

// funcao: Valida data de ponta a ponta
// autor : Diego Plentz
o.isDate = function(){ return (/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/).test(this); }


//*******************************************
    // funcao : Prototype para redimencionar tela de acordo com movimento do menu,
// a funcao encontra-se neste arquivo, pois nao tinha como colocar em um comum
// autor  : Rafael Trindade / Magno
// usemode: Ex.: var obj = new ResizeMenu(530,330,"Mensagem de alerta");
// obj.Init() deve ser usado no evento onload e onresize do body


//******************************************


/* Verifica se string eh um email valido 
por: Diego Plentz */
o.isEMail = function() { return (/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/).test(this); }

// funcao: Trim JS
// autor : Rafael Trindade
o.trim = function () { return this.replace(/^\s*|\s*$/g, ''); }

// funcao: Verifica se estah vazio
// autor : Rafael Trindade
o.isEmpty = function() { return (this.replace(/ /g,'').length < 1) ? true : false; }

// funcao: Valida hora
// autor : Diego Plentz / Rafael Trindade
o.isTime = function () { return (/^([0-1][0-9]|2[0-3]):[0-5][0-9]$/).test(this); }

// funcao: getElementById mozilla / ie / netscape 6
// autor : Rafael Trindade
gE = function (n) { return ns6 ? document.getElementById(n) : document.all[n]; }
// versao correta que deve ser utilizada
//gE = function(o) { return (document.getElementById(o) || (document.all || document.layers || {})[o]); }

// funcao: getElementsByTagName mozilla / ie / netscape 6
// autor : Rafael Trindade
gB = function (o) { return ((d = document).getElementsByTagName(o) || (d.all.tags || d.layers || {})[o]); }

// funcao: Adicionar Evento, substituindo o addEventListener tornando-o CROSS-BROWSER
// autor : Rafael Trindade
aE = function( o, e, h ){ o.addEventListener ? o.addEventListener( "on" + e, h, true)  : o.attachEvent ? o.attachEvent("on" + e, h ) : o["on" + e] = h; }

// funcao: Remover Evento, substituindo o removeEventListener tornando-o CROSS-BROWSER
// autor : Rafael Trindade
rE = function( o, e, h ){ o.detachEvent ? o.detachEvent("on" + e, h) : o.removeEventListener ? o.removeEventListener("on" + e, h, false) : o["on" + e] = null; }

// funcao : Remover zeros esquerda
// autor  : Rafael Trindade
// usemode: onBlur="removeLeftZero(this.name)"
removeLeftZero = function (c) { gE(c).value = gE(c).value.replace(/^0{0,}[^1-9]/g, ''); }

// funcao : Remover simbolos
// autor  : Rafael Trindade
// usemode: onBlur="removeSimbols(this.name)"
removeSimbols  = function (c) { if (gE(c)) gE(c).value = gE(c).value.replace(/[!,@,$,#,%,¨,|,\,&,*,(,),{,}]/g, ''); }

// funcao : Limpa no evento onblur campos do tipo numero, funcao especificamente criada para o Functions.cfm
// autor  : Rafael Trindade
// usemode: onBlur="removeAlfa(this);"
removeAlfa = function(o) { o.value = o.value.replace(/[^0-9]/g,''); }

// funcao    : Valida se campo eh vazio ou nao (return) true = vazio | false = ok
// refatorada: Rafael Trindade
ehVazio = function (f){ return (f.value.trim() == "") ? true : false; }

// funcao    : Retira espacos de uma string
// refatorada: Rafael Trindade
tiraEspaco = function (f){ return f.value.replace(' ',''); }

// funcao    : Show/Hide objetos, cross-browser
// autor     : Rafael Trindade
shObj = function(o,t) { gE(o).style.display = !t?'none':''; }

// funcao : Permite numeros com excecoes
// autor  : Alexandre Marcos / Rafael Trindade
// nota   : IMPORTANTE!!!!!!!!!!!!!!!!!! NAO PRECISA DEFINIR O ARGUMENTO NA FUNCAO PARA A EXCECAO!!!!
// usemode: onKeypress="return PermiteNumeroComExcecoes(event,'caracteresquequisersemseparador');"
PermiteNumeroComExcecoes = function (e) {
  var k  = String.fromCharCode(Event(e)); 
  var v  = String.fromCharCode(8) + '0123456789';
  var ex = (arguments.length == 2 && typeof(arguments[1]) == "string") ? arguments[1] += v : v;
  if (ex.indexOf(k) < 0) return false;
}

// funcao : Para o processamento de um JavaScript
// autor  : Rafael Trindade
// usemode: Chamar ela apos um processo
function PararProcesso() {
  if (!e) var e = window.event
  if (window.event) {
    window.event.cancelBubble = true;
    window.event.returnValue  = false;
  }
  if (e && e.preventDefault && e.stopPropagation) {
    e.preventDefault();
    e.stopPropagation();
  }
}

// funcao: GeraPontinhos no preloading
// autor : Rafael Trindade
GeraPontinhos = function() {
  txt = gE("aguarde-texto").innerHTML;
  if (pontinhos >= 10) {
	  txt = "Por favor aguarde.<br> Estamos processando suas informa&ccedil;&otilde;es.<br>";
	  pontinhos = 0;
  }
  gE("aguarde-texto").innerHTML = txt + "&#127;";
  pontinhos ++;
  window.setTimeout("GeraPontinhos()", 220);
}

// funcao : GeraPreloading (depois do retorno de validacao JS)
// usemode: O retorno da validacao for true, chama esta funcao
// autor  : Rafael Trindade
GeraPreloading = function() {
  if (gE("aguarde-conteudogeral")) {
    gE("aguarde-conteudogeral").style.display = "none";
    gE("aguarde-container").style.display     = "";
    GeraPontinhos();
  }
}

//FUNCAO:         consisteCampoNum
//Programador:    Karin Magedanz
//Objetivo:       So permite a digitacao de numeros, backspace, setas e delete
//Evento:         onkeydown
//Parametros:     tecla - tecla pressionada
//Atualizacao :   nao filtra mais a tecla "enter"
function consisteCampoNum(tecla){ return ((tecla >= 48 && tecla <= 57 ) || tecla == 8 || tecla == 13) ? true : false ; }

//FUNCAO:         formataValor
//Programador:    Karin Magedanz
//Objetivo:       Acrescenta casas decimais a um valor
//Evento:         onblur
//Parametros:     field - campo a ser formatado
//                nr_dec - quantidade de decimais
function formataValor(field,nr_dec){

  var str_aux = field.value;
  var tam = str_aux.length; // tamanho da string

  if (tam > 0 && str_aux.indexOf(",") == -1){ //se tamanho for maior que zero e nao possuir virgula
    str_aux = str_aux + ",";
    for (i=1;i<=nr_dec;i++){
      str_aux = str_aux + "0";
    }
    field.value = str_aux;
  }
  else if (tam > 0 && str_aux.indexOf(",") == (tam - 2)){ //se tamanho for maior que zero e so houver uma decimal
    for (i=1;i<=nr_dec - 1;i++){
      str_aux = str_aux + "0";
    }
    field.value = str_aux;
  }
  else if (tam > 0 && str_aux.indexOf(",") == (tam - 1)){ //se tamanho for maior que zero e so houver uma decimal
    for (i=1;i<=nr_dec;i++){
      str_aux = str_aux + "0";
    }
    field.value = str_aux;
  }
}


//FUNCAO:         preencheValor
//Programador:    Karin Magedanz
//Objetivo:       Formata o valor enquanto e digitado
//Evento:         onkeyup
//Parametros:     field - campo a ser formatado
//                maxtam - tamanho maximo de caracteres que o valor pode conter, com a virgula
//                nr_dec - quantidade de decimais
//Atualizacao:    27/08/2004 - Karin Magedanz
//                - a funcao passa a ser utilizada no evento onkeyup, para que possamos capturar
//                o evento do TAB. Assim, quando o TAB e pressionado o campo nao e selecionado
//                07/06/2006 - Rafael Trindade - Atualizacao do evento cross-browser
function preencheValor(field,maxtam,nr_dec,e){

  var tecla = (!e) ? (event||window.event).keyCode : Event(e);
  //var tecla = e.keyCode;

  if (tecla == 9){
    field.select();
  }

  // caso ja preencheu o valor maximo de caracteres
  // e tecla nao for backspace nem delete nem setas nem TAB nao permite mais digitar
  if (field.value.length > maxtam && tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 9){
    event.returnValue = false;
    return;
  }

  var str_aux = field.value.replace(",","");
  var tam = str_aux.length; // tamanho da string

  if (tecla == 8 || tecla == 46 || (tecla >= 48 && tecla <= 57 ) || (tecla >= 96 && tecla <= 105 )){
    if ( tam <= 1 ){
      field.value = str_aux;
    }
    if ( tam > nr_dec && tam <= maxtam ){
      field.value = str_aux.substr( 0, tam - nr_dec ) + ',' + str_aux.substr( tam - nr_dec);
    }
  }
}

//FUNCAO:         maskCartao - Funcao re-escrita
//Programador:    Rafael Trindade
//Objetivo:       Mascara com um espaco a cada 4 digitos e tratamento de copiar e colar
//Evento:         onBlur
//Parametros:     f - campo a ser formatado

maskCartao = function(f){
  s = '', f.value = f.value.replace(/[^0-9]/g,'');
  f.value = f.value.trim().substring(0,16);
  for(i = 0, h = f.value; i < h.length; i++){
    if (i%4 == 0 && i > 0) s += ' ' + h.charAt(i);
    else s += h.charAt(i);
  } 
  f.value = s;
  return; 
}

//FUNCAO:         validaNumerico
//Programador:    Karin Magedanz
//Objetivo:       Para validar o formato de um valor numerico
//Evento:
//Parametros:     field - campo a ser formatado
//                nr_int - quantidade de digitos permitidos na parte inteira do valor
//                nr_dec - quantidade de decimais

//Obs: O ideal eh definir esses parametros de acordo com os valores do campo no tabela do banco de dados
//     Para facilitar pode-se utilizar um parametro no input que defina esses valores (exemplo em FuelParamRelInconsistForm.cfm)

function validaNumerico(field,nr_int,nr_dec){
  //se possui virgula
  if (field.value.indexOf(",") != -1){
    if (field.value.length - (field.value.indexOf(",")+1) != nr_dec) return false;    //verifica numero de decimais
    if (field.value.indexOf(",") > nr_int) return false;    //verifica numero de digitos antes da virgula
  }
  else if (field.value.length != 0 && field.value.length > nr_int) return false;
  return true;
}

//FUNCAO:         preencheHora
//Programador:    Karin Magedanz
//Objetivo:       Formata a hora enquanto e digitada
//Evento:         onkeyup
//Parametros:     field - campo a ser formatado
//                tam - tamanho maximo para o campo
function preencheHora(field,tam){
  tecla = event.keyCode;

  if (tecla == 9){
    field.select();
  }

  // caso ja preencheu o valor maximo de caracteres
  // e tecla nao for backspace nem delete nem setas nem TAB nao permite mais digitar
  if (field.value.length > tam && (tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 9)){
    event.returnValue = false;
    return false;
  }
  var str_aux = field.value.replace(":","");

  if (tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 9 ){
		if (str_aux.length > 2 && str_aux.length < 5)
			str_aux = str_aux.substr(0, 2) + ':' + str_aux.substr(2);
		else if (str_aux.length >= 5 && str_aux.length < 9)
			str_aux = str_aux.substr(0,2) + ':' + str_aux.substr(2,2) + ':' + str_aux.substr(4);
    field.value = str_aux;
	}
}

function dataMask(i,e){
  if(nav == "IE") k = e.keyCode;
  else k = 0;
  if(k != 8 && k != 46) {
    s = i.value.replace("/","");
    if (s.length > 1 && s.length <= 4) s = s.substring(0,2) + "/" + s.substring(2);
    else if(s.length > 4 ) s = s.substring(0,2) + "/" + s.substring(2,4) + "/" + s.substring(4);
    if(i.value != s) i.value = s;
  }
}

/*
  Mascara para fone
*/
function MascaraFone(src)
{
	strsrc=src.value;

	if ((src.value.length>3) && (src.value.length<8))
	{
		strsrc_array=strsrc.split('-');
		if(typeof strsrc_array[1]!='undefined')
		{
			src.value=strsrc_array[0]+strsrc_array[1];
			strsrc=src.value;
		};

		src.value=strsrc.substring(0,3)+'-'+strsrc.substring(3,src.value.length);
	}
	else if(src.value.length==8)
	{
		strsrc_array=strsrc.split('-');
		if(typeof strsrc_array[1]!='undefined')
		{
			src.value=strsrc_array[0]+strsrc_array[1];
			strsrc=src.value;
		};

		src.value=strsrc.substring(0,4)+'-'+strsrc.substring(4,src.value.length);
	};
};

// Funcao : permite digitar apenas numeros / e formata a data.
// Autor  : Magno Oliveira
function filterNumero(e,svalor,stipo){
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;

	if ((code >= 48 && code <= 57 ) || code == 8 || code == 9 || code == 13){
		 e.returnValue = true;
		 if(stipo == 'DT')
		 {
		 	if (code != 8)
		 	{
			 if((svalor.value.length == '2') || (svalor.value.length == '5'))
			 {
				svalor.value = svalor.value + '/';
			 }
		 	}
		 }
   }else {
	 	if(!ie == true){ e.preventDefault();}
		else{e.returnValue = false;} 
   }
}


function formatar(src, mask)
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
  if (texto.substring(0,1) != saida)
  {
	src.value += texto.substring(0,1);
  }
}

// funcao     : conjunto de rotinas que desabilitam botoes de um form quando enviados
// refatorada : Rafael Trindade
// nota       : IMPORTANTE - para desabilitar TODOS os botoes de um form, basta definir
//              no escopo do template a seguinte linha var disabledAllButtons = true
var disabledAllButtons;
function disableButtons(func){
  if(func != false){
    if(func() == false){return false}
  }
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++) {
    var input = (b=inputs[i]).type.toLowerCase();
    if (input == "submit") b.value="Aguarde...";
    if ( (input == "submit" || input == "reset") || input == (vObj.isBoolean(disabledAllButtons)?"button":"submit") && input.indexOf("impr") == -1 ) {
       b.disabled = true;
       if (gE("aguarde-texto") && gE("aguarde-conteudogeral")) GeraPreloading();
    }
  }
}
function addOnSubmit(){
  for (i=0;i<document.forms.length;i++){
    var of = (d=document.forms[i]).onsubmit;
    if (d.target.toLowerCase() != "_blank") d.onsubmit = new Function(!d.onsubmit?"disableButtons(false)":"if(disableButtons("+ of +") == false){return false}");
  }
}

// funcao    : Faz validacao de data em formularios (em eventos)
// refatorada: Rafael Trindade
function validaDt(field){
//  if (field.value.trim() != "") {
if (field.value != "") {
    if (!field.value.isDate()) {
      alert("Formato data inválida!");
      field.focus();
      return false;
    }
  }
}

//funcao: verifica se uma data é superior a outra
//autor: rafael trindade
o.isDateGreater = function (dF) {
      if (this.substr(6, 4) < dF.substr(6,4))return true;
      else if (this.substr(6, 4) == dF.substr(6, 4))
      {
          if (this.substr(3, 2) < dF.substr(3, 2))return true;
          else if (this.substr(3, 2) == dF.substr(3, 2))
          {
              if(this.substr(0, 2) < dF.substr(0, 2))return true;
          }
      }
}

// funcao: conjunto de funcoes desenvolvidas somente para uso na custom tag FORMDATA.CFM
// autor: Rafael Trindade / Alexandre Marcos
var FormData = {

	// funcao: _cfgData
	// @param c - nome do campo
	// @param o - objeto de configuracao (cfgDatas[dinamico])
	// @param t - determina se eh tipo intervalo a chamada da custom (true/false)
  _cfgData : function(c,o,t) {
  	if (t) c.value = (c.name == (e=eval(o)).ds_nome_ini) ? e.dt_ini : e.dt_fim;
  	else {
  		c.value = "";
  		c.focus();
  	}
  },
	
	// funcao: validaDataCalendario
	// @param c - nome do campo
	// @param o - objeto de configuracao (cfgDatas[dinamico])
	// @param t - determina se a validacao eh ou nao obrigatoria
  validaDataCalendario : function(c,o,t) {
		if (c.value.trim() != '') {
	 		if (!c.value.isDate()) {
	 			alert("Data " + (((_o=eval(o).fl_controle))?(c.name==eval(o).ds_nome_ini)?"inicial ":"final ":"") + "inválida!");
	 			this._cfgData(c,o,(_o)?true:false);
	 		}
		} else {
			if (t) {
	 			alert("O preenchimento da data é obrigatório!");
	 			this._cfgData(c,o,eval(o).fl_controle?true:false);
			}
		}
  },

	// funcao: validaDataPeriodo
	// @param c - nome do campo
	// @param o - objeto de configuracao (cfgDatas[dinamico])
  validaDataPeriodo : function(c,o) {
  	if ( ( !(df=gE(eval(o).ds_nome_fim)).value.isEmpty() && !(di=gE(eval(o).ds_nome_ini)).value.isEmpty() ) ? df.value.isDateGreater(di.value) : false  ) {
  		alert("A data inicial não deve ser superior a data final.");
  		this._cfgData(c,o,true);
  	}
  },

	// funcao: selecionaPeriodos
	// @param o - objeto de configuracao (cfgDatas[dinamico])
	// @param c - nome do campo
  selecionaPeriodos : function(o,c) {
  	e = gE((_c=eval(c)).ds_nome_ini);
  	this._sP = function(o,c) {
  		_c = eval(c);
  		return (o==1)?_c.dt_hoje:(o==2)?_c.dt_mes:(o==3)?_c.dt_trinta:(o==4)?_c.dt_maximo:_c.dt_ini;
  	}
  	e.value = this._sP(o.value,_c);
  	return this._sP(o,_c)
  }
}


/******************* */
// funcao : Funcoes de consistencia de objetos e alguns tipos de variaveis JS
// usemode: if (vObj.isObject(gE('idCampo')) return true;
//          E assim com todas as outras funcoes
// autor  : Rafael Trindade
vObj = {
  isString    : function (o) { return typeof o == 'string'; },
  isFunction  : function (o) { return typeof o == 'function'; },
  isObject    : function (o) { return (o && typeof o == 'object') ; },
  isUndefined : function (o) { return typeof o == 'undefined'; },
  isBoolean   : function (o) { return typeof o == 'boolean'; }
}

/******************** */
// funcao  : Conjunto de funcao para gerenciamento de cookies via client
// use mode: Cookies.funcao() - de acordo com especificacao de parametros
// params  : n - nome do cookie | v = valor do cookie | d = dias para expirar
// autor   : Rafael Trindade
var Cookies = {
	exists : function(n) { // Verifica se cookie existe
		return ((!(mn=(ck=document.cookie).indexOf(n + "=")) && ck.substring(0,mn.length) || mn == -1) ? false : true);
	},
	create : function(n,v,d) { // Cria cookie
		var xp, dt, ck;
		if (d) {
			dt = new Date();
			dt.setTime(dt.getTime()+(d*24*60*60*1000));
			xp = "; expires="+dt.toGMTString(); }
		else xp = "";
		ck = n + "=" + v + xp + "; path=/";
		document.cookie = ck;
	},
	read : function(n) { // Faz leitura de cookie
		n = n+"="; 
		var ck = document.cookie.split(';');
		for(i = 0; i<ck.length; i++) {
			dc = ck[i];
			while (dc.charAt(0) == ' ') dc = dc.substring(1,dc.length);
			if (dc.indexOf(n) == 0) return dc.substring(n.length,dc.length);
		}
		return '';
	},
	erase : function(n) { // Zera o cookie
		this.create(n,"",0);	
	}
}

/******************* */
// funcao : Gera funcoes para pop ups, Central eh a funcao principal
// usemode: <a href=javascript:PopUp.Central('url.cfm',100,100,'janela')>um link</a> (execucao normal)
//          <a href=javascript:PopUp.Central('url.cfm',100,100)>um link</a> usa a url completa como nome da janela
//          <a href=javascript:PopUp.Central('url.cfm')>um link</a> (abre centralizado com base na resolucao do client)
// autor  : Rafael Trindade
var PopUp = {
  Central : function (u,l,a,n) {
    if (u.isEmpty()) alert("ERRO PopUp.Central: Voce deve definir um parametro de URL."); 
    var _rLU = Client.aWidth, _rAU = Client.aHeight,
        _arg = (arguments.length == 1) ? true : false,
    	_rLC = _arg ? _rLU/2 : l,
    	_rAC = _arg ? _rAU/2 : a,
    	top  = (_rAU-_rAC/2-_rAC/2)/2,
    	left = (_rLU-_rLC/2-_rLC/2)/2,
     	_win = "window"+_rLC,
        args = "menubar=no,toolbar=no,location=no,scrollbars=yes,status=yes,resizable=yes,width="+_rLC+",height="+_rAC+",left="+left+",top="+top;
    window.open(u,_win,args);
  }
}



//FUNCAO:         preencheData
//Programador:    Karin Magedanz
//Objetivo:       Formata a data enquanto e digitada
//Evento:         onkeyup
//Parametros:     field - campo a ser formatado
function preencheData(field){
  tecla = event.keyCode;

  if (tecla == 9){
    field.select();
  }

  // caso ja preencheu o valor maximo de caracteres
  // e tecla nao for backspace nem delete nem setas nem TAB nao permite mais digitar
  if (field.value.length >= 10 && (tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 9)){
    event.returnValue = false;
    return false;
  }
  if ((field.value.charAt(2) == "/" && field.value.charAt(3) == "/")){
    field.value = field.value.substr(0,3);
  }
  else if (field.value.charAt(2) == "/" && field.value.charAt(4) == "/") {
    field.value = field.value.substr(0,4);
  }
  if (tecla != 8 && tecla != 46 && tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40 && tecla != 9 ){
    var str_aux = field.value.replace("/","");
    str_aux = str_aux.replace("/","");

    if (str_aux.length > 2 && str_aux.length <= 4) {
      str_aux = str_aux.substr(0,2) + "/" + str_aux.substr(2);
    }
    else if (str_aux.length > 4 ){
      str_aux = str_aux.substr(0,2) + "/" + str_aux.substr(2,2) + "/" + str_aux.substr(4);
    }
    field.value = str_aux;
  }
}

//FUNCAO      : BarraStatus.Limpar
//Programador : Rafael Trindade / Karin Magedanz
//Objetivo    : funcao para limpar todos status dos objetos <a></a>
//Nota        : Refatorada por Rafael Trindade
//Parametros  :
if (vObj.isUndefined(BarraStatus)) var BarraStatus = {}
BarraStatus = function () {}
BarraStatus.prototype = {
  fL     : function() { window.status = ''; return true; } ,
  Limpar : function() {
    if (gB('a')){
      var tagA = gB('a');
      for (var i = 0; i < tagA.length; i++) { aE(tagA[i],"mouseover",this.fL); aE(tagA[i],"focus",this.fL); aE(tagA[i],"click",this.fL); }
    }
  }
}

/********************
*  funcao para fazer o tratamento CROSS-BROWSER do XMLHTTPREQUEST
*  Exemplo de uso  :
      var xmlhttp;
      xmlhttp = new XMLHTTPRequest();
      if (!xmlhttp) alert("Seu browser não está atualizado. .....");
*  @author : Rafael Trindade
*  @return  false ou o objeto XML
* Instancia cross-browser para HTTPREQUEST */
function XMLHTTPRequest() {
  var objHTTP;
  if (window.XMLHttpRequest) {
    objHTTP = new XMLHttpRequest(); } // Nativo (FF/Safari/Opera7.6+)
  else {
    try {
      objHTTP = new ActiveXObject("Msxml2.XMLHTTP"); } //activeX (IE5.5+/MSXML2+)
    catch(e) {
      try {
        objHTTP = new ActiveXObject("Microsoft.XMLHTTP"); } //activeX (IE5+/MSXML1)
      catch(e) {
        objHTTP = false;
      }
    }
  }
  if (ie501) objHTTP = false; // para IE 5.01 nao funciona mesmo, tem que sniffar
  return objHTTP;
}




// funcao : capturar propriedades da tela do client entre outros
// autor  : Rafael Trindade
// usemode: Client.funcao()
if (typeof Client == 'undefined') var Client = {}
var Client = {
	getWidth  : function() { return ((d = document).documentElement.offsetWidth || d.body.offsetWidth);	},
	getHeight : function() { return (self.innerHeight || (d = document).documentElement.clientHeight || d.body.clientHeight); },
        aWidth    : screen.availWidth,
        aHeight   : screen.availHeight
};

// ************************************************************************************************
// funcao   : Prototype OnUnLoad
// autor    : Rafael Trindade
// objetivo : Quando um operador esta alterando dados em um formulario, e deseja fazer qualquer outro
//            processo, eh enviada uma mensagem pra ele, avisando que os dados nao foram salvos.
//            IMPORTANTE: vale ressaltar que a funcionalidade deste processo esta limitada a apenas
//            tipo de campos diferentes de option e checkbox, sinta-se para alterar.
// usemode  : Ao final da pagina que tem o formulario
//            var objAviso = new OnUnLoad();
//            with (objAviso) { CarregarCampos(); ControlarCampos(); }
var campos = new Array();
campos[0]  = new Array(1);
campos[1]  = new Array(1);

ExibirAviso = function() { if (confirm("Voce alterou os dados do motorista.\n Deseja prosseguir sem salvar?")) return true; else PararProcesso(); }
CriarAviso  = function() { if (gB('a')) for (var i = 0; i < gB('a').length; i++) { rE(gB('a')[i],"click",ExibirAviso); aE(gB('a')[i],"click",ExibirAviso); } }

if (vObj.isUndefined(OnUnLoad)) var OnUnLoad = {}
OnUnLoad = function () {}
OnUnLoad.prototype = {
  CarregarCampos  : function() {
    var form = document.forms[0];
    if (vObj.isObject(form)) {
      for (var i = 0; i < form.elements.length; i++) {
        if (vObj.isObject(form.elements[i])) {
          var campo = form.elements[i];
          campo_nome  = ns6 ? campo.getAttribute('name')  : campo.name;
          campo_valor = ns6 ? campo.getAttribute('value') : campo.value;
          if (!campo_nome.trim().isEmpty()) {
            campos[0][i] = campo_nome;
            campos[1][i] = campo_valor;
          }
        }
      }
    }
  },
  CompararCampos  : function() {
    var form = document.forms[0];
    if (vObj.isObject(form)) {
      for (var i = 0; i < form.elements.length; i++) {
        if (vObj.isObject(form.elements[i])) {
          var campo = form.elements[i];
          campo_nome  = ns6 ? campo.getAttribute('name')  : campo.name;
          campo_valor = ns6 ? campo.getAttribute('value') : campo.value;
          if (!campo_nome.trim().isEmpty()) {
            if (campos[0][i] == campo_nome) {
              if (campos[1][i] != campo_valor) {
                CriarAviso();
                return true;
                break;
              }
            }
          }
        }
      }
    }
  },
  ControlarCampos : function() {
    if (gB('input') || gB('select')) {
      var tagInput  = gB('input');
      var tagSelect = gB('select');
      for (var i = 0; i < tagInput.length; i++) {
        if (vObj.isObject(tagInput[i]))  aE(tagInput[i],"blur",this.CompararCampos);
        if (vObj.isObject(tagSelect[i])) aE(tagSelect[i],"change",CriarAviso);
      }
    }
  }
}
//******************************************************************************************
//funcao: ValidaCNPJCPF
//autor: Magno Oliveira
//Objetivo: Conjunto de funções para verificar a validade do cpf e cnpj
//          scampo = objeto do campo
//			exemplo = this
//          stipo = tipo de válidação a ser feita
//          exemplo = 'CNPJ' ou 'CPF'
function ValidaCNPJCPF(scampo,stipo)
{
  if (scampo.value != '')
  { var campo = scampo.name;

	  if(!Verify(scampo.value, stipo))
	  {
	    alert(stipo+" inválido!");
	    gE(campo).focus();
	  }
  }
  return;
}

function ClearStr(str, schar)
{
  while((cx=str.indexOf(schar))!=-1)
  {
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

function ParseNumb(c)
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
}

function Verify(scampo,stipo)
{
  scampo=ParseNumb(scampo);

  if(scampo == 0)
  {
    return(false);
  }
  else
  {
    g=scampo.length-2;
    if(TestDigit(scampo,stipo,g))
    {
      g=scampo.length-1;
      if(TestDigit(scampo,stipo,g))
      {
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }
}

function TestDigit(scampo,stipo,g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig+=parseInt(scampo.charAt(f-1))*ind;
    if (stipo=='CNPJ')
    { if(ind>8) {ind=2} else {ind++} }
    else
    { ind++ }
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(scampo.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
//Funcao: caracter especiais.
//Descricao: os caracteres listados na invalidos não sera permitido digitar
//Autor: Magno
function CaracterEsp(e)
	{
		var invalidos = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890/\()-!@#$%¨&*_+<>,.;:?|[]{}";
		var tecla = e.keyCode;
		var key = String.fromCharCode(tecla);

		if (window.event)
		{
			keycode = window.event.keyCode;
		}
		else if (e)
		{
				keycode = e.which;
		}
		if((tecla !='13') && (tecla != '32') )
		{
			if(tecla =='92')
			{
				event.returnValue = false;
			}
			else
			{
				e.returnValue = !( invalidos.indexOf(key) == -1 );
			}
		}
	}
//Funcao: Tamanho
//Descricao: limita a quantidade de caracteres que se pode ser digitano em uma text area
//Autor: Magno
function Tamanho(event,campo,quantidade,label)
    {
		var tecla
		var sCampo = window.document.getElementById(campo.name);


		if (sCampo.value.length >= quantidade)
		{
			var tecla
			if (!e) var e = window.event;
		    if (e.keyCode) tecla = e.keyCode;
		    else if (e.which) tecla = e.which;
			if ((tecla == 0) || (tecla == 8) || (tecla == 32) || (tecla == 13))
			{
				event.returnValue = true;
			}
			alert('Limite de ' + quantidade + ' caracteres no campo ' + label +'!');
	        sCampo.focus();
			event.returnValue = false;
		}
		else
		{
			event.returnValue = true;
		}
    }