/*funcao para setar funcoes a teclas */
function tecla_pressionada(evento,executar_funcao,tecla_esperada){         
   if(document.all) { // Internet Explorer
      tecla = evento.keyCode;}      
   else if(document.forms){ // Netscape      
      tecla = evento.which;                  
   }
   if(tecla==tecla_esperada){                  
      executar_funcao();
      return true;
   }
   return tecla;
}
/////////////////////////////////////////////////////////////////////////////////

/*funcao que retorna o mes por extensso a partir do numero do mes exemplo 01='Janeiro' */
function mes(numero_mes){            
   nome_mes = new Array("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");   
   return nome_mes[numero_mes];   
} 
//////////////////////////////////////////////////////////////////////////////////

/*funcao que retorna se campo texto e vazio ou a caracteres diferentes de espaços*/
function vazio(conteudo){      
   var retorno=false
   var contador=0 
   for (i=0;i<conteudo.length;i+=1){      
      if (conteudo.substr(i,1) == " "){
         contador+=1;	 
      }      
   }
   if(contador==conteudo.length){retorno=true;}
   return retorno;   
}
/////////////////////////////////////////////////////////////////////////////////

/*funcao para retornar c data e valida ou nao com mensagem*/
function data_validada(me,mostra_mensa){
	if(!vazio(me.value) && validadata(me.value) == false){                  
		if (mostra_mensa){
			alert("Data Inválida");	 	 	 
		}  
		return false;
	}
	return true;        
}
/////////////////////////////////////////////////////////////////////////////////

/*  funcao para validar datas em campo testo*/
function validadata(dateValue,mostra_mensa){    
    var month;
    var day;
    var year;    
   
//  Extracting the month day and year values from the data entered on the screen

    day         =   dateValue.substring(0,dateValue.indexOf('/'));    
    dateValue   =   dateValue.substring(dateValue.indexOf('/') + 1);
    month       =   dateValue.substring(0,dateValue.indexOf('/'));
    year        =   dateValue.substring(dateValue.indexOf('/') + 1);    

//  Checking if the day, month and year are numeric values

    if(isNaN(month) || isNaN(day) || isNaN(year))
    {
        return false;
    }

//  Checking for the boundary conditions

    if(month>12||month<1||day<1||year<1||year.length != 4)
    {
        return false;
    }

    if(month == 1   &&  day > 31)
    {
        return false;
    }

    if(month == 2)
    {
        if(year%4 == 0 && day > 29)
        {
            return false;
        }

        if(year%4 != 0   &&  day > 28)
        {
            return false;
        }

    }

    if(month == 3 &&  day > 31)
    {
        return false;
    }

    if(month == 4 && day > 30)
    {
        return false;
    }

    if(month == 5   && day > 31)
    {
        return false;
    }

    if(month == 6   &&  day > 30)
    {
        return false;
    }

    if(month == 7   &&  day > 31)
    {
        return false;
    }

    if(month == 8   &&  day > 31)
    {
        return false;
    }

    if(month == 9   &&  day > 30)
    {
        return false;
    }

    if(month == 10   &&  day > 31)
    {
        return false;
    }
    if(month == 11   &&  day > 30)
    {
        return false;
    }

    if(month == 12   &&  day > 31)
    {
        return false;
    }

    return true;
}
/////////////////////////////////////////////////////////////////////////////////


/**********************************************************************************
* Descrição.: formata um campo do formulário de 
* acordo com a máscara informada... 
* Parâmetros: - objForm (o Objeto Form) 
* - strField (string contendo o nome 
* do textbox) 
* - sMask (mascara que define o 
* formato que o dado será apresentado, 
* usando o algarismo "9" para 
* definir números e o símbolo "!" para 
* qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" 
* name="xxx"..... 
* onkeypress="return txtBoxFormat(document.form1, 'txthora', '99:99:99', event);"> 
* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99.999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* hora -> 99:99:99
* Tel Resid -> (99) 999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
* E por aí vai... 
***********************************************************************************/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
   var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;   
      
   if(document.all) { // Internet Explorer
      nTecla = evtKeyPress.keyCode;}      
   //else if(document.layers) { // Nestcape
   else if(document.forms){ // Netscape      
      nTecla = evtKeyPress.which;                  
   }
   sValue = objForm[strField].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( " ", "" );
   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++;
   } 
   objForm[strField].value = sCod;
   if (nTecla == 0) { //tab
      return true;
   }
   if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
         return ((nTecla > 47) && (nTecla < 58));
      } // números de 0 a 9
      else { // qualquer caracter...
         return true;
      }
   }
   else {
      return true;
   }   
}
/////////////////////////////////////////////////////////////////////////////////

function valida_teclas(tecla_pressionada){
   tecla_pressionada=tecla_pressionada.which;      
   var retorno=false;   
   if((tecla_pressionada > 32 && tecla_pressionada < 41) || (tecla_pressionada > 15  && tecla_pressionada < 21) || (tecla_pressionada == 44) || (tecla_pressionada ==  45) || (tecla_pressionada == 93) || (tecla_pressionada == 27) || (tecla_pressionada > 101 && tecla_pressionada < 124) || (tecla_pressionada == 144) || (tecla_pressionada == 145) || (tecla_pressionada == 222)){      
      retorno = false;
   }
   else{
      retorno = true;
   }   
   return retorno;   
}

function valida_formulario(tecla_pressionada){
   tecla_pressionada=tecla_pressionada.which;      
   var retorno=false;   
   //aspas simples, aspas duplas, sinal de < e >
   if(tecla_pressionada == 34 || tecla_pressionada == 39 || tecla_pressionada == 60 || tecla_pressionada == 62){
      retorno=false;
   }
   else{
      retorno=tecla_pressionada;
   }
   return retorno;
}
/////////////////////////////////////////////////////////////////////////////////

// funcao para transformar um vetor javascript em string serializada para o php
function ArrayToSerialize(pVetor,pDimensao){
   var Str=new String("a:"+pVetor.length+":{");
   if(pDimensao == null){pDimensao=2;}
   if(pDimensao == 2){
      for(i=0;i < pVetor.length;i+=1){      
         Str+="i:"+i+";";      
         Str+="a:"+pVetor[i].length+":{";
	 for(j=0;j < pVetor[i].length; j+=1){
	    Str+="i:"+j+";"
	    tipo=typeof(pVetor[i][j]); tipo=tipo.substr(0,1)
	    Str+=tipo+":"+pVetor[i][j].length+":"+'"';
	    Str+=pVetor[i][j]+'";';	    
	 }   
         Str+="}";
      }   
   Str+="}";   
   }   
   return Str;
}
///////////////////////////////////////////////////

//funcao para formatar mascara de campo texto para valor
function formata_valor(me,campo,evento,ptamanho,ponevento){
	valor = me[campo].value;
	retorno=false;
	if(ponevento==null){ponevento=true;}
	if(document.all) { // Internet Explorer
       ntecla = evento.keyCode;
    }else{ // Netscape      
       ntecla = evento.which;                  
    }

    if(ntecla == 0){ //tab
       retorno= true;
    }

    texto=me[campo].value;
	if(valor.length > ptamanho){
	   texto=valor.substr(0,ptamanho);
	}else{	       
	   //if(ntecla == 8 || ntecla == 46 || (ntecla > 95 && ntecla < 106) || (ntecla > 47 && ntecla < 58) || ponevento==false){ // backspace ou tecla numerica
	      passou=false;
		  texto="";
	      for(i=0;i<valor.length;i++){	  
		     if(valor.substr(i,1)!="," && valor.substr(i,1)!="."){
		        if((valor.substr(i,1)=="0" && passou==true) || (valor.substr(i,1)!="0")){			    
				   texto=texto+valor.substr(i,1);
				   passou=true;
			    }
	         }
	      }
	      contador=0;	
	      texto1="";		 	   
          if(texto.length > 2){	      
	   	     for(i<texto.length-1;i>0;i--){
			    if(i == texto.length-2){
			       texto1=texto.substr(texto.length-3,1)+","+texto.substr(texto.length-2);			   
			    }else if(i < texto.length-2){			 
				   contador=contador+1;
				   if(contador==3){
			          contador=0;
				      if(i+1<texto.length-2){
				         texto1=texto.substr(i-1,1)+"."+texto1;
				      }				
			       }else{			 	    
			          texto1=texto.substr(i-1,1)+texto1;
				   }
			    }				   			 			
		      }
		      texto=texto1;
		  }else{
		      if(texto.length == 1){
		         texto="0,0"+texto;
		      }else{
		         texto="0,"+texto;
		      }		   
		  }  
	   //}	   
   }
   me[campo].value=texto;        
   return retorno;
}
////////////////////////////////////////////////////////////////

/* funcao que procura dentro de uma string por um valor e substiu por outro */
function inverter(pvalor,pantigo,pnovo){
   if(pnovo==null){pnovo='';}
   retstr="";
   cont=0;
   for(i=0;i<pvalor.length;i++){
      if(pvalor.substr(i,1)!=pantigo){
	     retstr=retstr+pvalor.substr(i-cont,1);
	  }else{
	     retstr=retstr+pnovo;
	  }
   }
   return retstr;
}
///////////////////////////////////////////////////////////////

/*funcao para validar cpf e cnpj que retorno true ou false validados ou não*/
function checacpf(CPF,tipo) {
CPF=inverter(CPF,'.','');
CPF=inverter(CPF,'-','');
CPF=inverter(CPF,'/','');
CPF=inverter(CPF,'.','');
if(tipo=='cpf'){
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
	return true;
}else{
      cnpj=CPF; 
	  var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais; 
      digitos_iguais = 1; 
      if (cnpj.length < 14 && cnpj.length < 15) 
            return false; 
      for (i = 0; i < cnpj.length - 1; i++) 
            if (cnpj.charAt(i) != cnpj.charAt(i + 1)) 
                  { 
                  digitos_iguais = 0; 
                  break; 
                  } 
      if (!digitos_iguais) 
            { 
            tamanho = cnpj.length - 2 
            numeros = cnpj.substring(0,tamanho); 
            digitos = cnpj.substring(tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(0)) 
                  return false; 
            tamanho = tamanho + 1; 
            numeros = cnpj.substring(0,tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(1)) 
                  return false; 
            return true; 
            } 
      else 
            return false;
      }
}
////////////////////////////////////////////////////////////////////////////////

/* funcao que busca dentro de um vetor por um valor e retorna o elemento que c encontra este valor */
function ascan(pvetor,pvalor,pdimensoes,pelemento){
   if(pdimensoes==null){pdimensoes=1;}
   if(pelemento==null){pelemento=0;}
   retorno=-1;
   for(i=0;i<pvetor.length;i++){
      if(pdimensoes==1){
	     if(pvetor[i]==pvalor){
	        retorno= i;
   	     }  
      }else{
	     if(pvetor[i][pelemento]==pvalor){
	        retorno=i;
	     }		  
      }
   }
   return retorno;
}
/////////////////////////////////////////////////////////////////////////////////
/* funcao para troca de layers interativos */
function troca_layer(playershow,playerhide){
   if(playershow != ''){
      layershow=document.getElementById(playershow).style;	 
      layershow.visibility="";
      layershow.position="";
   }
   if(playerhide != ''){
      layerhide=document.getElementById(playerhide).style;	 
      layerhide.visibility="hidden";
      layerhide.position="absolute";
   }	  
}
//////////////////////////////////////////////////////////////////////////////////////

/*funcao para validar horarios*/
function valida_hora(pvalor){
   var horas,minutos;
   ret=true;
   pvalor = pvalor.toString().replace(":", "" );
   pvalor = pvalor.toString().replace(" ", "" );
   horas  = parseFloat(pvalor.substr(0,2));
   minutos= parseFloat(pvalor.substr(2,2));

   if(pvalor.length != 4 ){
      ret=false;
      //alert("1");	 
   }
   
   if( (horas > 23 || horas < 0 ) && ret ){
      ret=false;
      //alert("2");	  
   }
   if( (minutos >59 || minutos < 0 ) && ret){
      ret=false;
      //alert("3");	  
   }
   
   return ret;
}
///////////////////////////////////////////////////////////////////////////////////////

