/*
funÃ§Ã£o que recebe um array de combos e limpa todos
*/
function limpaCombos(arrayCombos) {
	i = 0;
	for(i = 0; i < arrayCombos.length; i++) {
		DWRUtil.removeAllOptions(arrayCombos[i]);
		DWRUtil.setValue(arrayCombos[i], 0);
	}
}


function fullwin(targeturl){
sistemaWindow=window.open(targeturl,"SistemaMetropolis","fullscreen,scrollbars");
}

/*
funcao que marca e desmarca todos os checkboxs 
de um formulario
*/
function marcarDesmarcarTodos(checkbox) { 

	//pega o formulario desse checkbox
	formulario = checkbox.form;
	
	//varre todo o formulario e atualiza o estado para os itens de checbox
	for(i=0; i<=formulario.length -1; i++)
		if( formulario.elements[i].type == "checkbox" )
			formulario.elements[i].checked = checkbox.checked;
	
} 


//funcao que limpa todos os itens de um formulario

function limparFormulario(botao) { 

	//pega o formulario desse botao
	formulario = botao.form;
	
	//varre todo o formulario e seta branco em todos
	for(i = 0; i < formulario.length; i++){
	
		if (formulario.elements[i].type == "checkbox")
			formulario.elements[i].checked = false;
			
		if (formulario.elements[i].type == "text")
			formulario.elements[i].value = "";
		
		if (formulario.elements[i].type == "textarea")
			formulario.elements[i].value = "";
				
		if (formulario.elements[i].type == "radio") {
			formulario.elements[i].checked = false;
			if (formulario.elements[i].value == "")
				formulario.elements[i].checked = true;
		}
			
		if (formulario.elements[i].type == "select-one")
			if (formulario.elements[i].options[0] != null)
				formulario.elements[i].options[0].selected = true;

		if (formulario.elements[i].type == "select-multiple") {
			for (j = 0; j < formulario.elements[i].length; j++) {
				if (formulario.elements[i].options[j] != null)
					formulario.elements[i].options[j].selected = false;
			}
		}
		
	}
	
} 


/*
funcao que redireciona para uma url
*/
function goToUrl(url,target){    

	if(target="self")
		self.location.href = url;
	else if(target="top")
		top.location.href = url;
	else
		blank.location.href = url;
}


/*
funcao que redireciona para uma url sem target
*/
function goToUrl(url){    
		self.location.href = url;
}


/*
funcao que confirma a exclusÃ£o de um registro 
pelo icone de exclusao da grid
*/
function confirmarExcluir(url, msg){
    
	if ( confirm(msg) )
		goToUrl(url);
	else
		return false;	
}


/*
funcao que confirma a exclusÃ£o de um registro 
pelo submit do formulario da grid
*/
function confirmarExcluirForm(form, msg, msgErro){

	marcado = false;
	
	for(i=0; i<=form.length - 1; i++)
		if( (form.elements[i].type == "checkbox") && (form.elements[i].checked) && (form.elements[i].id != "marcarTodos") )
			marcado = true;			

	if(marcado)	    
		return confirm(msg);
	else
		alert(msgErro);

	return false;	

}


/*
Funcao que mostra e oculta uma layer
*/
function ShowHideLayerAcao(layer,acao){

  obj=document.getElementById(layer);
  obj.style.display = acao;
  
}


/*
Funcao que mostra e oculta uma layer
(se estiver oculta, mostra, e vice-versa)
*/
function ShowHideLayer(layer){

  obj=document.getElementById(layer);  
  
  if(obj.style.display == 'none')
  	obj.style.display = 'block';
  else
  	obj.style.display = 'none';
}


/*
Funcao que Abre uma janela Modal 
tanto para IE, quanto Netscape
*/
function modalWin(url,nome,largura,altura,parametros) {


	if (parametros!=''){
	   parametros="&"+parametros;
	   
	}


	window.open(url+parametros, nome, "left=200,top=200,height="+altura+",width="+largura+",toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no");
}
	
	function populaCombo(comboOrigem,comboDestino,urlMetodo){
	
		//pega o formulario do combo de origem
		formulario = comboOrigem.form;
		
		//salva o action e o target original do formulario
		actionOriginal=formulario.action;
		targetOriginal=formulario.target;
		
		//indice do combo de destino, no array de elements do form.
		indiceDestino = 0;
			
		//encontra o indice do elementos de destino
		for(i=0; i<formulario.length; i++)			
			if((formulario.elements[i].type == "select-one") && (formulario.elements[i].name == comboDestino.name) )
				indiceDestino = i;
		

		//zera combos, apartir do combo de destino
		for(i=indiceDestino; i<formulario.length; i++){

			if((formulario.elements[i].type == "select-one"))	
				limparCombo(formulario.elements[i]);
			
			if((formulario.elements[i].type == "select-one"))								
				formulario.elements[i].options[0] = new Option('-------- selecione ---------','0');
		}	
		
		//se a opcao do combo de origem for valida (diferente de ----selecione----)
		if(comboOrigem.value != 0){
		
			//popula o combo seguinte
			formulario.action = urlMetodo+"&id="+comboOrigem.value+"&comboDestino="+comboDestino.name;
			formulario.target ="iframeCombo";
			formulario.submit();
		}
		
		//recupera o action e o target original do formulario
		formulario.action=actionOriginal;
		formulario.target=targetOriginal;
	}
	
	
	function enviaFormulario(frm){
	
		//configura o action
		frm.action="combo-resultado.jsp";
		frm.target="_top";
		frm.submit();
	}	

	function limpaArrayCombo(combos){
		for(i=0;i<combos.length;i++)
			combos[i].options.length=0;
	}
	
	function limparCombo(combo){
		for (var i=0; i < combo.options.length; i++) {
		  combo.options[i] = null;
		}
		combo.options[0] = new Option('-------- selecione ---------','');
	}
	
	function limparComboDefault(combo){
		for (var i=0; i < combo.options.length; i++) {			
		  combo.options[i] = null; 
		}
		combo.options[0] = new Option('-------- selecione ---------','0');
	}
	
 function abrePopupSelecionaUnidadeOrganizacional(form, path){

	//abre a janela modal aki olha
	modalWin(path+'/cadastrogeral/selecionarUnidadeOrganizacional.do?metodo=preSelecionar','modal',400,300,'form=' + form);

}

/*
   Funcao que limpa os itens de formulario passados como parametro
*/

function limparFormularioCampos(campos) { 

	for(i = 0; i< campos.length; i++){
	
		obj = document.getElementById(campos[i]);
		
		if( obj.type == "checkbox" )
			obj.checked = false;
			
		if( (obj.type == "text") || (obj.type == "hidden") )
			obj.value = "";
			
		if( obj.type == "radio" )
			obj.checked = false;	
			
		if( obj.type == "select-one" )
			obj.options[0].selected = true;
		
	}
		
} 


//Funcao que verifica se a data final eh maior que a inicial

function compararData(obj_dtInicial,obj_dtFinal){
  	
  	var dia, mes, ano;

	dia = obj_dtInicial.value.substr(0,2);
	mes = obj_dtInicial.value.substr(3,2);
    ano = obj_dtInicial.value.substr(6,4);
		
	var dtinicial = new Date(ano + "/" + mes + "/" + dia);

	dia = obj_dtFinal.value.substr(0,2);
	mes = obj_dtFinal.value.substr(3,2);
    ano = obj_dtFinal.value.substr(6,4);
		
	var dtfinal = new Date(ano + "/" + mes + "/" + dia);

   if (dtinicial > dtfinal){
     alert("Data final deve ser maior que Data Inicial.");
	 obj_dtFinal.focus();	 
	 return false;
   }

	return true;
 }
 
  // Funcao que verifica se o conteudo do campo eh vazio 
  function naoVazio(field){
  	var thisChar, str;
  	var counter = 0;

    str = field.value;
    if ( str == '') {
		field.focus()
		return false;
    }
    
    for (var i=0; i<str.length; i++){
       thisChar = str.substring(i, i+1);
       if (thisChar == " ")
           counter++;
    }
   
    if (counter == str.length){
	 field.focus();		
     return(false);
    }
   
    return true;	
  }
  
  //Funcao que verifica se o campo eh vazio
  function isVazio(field){
   var thisChar;
   var counter = 0;
   var str;
   
    str = field.value
    if ( str == "" ) {
       if (typeof(msg) != "undefined"){ 
		   field.focus()
		}   
		return true;
    }
    
    for (var i=0; i<str.length; i++){
       thisChar = str.substring(i, i+1);
       if (thisChar == " ")
           counter++;
   }
   
   if (counter == str.length){
     if (typeof(msg) != "undefined"){
          field.focus();		
	 }   
      return true;
   }
   
    return false;	
}


//Funcao que verifica qual o browser do cliente
function verificarBrowser(){
	
	if (navigator.appName.indexOf('Microsoft') != -1){
		clientNavigator = "IE";
	}else{
		clientNavigator = "Other";
	}
	
	return clientNavigator;
}


 //Funcao qeu so permite digitar numeros
 function mascaraNumNatural(evnt){ 
	  
 	if (verificarBrowser() == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
 }
 
  //Ajusta mÃ¡scara de Data no formato "99/99/9999" e sÃ³ permite digitaÃ§Ã£o de nÃºmeros 
  function mascaraData(input, evnt){

 	if (input.value.length == 2 || input.value.length == 5){
 		if(verificarBrowser() == "IE"){
 			input.value += "/";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "/";
 			}
 		}
 	}
 	return mascaraNumNatural(evnt);
 }
 
 //Ajusta mÃ¡scara de Data no formato "99/9999" e sÃ³ permite digitaÃ§Ã£o de nÃºmeros 
  function mascaraMesAno(input, evnt){

 	if (input.value.length == 2){
 		if(verificarBrowser() == "IE"){
 			input.value += "/";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "/";
 			}
 		}
 	}
 	return mascaraNumNatural(evnt);
 }
 
 //Ajusta mÃ¡scara de Hora no formato "99:99" e sÃ³ permite digitaÃ§Ã£o de nÃºmeros 
  function mascaraHora(input, evnt){

 	if (input.value.length == 2){
 		if(verificarBrowser() == "IE"){
 			input.value += ":";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += ":";
 			}
 		}
 	}
 	return mascaraNumNatural(evnt);
 }
 

 //Funcao que ajusta mascara para numero do processo no formato "99999/9999"
 function mascaraNumProcesso(input, evnt){
 	
 	if (input.value.length == 5){
 	 		if(verificarBrowser() == "IE"){
 			input.value += "/";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "/";
 			}
 		}
 	}
 	return mascaraNumNatural(evnt);
 	
 }
 
 
//Funcao de comparacao do numero de processl inicial com o final

function compararNumProcesso(numProcessoInicial, numProcessoFinal){
	var numeroInicial, numeroFinal;
	var splitNumIni, splitNumFim;
	
	splitNumIni = numProcessoInicial.value.split("/");
	splitNumFim	= numProcessoFinal.value.split("/");
	
	numeroInicial = splitNumIni[1] + splitNumFim[0];
	numeroFinal	= splitNumFim[1] + splitNumFim[0]; 	
	
	if (numeroInicial > numeroFinal){
     alert("Numero Final deve ser maior do que o Inicial.");
	 numProcessoFinal.focus();	 
	 return false;
   }
   else{
	return true;
   }
}


function transfereItemCombo(origem, destino){
	for(i=0;i<origem.options.length;i++){
		if(origem.options[i].selected){
			destino.options[ destino.length ] = new Option(origem.options[i].text, origem.options[i].value);
			origem.options[i] = null;
			i=-1;
		}
	}

}


function insereItemCombo( origem,  destino )
  {
      if (origem.selectedIndex < 0 ){
		  return false;
	  }
	  
	  existe = false;
      for ( lnx = 0 ;  lnx < destino.length && !existe ; lnx++ )
	  {
	      if ( destino.options[ lnx ].value == origem.value ) 
		  {
		     existe = true;
//   	         alert( "Esse item ja foi associado." );
		     return false;
			 
		  }
	  }
	  
  
	  destino.length =  destino.length + 1;
	  destino.options[ destino.length -1 ].value = origem.value;
	  destino.options[ destino.length -1 ].text = origem.options[ origem.selectedIndex ].text
  }
  
 
  
  function removeItemCombo( campo ) 
  {
		
      if ( campo.selectedIndex >= 0 )
         campo.options[ campo.selectedIndex ] = null;
				  
  }
  
  	function existeRadioSelecionado(obj){
		radioSelecionado = false;				
	
		//varre o objeto do radio e verifica se existe algum item selecionado
		for(i = 0; i < obj.length; i++){
			if(obj[i].checked == true){
				radioSelecionado = true;
			}
		}
		return radioSelecionado;
	}
	
		
	function populaListBox(pesquisa,comboDestino,urlMetodo){
		formulario = pesquisa.form; 
		formulario.action = urlMetodo+"&pesquisa="+pesquisa.value+"&comboDestino="+comboDestino.name;
		formulario.target ="iframeCombo";
		formulario.submit();
	}
	
	function removeItensCombo(idCombo){
	
		combo = document.getElementById(idCombo);
		
		colOptions = combo.childNodes;

		for (i=0; i < colOptions.length; i++){

			if (colOptions.item(i).selected){
				combo.removeChild(colOptions.item(i));
				i=-1; //volta para o inicio pq ao remover reorganiza
			}
		}
	
	}
	
	function cleanElementsCombo(element){
      for(i=0; i<element.options.length; i++){
       if (element.options[i].selected){
         element.options[i]=null;
         i--; 
       }
      }
    }
	
	function addAllElementsCombo(from, to){
  
     for (i=0; i<from.options.length; i++){
       var existe=false;
       from_ = from.options[i];
         for(j=0; j<to.options.length; j++){
            to_ = to.options[j]; 
            if ( (from_.text)==(to_.text) ){
               var existe=true;
               break;
            } 
         }
         if (!existe){
           var last = to.options.length;
           to.options[last]= new Option(from_.text,from_.value); 
         } 
      } 
    }
    
    function relatorio(form,url) {
		var action = form.action;
		var target = form.target;
		form.action = url;
		//Esta linha estava abrindo uma página em branco quando mandava imprimir um relatório. [Nelson]
		//form.target = "blank";
		form.submit();
		form.action = action;
		form.target = target;
	
	}
	
	function formataValor4CasasDecimais(campo) {
		vr = campo.value;
		vr = vr.replace("/", "");
		vr = vr.replace("/", "");
		vr = vr.replace(",", "");
		vr = vr.replace(".", "");
		vr = vr.replace(".", "");
		vr = vr.replace(".", "");
		vr = vr.replace(".", "");
		tam = vr.length;
		
		if ( tam <= 4 ){
		campo.value = vr; }
		if ( (tam > 4) && (tam <= 7) ){
		campo.value = vr.substr( 0, tam - 4 ) + ',' + vr.substr( tam - 4, tam ); }
		if ( (tam >= 8) && (tam <= 10) ){
		campo.value = vr.substr( 0, tam - 7 ) + '.' + vr.substr( tam - 7, 3 ) + ',' + vr.substr( tam - 4, tam ); }
		if ( (tam >= 11) && (tam <= 13) ){
		campo.value = vr.substr( 0, tam - 10 ) + '.' + vr.substr( tam - 10, 3 ) + '.' + vr.substr( tam - 7, 3 ) + ',' + vr.substr( tam - 4, tam ); }
	}
	
	function formataValorMascProcesso(campo){
		vr = campo.value;
		
		vr = vr.replace("/", "");
		vr = vr.replace("/", "");
		vr = vr.replace("/", "");
		tam = vr.length;
		
		if ( tam <= 4 ){
		campo.value = vr; }
		if ( (tam > 4) && (tam <= 10) ){
		campo.value = vr.substr( 0, tam - 4 ) + '/' + vr.substr( tam - 4, tam );}
	}
	
	function formataValor(campo,tammax) {		
			vr = campo.value;
			vr = vr.replace( "/", "" );
			vr = vr.replace( "/", "" );
			vr = vr.replace( ",", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			vr = vr.replace( ".", "" );
			tam = vr.length;

			if ( tam <= 2 ){
				campo.value = vr ; }
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 9) && (tam <= 11) ){
				campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 12) && (tam <= 14) ){
				campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 15) && (tam <= 17) ){
				campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
	}
	
		function formataCRC(campo) {
			crc = campo.value;
			crc = crc.replace( "-", "" );
			crc = crc.replace( "-", "" );
			crc = crc.replace( "-", "" );
			crc = crc.replace( ".", "" );
			crc = crc.replace( ".", "" );
			crc = crc.replace( ".", "" );
			crc = crc.replace( "/", "" );
			crc = crc.replace( "/", "" );
			crc = crc.replace( "/", "" );			
			crc = crc.replace( " ", "" );
			crc = crc.replace( " ", "" );
			crc = crc.replace( " ", "" );
			tam = crc.length;

			if ( tam <= 1 ){
				campo.value = crc ; }
			if ( tam == 2 ){
				campo.value = crc.substr( 0, 1 ) + '-' + crc.substr( 1, tam ) ; }
			if ( (tam >= 3) && (tam <= 5) ){
				campo.value = crc.substr( 0, tam - 2 ) + '/' + crc.substr( tam - 2, 1 ) + '-' + crc.substr( tam - 1, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				campo.value = crc.substr( 0, tam - 5 ) + '.' + crc.substr( tam - 5, 3 ) + '/' + crc.substr( tam - 2, 1 ) + '-' + crc.substr( tam - 1, tam ) ; }
			if ( (tam >= 9) && (tam <=10 ) ){
				campo.value = crc.substr( 0, tam - 8 ) + ' ' + crc.substr( tam - 8, 3 ) + '.' + crc.substr( tam - 5, 3 ) + '/' + crc.substr( tam - 2, 1 ) + '-' + crc.substr( tam - 1, tam ) ; }
		}
		
	function formataCPF(campo) {
			cpf = campo.value;
			cpf = cpf.replace( "-", "" );
			cpf = cpf.replace( ".", "" );
			cpf = cpf.replace( ".", "" );
			cpf = cpf.replace( ".", "" );
			cpf = cpf.replace( ".", "" );
			cpf = cpf.replace( ".", "" );
			tam = cpf.length;

			if ( tam <= 2 ){
				campo.value = cpf ; }
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = cpf.substr( 0, tam - 2 ) + '-' + cpf.substr( tam - 2, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				campo.value = cpf.substr( 0, tam - 5 ) + '.' + cpf.substr( tam - 5, 3 ) + '-' + cpf.substr( tam - 2, tam ) ; }
			if ( (tam >= 9) && (tam <= 11) ){
				campo.value = cpf.substr( 0, tam - 8 ) + '.' + cpf.substr( tam - 8, 3 ) + '.' + cpf.substr( tam - 5, 3 ) + '-' + cpf.substr( tam - 2, tam ) ; }
			if ( (tam >= 12) && (tam <= 14) ){
				campo.value = cpf.substr( 0, tam - 11 ) + '.' + cpf.substr( tam - 11, 3 ) + '.' + cpf.substr( tam - 8, 3 ) + '.' + cpf.substr( tam - 5, 3 ) + '-' + cpf.substr( tam - 2, tam ) ; }
			if ( (tam >= 15) && (tam <= 17) ){
				campo.value = cpf.substr( 0, tam - 14 ) + '.' + cpf.substr( tam - 14, 3 ) + '.' + cpf.substr( tam - 11, 3 ) + '.' + cpf.substr( tam - 8, 3 ) + '.' + cpf.substr( tam - 5, 3 ) + '-' + cpf.substr( tam - 2, tam ) ;}
		}
		
	function formataCNPJ(campo) {
			cnpj = campo.value;
			cnpj = cnpj.replace( "-", "" );
			cnpj = cnpj.replace( "/", "" );
			cnpj = cnpj.replace( ".", "" );
			cnpj = cnpj.replace( ".", "" );
			cnpj = cnpj.replace( ".", "" );
			cnpj = cnpj.replace( ".", "" );
			cnpj = cnpj.replace( ".", "" );
			tam = cnpj.length;

			if ( tam <= 2 ){
				campo.value = cnpj ; }
			if ( (tam > 2) && (tam <= 6) ){
				campo.value = cnpj.substr( 0, tam - 2 ) + '-' + cnpj.substr( tam - 2, tam ) ; }
			if ( (tam >= 7) && (tam <= 9) ){
				campo.value = cnpj.substr( 0, tam - 6 ) + '/' + cnpj.substr( tam - 6, 4 ) + '-' + cnpj.substr( tam - 2, tam ) ; }
			if ( (tam >= 10) && (tam <= 12) ){
				campo.value = cnpj.substr( 0, tam - 9 ) + '.' + cnpj.substr( tam - 9, 3 ) + '/' + cnpj.substr( tam - 6, 4 ) + '-' + cnpj.substr( tam - 2, tam ) ; }
			if ( (tam >= 13) && (tam <= 15) ){
				campo.value = cnpj.substr( 0, tam - 12 ) + '.' + cnpj.substr( tam - 12, 3 ) + '.' + cnpj.substr( tam - 9, 3 ) + '/' + cnpj.substr( tam - 6, 4 ) + '-' + cnpj.substr( tam - 2, tam ) ; }
			if ( (tam >= 16) && (tam <= 18) ){
				campo.value = cnpj.substr( 0, tam - 15 ) + '.' + cnpj.substr( tam - 15, 2 ) + '.' + cnpj.substr( tam - 12, 3 ) + '.' + cnpj.substr( tam - 9, 3 ) + '/' + cnpj.substr( tam - 6, 4 ) + '-' + cnpj.substr( tam - 2, tam ) ;}
		}
	
	function somaCampos(array, res, tam) {
		var a = parseFloat("0");
		i = 0;
		for(i = 0; i < array.length; i++) {
			if (array[i].value == "") {
				a = a + parseFloat("0");
			}
			else {
				vl = array[i].value;
				vl = vl.replace( "/", "" );
				vl = vl.replace( "/", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ",", "." );
				a = parseFloat(a) + parseFloat(vl);
			}
		}
		res.value = a.toFixed(2);
		formataValor(res, tam);
	}
	
	 
	function subtraiCampos(array, res, tam) {		
		var a = parseFloat(array[0].value);
		i = 1;
		for(i = 1; i < array.length; i++) {
			if (array[i].value != "") {
				vl = array[i].value;
				vl = vl.replace( "/", "" );
				vl = vl.replace( "/", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ",", "." );
				a = parseFloat(a) - parseFloat(vl);
			}
		}
		res.value = a.toFixed(2);
		formataValor(res, tam);
	}
	
	
	function multiplicaCampos(array, res, tam) {
		var a = parseFloat("1");
		i = 0;
		for(i = 0; i < array.length; i++) {
			if (array[i].value == "") {
				a = a * parseFloat("1");
			}
			else {
				vl = array[i].value;
				vl = vl.replace( "/", "" );
				vl = vl.replace( "/", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ".", "" );
				vl = vl.replace( ",", "." );
				a = parseFloat(a) * parseFloat(vl);
			}
		}
		res.value = a.toFixed(2);
		formataValor(res, tam);
	}

	
    // Trim whitespace from left and right sides of s.
    function trim(s) {
        return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
    }	
    
    
    function enableFormElements(form){
       len = form.elements.length;
       for( i=0 ; i<len ; i++) {
          if ( (form.elements[i].type=='button') || (form.elements[i].type=='submit')){
                form.elements[i].disabled=false;
          }
       }
    } 
    
    
    documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {	
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {	
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;
	
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}
    

// Função que calcula o dígito da matrícula do funcionário.
var _tamanhoMatricula = 6;
	
function gerarDigitoMatricula(campoMatricula, campoDigito)
{
	var matricula = campoMatricula.value;

	if(matricula.length > 0)
	{
		var numDigito = 0;
		matricula = formatarMatricula(matricula);
		
		cont = 1;
		for(var i=0; i < _tamanhoMatricula;i++)
		{
			var num = new Number(matricula.charAt(i));
			
			numDigito = numDigito + (num * cont);
			
			cont++;
		}
		
		numDigito = numDigito % 10;
		
		numDigito = (numDigito != 0) ? 10 - numDigito : numDigito;
		
		campoMatricula.value = matricula;
		campoDigito.value = numDigito;
	}
	else
	{
		campoDigito.value = "";
	}
}

function formatarMatricula(matricula)
{
	while(matricula.length < _tamanhoMatricula)
	{
		matricula = "0" + matricula;
	}
	
	return matricula;
}
