/* formato corrente com arredondamento e 2 casas*/
function currencyFormat(fld,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;
	var milSep = '.';
	var decSep=',';
	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

/* para qualquer mascara
	deficiencia -> 2 campos de mascara juntos exemplo 123%%456
*/
function mask_ed(form, format,e) {

	var input = form.value;
	var sem_mascara = '';
	var com_mascara = '';
	var cont_mascara=0;
	var tecla = new Array();

	//tecla[8] = 1;  // backspace
	tecla[16] = 1; // shift
	tecla[17] = 1; // ctrl
	tecla[18] = 1; // alt
	tecla[32] = 1; // espaco
	tecla[37] = 1; // seta
	tecla[38] = 1; // seta
	tecla[39] = 1; // seta
	tecla[40] = 1; // seta
	tecla[46] = 1; // delete

	if(input.length > 0) {
		//alert (window.event ) ;
		var key = window.event ? e.keyCode : e.which;
		if (key && tecla[e.keyCode] != 1) { 
			for (cont=0;cont<input.length;cont++){
				if (format.charAt(cont)!='#'){ 
					if (input.charAt(cont)!=format.charAt(cont)){ 
						sem_mascara = sem_mascara + input.charAt(cont);										
					}
				} else {
					sem_mascara = sem_mascara + input.charAt(cont);					
				}
			}


			for (cont=0;cont<sem_mascara.length;cont++){
				if (format.charAt(cont_mascara)!='#'){ 
					com_mascara = com_mascara + format.charAt(cont_mascara) + sem_mascara.charAt(cont);
					cont_mascara=cont_mascara+2;
				} else {
					com_mascara = com_mascara + sem_mascara.charAt(cont);
					cont_mascara++;
				}				
			}
			form.value = com_mascara; 
		}
	}
}

/*FUNCAO PARA CONVERTER UM VALOR NUMERO PARA MOEDA SEM ARREDONDAMENTO*/
/*minimo de casas decimais=1*/
function formatoCorrente (valor,decimais,pontoDecimal,pontoMilhar){	

	valorFinal="";
	valorDecimal="";
	valorInteiroTmp="";
	valorInteiroInv="";
	valorInteiro="";	
	addPonto=1;	
	/* adicionar funcao para converter para numero inteiro*/
	valor = removerPonto(valor);
	valor = tirarZerosEsquerda(valor);
	/* iniciar a formatacao caso o tamanho seja maior que o total de decimais */
	if (valor.length > decimais){
		/* iniciar subtraindo o valor decimal*/	
		valorDecimal=valor.substr((valor.length-decimais),decimais);
		
		/*tratar valor inteiro*/	
		valorInteiroTmp=valor.substr(0,(valor.length-decimais));
		
		/*adicionar separador milhar ao inteiro*/
		//alert (valorInteiroTmp);
		for (cont=1;cont<=valorInteiroTmp.length;cont++){
			valorInteiroInv=valorInteiroInv+valorInteiroTmp.substr((valorInteiroTmp.length-cont),1);
			//alert (valorInteiroInv+"="+(valorInteiroTmp.length-cont)+"=>"+valorInteiroTmp.substr((valorInteiroTmp.length-cont),1));
			if (addPonto==3 && valorInteiroTmp.length!= cont){
				valorInteiroInv=valorInteiroInv+pontoMilhar;
				addPonto=0;
			}
			addPonto++;
		}

		/* o valor inteiro neste ponto esta invertido do ultimo para o primeiro retornar ao lado certo*/
		for (cont=valorInteiroInv.length;cont>=0;cont--){
			//alert (valorInteiroInv.substr((valorInteiroTmp.length-cont),1));
			valorInteiro=valorInteiro+valorInteiroInv.substr((cont),1);
		}		

		if (valorDecimal==""){valorDecimal="0";}
		valorFinal=valorInteiro+pontoDecimal+valorDecimal
	}else{
		/* adiciona valor equivalente ao tamanho do inteiro + decimal*/
		for (cont=0;cont<decimais-valor.length;cont++){
			valorDecimal=valorDecimal+"0";
		}
		valorFinal="0"+pontoDecimal+valorDecimal+valor;
	}
	
	return valorFinal;
}

function removerPonto(str){

	str=replaceChars(str,'.','');
	str=replaceChars(str,',','');
	return str;
}


function replaceChars(entry,out,add) {
	temp = "" + entry; 
	while (temp.indexOf(out)>-1) {
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + 
		temp.substring((pos + out.length), temp.length));
	}
	return temp;
}

function tirarZerosEsquerda(STR){

  var sAux='';
  var i=0;
  STR=new String(STR);
  
  while (i < STR.length ){
    if ((STR.charAt(i)!='.') && (STR.charAt(i)!=',')){
	  sAux += STR.charAt(i);
    }
	i++
  }  
  
  STR = new String(sAux);
  sAux = '';
  i=0;
  
  while (i < STR.length ){
    if (STR.charAt(i) != '0'){
      sAux = STR.substring(i,STR.length);
	  i = STR.length;
	}
    i++;
  }
  
  return  sAux;
}

function keyInterger( e ) {
  /*******************************************************************************
  	keyInterger ( tecla )
  	Funçao para permitir a digitação somente de números.
  	A funçao dá suporte para números do tipo moeda, portando valores como:
  	17.50  ou 17,50 são permitidos.
  	TECLAS PERMITIDAS
	  -> 48 a 57  => Números do teclado alfa numérico
	  -> 96 a 105 => Números do teclado numérico
	  -> 46 => Tecla [Delete]
	  -> 8 => Tecla [Back space]
	  -> 37 a 40 => setas
	  -> 9 => tab
	  -> 17 => ctrl
	  EXEMPLO:onKeyDown="return keyInterger( event );"	 
  ********************************************************************************/
  var tecla = e.keyCode? e.keyCode : e.wich;

  if( (tecla >= 46 && tecla <= 57) || 
	  (tecla >= 96 && tecla <= 105)||
	  (tecla >= 37 && tecla <= 40)||
	  (tecla==46 ) ||
	  (tecla==8 ) ||
	  (tecla==9 ) ||
	  (tecla==17 ) ) {
    return true;
  }else{
  	return false;
  }
}

/*bloqueando history.back com backspace*/
function noBackspace(e) {
	if (!e){
		var item=event.srcElement.tagName;
		var tecla=event.keyCode;
	}else{
		var item=e.target.tagName;
		var tecla=e.keyCode;
	}
	if (tecla == 8 && item != "INPUT" && item != "TEXTAREA") {
		if (!e){
			event.cancelBubble = true;
			event.returnValue = false;
		}else{
			e.cancelBubble = true;
			return false;		
		}
	}
}


function HideShow(obj) {
   
	var htm=document.getElementById(obj);	
	if (htm!=null){
		if (htm.style.display=="" || htm.style.display=="inline" || htm.style.display=="block"){
			htm.style.display='none';
		}else{
			htm.style.display='block';
		}
	}


}
function HideShowTrocar(obj1,obj2){
	HideShow(obj1);
	HideShow(obj2);	
}

document.onkeydown = noBackspace;


function checkPeriodo( objFrm, dataInicio, dataTermino ){
/*********************************************************************************
	VALIDARPERIODO( FORM, DATA1, DATA2 );
		Função genérica para validação de período entre datas.
		Tem como objetivo verificar se a data de término é menor que
		a data de inicio do período.

	Exemplo de como chamar a função:
		<input type="button" name="botao" value="! validar !" onClick="checkPeriodo( frm, 'fldDataIni', 'fldDataFim' );">

	Nota: Veja que os campos aonde estão as datas são passados como string comum.
***********************************************************************************/
	var dtIni, dtFim;
	var ctlDt1, ctlDt2;
	// obter o value do campo
	var dtInicio	= eval( "objFrm." + dataInicio );
	var dtTermino	= eval( "objFrm." + dataTermino );

	// retirar a barra de separação para transformar
	// em um numero inteiro
	// ex.:  27/01/1982 - 27011982
	ctlDt1	= dtInicio.value.split("/");
	ctlDt2	= dtTermino.value.split("/");

	// para validar o período deve-se iniciar do Ano para o Dia
	dtIni	= ctlDt1[2] + ctlDt1[1] + ctlDt1[0];
	dtFim	= ctlDt2[2] + ctlDt2[1] + ctlDt2[0];

	if ( parseInt(dtIni) > parseInt(dtFim) ){
		alert( "Período inválido!\nA data final é menor que a data de inicio do período." );
		dtInicio.focus();
		return false;
	}
	return true;
}