// AO CLICAR ENTER FAZ SUBMIT
// <input type="text" onKeyPress="checkEnter(event)"> 


function checkEnter(e){ //e is event object passed from function invocation
//var characterCode literal character code will be stored in this variable

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
document.forms[0].submit() //submit the form
return false 
}
else{
return true 
}

}


//   DURANTE DIGITAÇÃO MUDA PARA MAIÚSCULA

//onKeyUp="maiusculas(this.form.name,this.name,this.value)"
	function maiusculas(form,cp,vl){
		eval("document."+form+"."+cp+".value='"+vl.toUpperCase()+"'");
	}
	
//MUDA DE CAMPO SE CHEGAR AO LIMITE
	
//onKeyPress="muda_de_campo(this.name,this.value,this.form.name,'telefone_1',2)"
	function muda_de_campo(campo,valor,form,mudar_para,limite){
		//Muda automaticamente de campo após x caracteres	
		if (valor.length >= limite) {
			//muda para o próximo campo
			eval("document."+form+"."+mudar_para+".focus()");
		}
	}	
	

	
	function mostra_hoje(nome_campo,nome_form) {
		dt_atual = new Date();
		dia = dt_atual.getDate();
		if (dia < 10) dia = "0" + dia;
		mes = dt_atual.getMonth() + 1;
		if (mes < 10) mes = "0" + mes;
		ano = dt_atual.getFullYear();
		dt_atual = dia + "/" + mes + "/" + ano;
		eval("document."+nome_form+"." + nome_campo + ".value = dt_atual");
	}	
	
	
	
	
//onKeyup="FormataHora(this.value,this.name)" onblur="vld_hora(this.value,this.name)"
	vr_antigo = "";
	function FormataHora(form,valor,campo) {
		//alert(form)
		vr_atual = "";
		tam_atual = 0;
		tam_antigo = 0;
		vr_atual = eval("document."+form+"."+campo+".value");
		tam_atual = eval("document."+form+"."+campo+".value.length");		
		tam_antigo = vr_antigo.length;
		if (tam_atual == 2 && tam_antigo < tam_atual) eval("document."+form+"."+campo+".value='"+vr_atual + ":'");
		vr_antigo = vr_atual;
	}
	
	//onKeyup="FormataHora(this.value,this.name)" onblur="vld_hora(this.value,this.name)"
	function vld_hora(form,valor,campo) {
		vr_atual = "";
		erro = "";
		tam = 0;
		vr = eval("document."+form+"."+campo+".value");
		tam = eval("document."+form+"."+campo+".value.length");		
		if (tam != 5 && tam != 0) {
			alert("Atenção!\nA hora deve estar no formato hh:mm.");
			eval("document."+form+"."+campo+".focus()");
			eval("document."+form+"."+campo+".select()");
		} else {
			hora = vr.substring(0,2);
			minuto = vr.substring(3,5);
			if (isNaN(hora)) erro += "\nA hora deve ser um número de 00 a 24."
			if (isNaN(minuto)) erro += "\nO valor dos minutos deve ser um número de 00 a 24."
			if (!isNaN(hora) && parseInt(hora) > 24) erro += "\nA hora deve estar dentro de um intervalo válido (00 a 24)."
			if (!isNaN(minuto) && parseInt(minuto) > 59) erro += "\nO valor dos minutos deve estar dentro de um intervalo válido (00 a 59)."
		}
		if (erro != "") {
			alert("Atenção!!" + erro);
			eval("document."+form+"."+campo+".focus()");
			eval("document."+form+"."+campo+".select()");			
		}
	}	
	
	
	
	//onKeyup="FormataData(this.value,this.name,this.form.name)" onblur="vld_data(this.value,this.name,this.form.name)"
	function FormataData(form,valor,campo) {
		vr_atual = "";
		tam_atual = 0;
		tam_antigo = 0;
		vr_atual = eval("document."+form+"."+campo+".value");		
		tam_atual = eval("document."+form+"."+campo+".value.length");		
		tam_antigo = vr_antigo.length;
		if ((tam_atual == 2 || tam_atual == 5) && tam_antigo < tam_atual) {
			eval("document."+form+"."+campo+".value='"+vr_atual + "/'");
		}
		vr_antigo = vr_atual;
	}	
	
	function vld_data(form,valor,campo) {
		vr_atual = "";
		erro = "";
		tam = 0;
		vr = eval("document."+form+"."+campo+".value");
		tam = eval("document."+form+"."+campo+".value.length");		
		if (tam != 10 && tam != 0) {
			alert("Atenção!\nA data deve estar no formato dd/mm/aaaa.");
			eval("document."+form+"."+campo+".focus()");
			eval("document."+form+"."+campo+".select()");
		} else if (tam == 10 && tam != 0){
			dia = vr.substring(0,2);
			mes = vr.substring(3,5);
			ano = vr.substring(7,10)
			ano_ref = new Date();
			if (isNaN(dia)) erro += "\nO dia deve ser um número."
			if (isNaN(mes)) erro += "\nO mês deve ser um número de 01 a 12."
			if (isNaN(ano)) erro += "\nO ano deve ser um número válido de quatro dígitos."
			mes = (mes * 10) /10
			//alert(mes)
			if (!isNaN(mes) && (parseInt(mes) > 0 && parseInt(mes) <= 12)) {
				verifica_mes(mes,ano);
				if (parseInt(ultimo_dia) == 0 || parseInt(dia) > ultimo_dia) {
					erro += "\nO dia do mês deve ser um valor válido para o mês atual.";
				}
			} else {
				//alert(parseInt(mes))
				erro += "\nO mês deve estar dentro de um intervalo válido (01 a 12)."		
			}
		}
		if (erro != "") {
			alert("Atenção!!" + erro);
			eval("document."+form+"."+campo+".focus()");
			eval("document."+form+"."+campo+".select()");			
		}
	}		
	
	function verifica_mes(mes,ano){
		ultimo_dia = 0;
		switch (parseInt(mes)) {
			case 1 :
			case 3 :
			case 5 :
			case 7 :
			case 8 :
			case 10 :
			case 12 :			
				ultimo_dia = 31;
				break;
			case 4 :
			case 6 :
			case 9 :
			case 11 :									
				ultimo_dia = 30;
				break;
			case 2 :
				ultimo_dia = 28;
				
				if (ano % 4 == 0) {
					ultimo_dia = 29;
				} else {
					ultimo_dia = 28;
				}
				if ((ano % 100 == 0) && (ano % 400 != 0)) {
					ultimo_dia = 28;
				}				
				break;
			default :
				ultimo_dia = 0;
				break;
		}
	}
	
	
	
	
//onClick="limpa_campos(this.form)"
	function limpa_campos(formulario){
		resp = confirm("Tem certeza que deseja limpar os campos do formulário?");
		if (resp){
			itens_form = formulario.length;
			for(i=0;i<itens_form;i++){
				tipo = formulario.elements[i].type;
				nome = formulario.elements[i].name;
				if (tipo == "select-one"){
					formulario.elements[i].options[0].selected=true;
				}
				if (tipo == "checkbox" || tipo == "radio"){
					formulario.elements[i].checked=false;
				}
				if (tipo == "text" || tipo == "textarea"){
					formulario.elements[i].value = "";
				}
				if (nome == "id"){
					formulario.elements[i].value = "";
				}				
			}
		}
	}		
	
	
function valida_login(){
	
	
		login = document.form1.txtusuario.value;
		
		senha = document.form1.txtsenha.value;
		if (login == "" && senha == "") {
			alert("É preciso preencher os campos de CNPJ / CPF e Senha para continuar!");
			document.form1.txtusuario.focus();
		} else if (login == ""){
			alert("É preciso preencher o campo CNPJ / CPF para continuar!");
			document.form1.txtusuario.focus();		
		} else if (senha == ""){
			alert("É preciso preencher o campo Senha para continuar!");
			document.form1.txtsenha.focus();		
		} else {
			document.form1.submit();
		}
	}				
	
	
function valida_login2(){
	
	
		login = document.form1.txtusuario.value;
		
		senha = document.form1.txtsenha.value;
		senha2 = document.form1.txtsenha2.value;
		if ((login == ""||login==null) && senha == "") {
			alert("É preciso preencher os campos de CNPJ / CPF e Senha para continuar!");
			document.form1.txtusuario.focus();
		} else if (login == "" || login==null){
			alert("É preciso preencher o campo CNPJ / CPF para continuar!");
			document.form1.txtusuario.focus();		
		} else if (senha == "" || senha==null){
			alert("É preciso preencher o campo Senha Anterior para continuar!");
			document.form1.txtsenha.focus();		
		} 
		 else if (senha2 == "" || senha2==null){
			alert("É preciso preencher o campo Nova Senha para continuar!");
			document.form1.txtsenha2.focus();		
		}
		
		else {
			document.form1.submit();
		}
	}					
	
	
	
//onKeydown="JavaScript:FormataCNPJ(this,event)"
function FormataCNPJ(Campo, teclapres){
	//alert(Campo);
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");
	tam = vr.length + 1 ;
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
		
}	


	function validaCNPJ(CNPJ) {
		erro = new String;
		if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		}
		//substituir os caracteres que nao sao numeros
		if(document.layers && parseInt(navigator.appVersion) == 4){
			x = CNPJ.substring(0,2);
			x += CNPJ.substring(3,6);
			x += CNPJ.substring(7,10);
			x += CNPJ.substring(11,15);
			x += CNPJ.substring(16,18);
			CNPJ = x;	
		} else {
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace("-","");
			CNPJ = CNPJ.replace("/","");
		}
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";	
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]); 
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			//alert(erro);
			//return false;			
		} else {
			//alert("CNPJ valido!");
		}
		return erro;
	}	



	//onblur="apenas_numeros(this.value, this.name,this.form.name) - ideal para campo CEP"
	function apenas_numeros(x,campo,form){
		tam = x.length; erro = 0;
		if(tam > 0){
			for(i=0;i<x.length;i++){
				crt = x.charAt(i);
				if (isNaN(crt)) {
					//alert("Digite apenas números.");
					seleciona = "document."+form+"."+ campo +".value=''";
					eval(seleciona);
					erro++;
					break;					
				}
			}
		}
		return erro;
	}
	
	
	
	//onBlur="valida_cpf(this.value,this.name,this.form.name)"
	function valida_cpf(vl,campo,form){
		resp = isCPF(vl);
		if (!resp && vl.length > 0){
			msg = "CPF Inválido!\nVerifique o valor digitado e tente novamente.";	
			alert(msg);
			//alert("document."+form+"."+campo+".value");
			eval("document."+form+"."+campo+".select()");
			
			eval("document."+form+"."+campo+".focus()");
		}
	}
	
	
	//Função de validação de CPF
	function isCPF(st) {
		if (st == "")
		  return (false);
		l = st.length;
		
		//alterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
		if ((l == 9) || (l == 8)){
		   for (i = l ; i < 10; i++){
			  st = '0' + st
		   }
		}
		
		l = st.length;
		st2 = "";
		for (i = 0; i < l; i++) {
		  caracter = st.substring(i,i+1);
		  //if ((caracter >= '0') && (caracter <= '9'));
		  if (!isNaN(caracter)) st2 = st2 + caracter;
		}
		//alert(st2);
		if ((st2.length > 11) || (st2.length < 10))
		   return (false);
		if (st2.length==10)
		   st2 = '0' + st2;
		digito1 = st2.substring(9,10);
		digito2 = st2.substring(10,11);
		digito1 = parseInt(digito1,10);
		digito2 = parseInt(digito2,10);
		sum = 0; mul = 10;
		for (i = 0; i < 9 ; i++) {
			digit = st2.substring(i,i+1);
			tproduct = parseInt(digit ,10) * mul;
			sum += tproduct;
			mul--;
		}
		dig1 = ( sum % 11 );
		if ( dig1==0 || dig1==1 )
		   dig1=0;
		else
		  dig1 = 11 - dig1;
		if (dig1!=digito1)
		  return (false);
		sum = 0;
		mul = 11;
		for (i = 0; i < 10 ; i++) {
			digit = st2.substring(i,i+1);
			tproduct = parseInt(digit ,10)*mul;
			sum += tproduct;
			mul--;
		}
		dig2 = (sum % 11);
		if ( dig2==0 || dig2==1 )
		  dig2=0;
		else
		  dig2 = 11 - dig2;
		if (dig2 != digito2)
		  return (false);
		return (true);
	}		
			
			

	//onBlur="valida_rg(this.value,this.name,this.form.name)"
	function valida_rg(vl,campo,form){
		erro_num = apenas_numeros(vl,campo);
		if (erro_num == 0){
			//O usuário digitou apenas números
			resp = isRG(vl);
			if (!resp && vl.length > 0){
				msg = "Número de RG Inválido!\nVerifique o valor digitado e tente novamente.";	
				alert(msg);
				eval("document."+form+"."+campo+".select()");
				eval("document."+form+"."+campo+".focus()");
			}			
		}
	}
	
	function isRG(numero){
		 /*
		 ##  Igor Carvalho de Escobar
		 ##    www.webtutoriais.com
		 ##   Java Script Developer
		 */
		 resp = true;
		 var numero = numero.split("");
		 tamanho = numero.length;
		 vetor = new Array(tamanho);
	
		if(tamanho>=1){
			vetor[0] = parseInt(numero[0]) * 2; 
		}
		
		if(tamanho>=2){
			vetor[1] = parseInt(numero[1]) * 3; 
		}
	
		if(tamanho>=3){
			vetor[2] = parseInt(numero[2]) * 4; 
		}
	
		if(tamanho>=4){
			vetor[3] = parseInt(numero[3]) * 5; 
		}
		
		if(tamanho>=5){
			vetor[4] = parseInt(numero[4]) * 6; 
		}
		
		if(tamanho>=6){
			vetor[5] = parseInt(numero[5]) * 7; 
		}
		
		if(tamanho>=7){
			vetor[6] = parseInt(numero[6]) * 8; 
		}
		if(tamanho>=8){
			vetor[7] = parseInt(numero[7]) * 9; 
		}
		if(tamanho>=9){
			vetor[8] = parseInt(numero[8]) * 100; 
		}
	
		total = 0;
	
		if(tamanho>=1){
			total += vetor[0];
		}
		if(tamanho>=2){
			total += vetor[1]; 
		}
		if(tamanho>=3){
			total += vetor[2]; 
		}
		if(tamanho>=4){
			total += vetor[3]; 
		}
		if(tamanho>=5){
			total += vetor[4]; 
		}
		if(tamanho>=6){
			total += vetor[5]; 
		}
		if(tamanho>=7){
			total += vetor[6];
		}
		if(tamanho>=8){
			total += vetor[7]; 
		}
		if(tamanho>=9){
			total += vetor[8]; 
		}
	
		resto = total % 11;
		if(resto!=0){
			resp = false;
			//alert("RG Inválido!");
		}
		return resp;
	}
	

// TRANSFORMA VALOR EM BR

function floatUS2BR(valor) {
        valor = valor.toString();
        pos = valor.indexOf(".", 0);
        if(pos >= 0) {
            valor = valor.substr(0, pos) + "," + valor.substr(pos + 1, valor.length - pos);
        }
        return valor
    }

// TRANSFORMA VALOR EM US

function floatBR2US(valor) {
        valor = valor.toString();
        pos = valor.indexOf(",", 0);
        if(pos >= 0) {
            valor = valor.substr(0, pos) + "." + valor.substr(pos + 1, valor.length - pos);
        }
        return valor
    }	
	

    function somaCampos(campo, campo1, campo2) {
        campo1 = parseFloat("0" + floatBR2US(campo1.value));
        campo2 = parseFloat("0" + floatBR2US(campo2.value));
        //alert(campo1+'*'+campo2);
        campo.value = floatUS2BR(campo1 * campo2);
    }	

// CALCULA VALOR FINAL COM DESCONTO OU NÃO	
	
   function calculoPecas(quantidade, valorUnitario, total, desconto, totalLiquido) {
        campo1 = parseFloat("0" + floatBR2US(quantidade.value));
        campo2 = parseFloat("0" + floatBR2US(valorUnitario.value));
        //alert(campo1+'*'+campo2);
        total.value = floatBR2US(floatUS2BR(campo1 * campo2));
        valorDesconto = total.value * (desconto.value / 100);
        //alert(total.value+' - '+valorDesconto);
        totalLiquido.value = total.value - valorDesconto;
    }	
	
	
	
function formata_float(obj) {
	var len;
	var pos;
	if (obj.value == '') {
		obj.value = '0,00';
		return;
	}
	pos = obj.value.indexOf(',');
	if (pos != -1) {	
		//há virgula
		len = obj.value.length;
		if (len - pos >= 4) {			
			obj.value = obj.value.substring(0, pos + 3);
		}
		if ((len - pos  == 1) || (len - pos) == 2)
			obj.value = obj.value + '0';
	} else {
		obj.value = obj.value + ',00';
	}
}

// MOSTRAR E ESCONDER DIV

function Show(div) {
	document.all[div].style.visibility = 'visible';
}
function Hide(div) {
	document.all[div].style.visibility = 'hidden';
}



// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
	
// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}





// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.

///////  You can also put this into the <SELECT> object as follows:
///////   onDblClick="moveSelectedOptions(this,this.form.target)

//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			to.options[to.options.length] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}


// ADICIONAR ZEROS À ESQUERDA OU À DIREITA
// COMO CHAMAR:
//N = 123
//N.zeroFormat(5, true, true) = 12300 (
//N.zeroFormat(5, true) = 00123
//N.zeroFormat(5) = 00000123 
//Number.zeroFormat(n: Integer, [fill: Boolean = false], [right: Boolean = false]): String 
//Retorna o número em forma de string com zeros à esquerda ou à direita. 
//nquantidade de zeros a ser adicionada 
//fill se "true", serão adicionados zeros ao número até que se obtenha no mínimo "n" digitos, caso //contrário será sempre adicionado a quantidade especificada de zeros 
//right se "true" os zeros serão concatenados à direita, caso contrário, à esquerda 



/*
**************************************
* zeroFormat Function v1.1           *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
Number.prototype.zeroFormat = function(n, f, r){
    return n = new Array((++n, f ? (f = (this + "").length) < n ? n - f : 0 : n)).join(0), r ? this + n : n + this;
};



// QUEBRA DE PALAVRAS EM UM TEXTAREA
// COMO USAR:
// String.wordWrap(maxLength: Integer, [breakWith: String = "\n"], [cutType: Integer = 0]): String 
//Retorna a string com os caracteres/palavras extras "quebrados". 
//maxLengthquantidade máxima de caracteres por linha 
//breakWtihstring que será adicionada onde houver necessidade de quebrar a linha 
//cutType 0 = palavras mais longas que "maxLength" não serão quebradas 
//1 = palavras serão quebradas quando necessário 
//2 = qualquer palavra que ultrapasse o limite será quebrada 

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/wordwrap [v1.1]

String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};
	
	
	
	
	
function floatUS2BRgil(valor) {
        valor = valor.toString();
        pos = valor.indexOf(".", 0);
        if(pos >= 0) {
            valor = valor.substr(0, pos) + "," + valor.substr(pos + 1, valor.length - pos);
        }
		else{
			valor = valor+',00';
			}
		
        return valor
    }	
	
// onKeyPress="checar_caps_lock(event)"
// para aparecer na página o aviso:
// <div id="aviso_caps_lock" style="visibility: hidden">
// <table border="0" style="background-color: #FFFFCC; border: 1 solid #FF0000">
// <tr>
// <td width="100%">Atenção: O Caps Lock esta ativado!</td>
//  </tr>
// </table> </div>

function checar_caps_lock(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		document.getElementById('aviso_caps_lock').style.visibility = 'visible';
	}
	else {
		document.getElementById('aviso_caps_lock').style.visibility = 'hidden';
	}
}	