function showText(ob, txt){
	if (ob.value == "") {
		ob.value = txt;
	}
}

function clearText(ob, txt){
	if (ob.value == txt) {
		ob.value = "";
		ob.select();
	}
}

function isNumberKey(Key){
       var charCode = (Key.which) ? Key.which : event.keyCode
       if (charCode < 48 || charCode > 57)
          return false;
       return true;
}

function formatFloat(valor){
	var nvalor = valor.replace('.',',');
	return nvalor.substring(0,nvalor.length - 3);
}

function formatMoney(valor){
var result = new String(valor);

  if ( result.lastIndexOf(",") != -1 ) {
     return valor;
  } else {
     result = parseFloat(valor).format(2, ",", ".");
     return result;
  }
}

function toFloat(price){
	price = price.replace('R', '');
	price = price.replace('r', '');
	price = price.replace(' ', '');
	price = price.replace('$', '');
	price = price.replace('.', '');
	price = price.replace(',', '.');
	
	price = parseFloat(price);
	return(price);
}

function mascararDinheiro(e, obj)
{
   sKey = e.keyCode ? e.keyCode : e.which ;

   if (
         (sKey>=48 && sKey<=57) // [0-9]
       || sKey==8 // backspace
       || sKey==46 // delete
       || sKey==9 // TAB
       || (sKey>=35 && sKey<=40) // home, end, setas
       || (sKey>=96 && sKey<=105) // [0-9] teclado numerico
      ) {

         valor = obj.value.replace(",","").replace(".",""); // remove pontos de separação caso existam

         while(true) { // remove os zeros à esquerda
             tamanho = valor.length;

             if(valor.substr(0,1) != 0 || tamanho == 0)
                 break;
             else
                 valor = valor.substr(1);
         }

         tamanho = valor.length;
         
         inteiros = valor.substr(0,tamanho-2);
         decimais = valor.substr(tamanho-2,2);

         if (inteiros.length==0) inteiros = "0";
         if (decimais.length==0) decimais = "00";
         if (decimais.length==1) decimais = "0"+decimais;
         
         valor = inteiros+","+decimais
         obj.value = valor;

         return true;

   } else {
		if (window.event) // para IE
		{
			e.cancelBubble = true;
			e.returnValue = false;
		}
		else // para mozilla
		{
			e.stopPropagation();
			e.preventDefault ();
		}

		return false;
   }
}

/*Funcoes Genéricas*/

//Funcao para caixa alta
function caixaalta(Wparam){
	Wparam.value = Wparam.value.toUpperCase();
}

//Funcao para caixa baixa
function caixabaixa(Wparam){
	Wparam.value = Wparam.value.toLowerCase();
}
	
//Função para obrigar a digitação de números com número minimo de digitos
function apenasnumerodigito(wparam, digitos){
	if (wparam.value==""){
		return false;
	}
	if (isNaN(wparam.value)){
		alert("Este campo deve conter apenas números!");
		wparam.focus();
		return false;
	}		
	
	if (wparam.value.length < digitos){
		alert("Este campo deve conter "+digitos+" digitos!");
		wparam.focus();
		return false;
	}		
}

//Função para obrigar a digitação de números
function apenasnumero(wparam){
	if (wparam.value==""){
		return false;
	}
	if (isNaN(wparam.value)){
		alert("Este campo deve conter apenas números!");
		wparam.focus();
		return false;
	}		
}

//Função para Validar Data
function validaData(data) {
    var ok = true;
	var dia, mes, ano;
    if (!(data.match(/^[0-9]{2,2}[./-]{0,1}[0-9]{2,2}[./-]{0,1}[0-9]{4,4}$/))) {
        ok = false;
    }
	if((data.charAt(2) != '/') || (data.charAt(5) != '/')){
		ok =  false;
	}
    data = retiraCaracter(retiraCaracter(retiraCaracter(data, '.'), '-'), '/');
    dia = parseInt(data.substr(0,2));
    mes = parseInt(data.substr(2,2));
    ano = parseInt(data.substr(4,4));
    if ((mes < 1) || (mes > 12)) {
        ok =  false;
    }
    if ((dia < 1) || (dia > 31)){
        ok =  false;
    }
    if ((mes == 2) || (mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) {
        if (dia > 30) {
            ok =  false;
        }
        if (mes == 2) {
            if (ano % 4 == 0) {
                if (dia > 29) {
                    ok =  false;
                }
            }
            else {
                if (dia > 28) {
                    ok =  false;
                }
            }
        }
    }
	if(!ok) alert('Data inválida!');
}

function validaDataNascimento( campo, idadeMinima ){

	wparam = campo;
	
	if (wparam.value =="")
	{
		return false;
	}

	var idade = idadeMinima;
	
	erro=0;
	hoje = new Date(); /* data de hoje */
	anoAtual = hoje.getFullYear() - idade; /* ano atual - idade permitida */
	barras = wparam.value.split("/"); /* cria um array separado pelas / */
	
	if (barras.length == 3)
	{
		dia = barras[0]; /* dia de nascimento */
		mes = barras[1]; /* mes de nascimento */ 
		ano = barras[2]; /* ano de nascimento */
		resultado = ( ! isNaN(dia) && (dia > 0) &&  /* dia tem q ser numero e maior q 0 */
					   (dia < 32)) && (!isNaN(mes) &&  /* dia tem q ser menor q 32 e mes tem q ser numero */
					   (mes > 0) && (mes < 13)) && /* mes tem q ser maior q 0 e mes tem q ser menor q 13 */
					   (!isNaN(ano) && (ano.length == 4) && /* ano tem q ser numero e ano tem q ter 4 digitos */
					   (ano <= anoAtual && ano >= 1920) ); /* ano tem q ser menor q ano atual e maior q 1920 */
					   
	     if(ano >= 1993)
	     {
			if (mes >= 4 && dia > 21)
			{
				alert("Idade mínima exigida de "+idade+" anos!");			
				wparam.select();
				wparam.focus();
				return false;
			}		  
		 }
	
	     if(ano >= 1991)
	     {
			if (mes >= 4 && dia > 21)
			{
				alert("Idade mínima exigida de "+idade+" anos!");			
				wparam.select();
				wparam.focus();
				return false;
			}		  
		 }
	
		if(!resultado)
		{ /* se o resultado não bater mostra mensagem para usuario */
			alert("Idade mínima exigida de "+idade+" anos!");
			wparam.select();
			wparam.focus();
			return false;
		}
	}
	else
	{
		alert("Data de nascimento não permitida para o Evento!");
		wparam.focus();
		return false;
	}
}

// mascara - colocar no evento onKeyUp passando o objeto como parametro
function mascara(obj, tipo){
	var saida = obj.value;
	var len   = saida.length;

	if(tipo == 0){ //Tipo Data dd/mm/aaaa
		if((len == 2) || (len == 5)) 
			obj.value = saida + '/';
	}
	
	if(tipo == 1){ //Tipo Hora hh:mm
		if(len == 2)
			obj.value = saida + ':';
	}

	if(tipo == 2){ //Tipo CEP 00.000-000
		if(len == 2)
			obj.value = saida + '.';
		if(len == 6)
			obj.value = saida + '-';
		
	}
	return true;
}

//Função para Confirmar a exclusão do registro
function confirmaExclusao(stringLink){
	if (confirm('Confirma a exclusão deste registro?')){
		location.href = stringLink; 
	}
}

function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, 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 - dec, 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 - dec, 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 ) ;}
} 

}


/*
Função para formatar os mais diversos valores, datas, horas, telefones, cpf, cnpj.... em fim
	Exemplo de Uso
	Data:<input type="text" size="20" onkeypress="return Formata2(this, '99/99/9999', event);">
	CPF:<input type="text" size="20" onkeypress="return Formata2(this, '999.999.999-99', event);">
	Telefone:<input type="text" size="20" onkeypress="return Formata2(this, '(99)9999-9999', event);">
	Código:<input type="text" size="20" onkeypress="return Formata2(this, '99-999', event);">
	
*/
function Formata2(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

sValue = objeto.value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
  bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
  bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

  if (bolMask) {
	sCod += sMask.charAt(i);
	mskLen++; }
  else {
	sCod += sValue.charAt(nCount);
	nCount++;
  }

  i++;
}

objeto.value = sCod;

if (nTecla != 8) { // backspace
  if (sMask.charAt(i-1) == "9") { // apenas números...
	return ((nTecla > 47) && (nTecla < 58)); } 
  else { // qualquer caracter...
	return true;
  } 
}
else {
  return true;
}
}

function contarTexto( inputTextID, labelID, limit )
{
	var limite = limit;
	var myTextArea  = document.getElementById(inputTextID);
	var myTextField = document.getElementById(labelID);

	if ( myTextArea.value.length > limite ) 
	{
		myTextArea.value = myTextArea.value.substr( 0, ( myTextArea.value.length - 1 ) );
	}
	else
	{
		myTextField.innerHTML = ( limite - myTextArea.value.length );
	}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}	
