﻿// JScript File
//Criado por Fabio Ambrozio Porto
//Vou colocar códigos para faciliar o comentário das funções que estamos desenvolvendo
//Caso queiram implementar algo, adicionem o comentário do autor
/*
    F01
    Ela exibe ou não um elemento.
    Parametros: O ID do elemento que será exibido ou não
    Exemplo: Se uma div estiver oculta, ela habilita, senão, oculta.

    F02
    Valida se o(s) campo(s) está vazio
    Parametros: Recebe os campos dividido por pipe |

    F03
    Função para validar email
    Parametros: Recebe o campo(objeto) email
    
    F04
    Função para validar um CNPJ
    Parametros: Campo o valor do campo 
    
    F05
    Função para cria qualquer tipo de mascara (exceto valores monetarios)
    Parametros: txtBoxFormat(objForm(id do formulario), strField(campo), sMask('99/99/9999'), event)
    Importante: Ele funciona no evento onkeypress

    F06
    Verifica se o CNPJ é válido
    Parametros:  valor do campo CNPJ
    
    
    F07
    Verifica se é uma Data Válida
    Parametros : isValidData(vfield(nome campo) , vfieldName)

    F08
    Verifica se somente números foram digitados no campo
    
   F09
   Compara duas datas DE ATE
   
   F10
   Habilita ou Desabilita os campos de Imagens para inserção das mesmas.
   Ex; campo 1 tem imagem, então habilita o campo 2, etc....
   
   F11
   A data enviada deve ser menor que a data atual
   
   F12
   Verifica se a mesma esta poreenchida
   Especifico da Imagem1
   
   F13
   Específica do Menu do Ras
   Deixa 'block' o menu ativado
   Parâmetros : nome da pagina
   
   

    Exemplos para acesso a estas funçoes na p- do .NET
    return isEmail('"+email_faleconosco.Text+"'); 
    cnpjCliente.Attributes.Add("onkeypress", "return txtBoxFormat(form1, 'cnpjCliente', '99.999.999/9999-99', event)");
    form1.Attributes.Add("onsubmit", " isDateComparison(dtDeObra.value,dtAteObra.value); return ValidaForm(" + casodeUso.getCamposObrigatorios(4) + ")");
    dtDeObra.Attributes.Add("onkeypress", " return txtBoxFormat(form1,'dtDeObra', '99/99/9999', event)");
    dtDeObra.Attributes.Add("onblur", " return isValidData(this, 'dtDeObra')");
    dtAteObra.Attributes.Add("onkeypress", " return txtBoxFormat(form1,'dtAteObra', '99/99/9999', event)");
    dtAteObra.Attributes.Add("onblur", " return isValidData(this, 'dtAteObra')");


*/
//F01
function trocaImg(id){
    var elemento = document.getElementById(id);
    if(typeof(elemento)=='object'){
        elemento.src.indexOf('setaCima')!= -1 ? elemento.src='/ras/master/imagens/setaBaixo.gif': elemento.src='/ras/master/imagens/setaCima.gif';
    }else{
        //Criar um log para adicionar os erros
        alert('Elemento não encontrado'+id);
    }
}



//F01
function exibirOcultar(id){
    var elemento = document.getElementById(id);
    if(typeof(elemento)=='object'){
        elemento.style.display=='none'? elemento.style.display='block': elemento.style.display='none';
    }else{
        //Criar um log para adicionar os erros
        alert('Elemento não encontrado'+id);
    }
}

//F02
function ValidaForm(campos){
    var aCampos = campos.split("|");
    var campo;
    var originalClass;
    var cont = 0;
    for(i=0;i<aCampos.length;i++){
        if(document.getElementById(aCampos[i])){
                campo = document.getElementById(aCampos[i]).value.replace('  ','');
                originalClass = document.getElementById(aCampos[i]).className.replace('msnErro','');

                if(campo=="0" || campo=="" || campo.length < 1 && (document.getElementById(aCampos[i]).disabled==false)){
                    document.getElementById(aCampos[i]).className= originalClass + ' msnErro';
                    cont++;                           
                }else{
                    document.getElementById(aCampos[i]).className = originalClass;
                }
        }
    }
    if(cont>0){return false;}
    
return true;
}

//F03
function isEmail(email){
      if(email!="")
      {
          er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
          if(!er.exec(email)){
              alert('Formato de email inválido');
              return false;
            }
      }
        //return true;
}



//F04
 function isCNPJ(NumCNPJ) {
         CNPJ = NumCNPJ.value;
         erro = new String;
         if (CNPJ.length < 18  && CNPJ.length > 0) erro += "É necessario preencher corretamente o número do CNPJ! "; 
		 CNPJ = CNPJ.replace(/\./g,'').replace(/\-/g,'').replace(/\//g,'');
         if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
         //substituir os caracteres que não são números
                       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 verificação de CNPJ suporta apenas números. "; 
       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 +="CNPJ Inválido.";
       }
       if (erro.length > 0){
               alert(erro);
			   NumCNPJ.value='';			
			   NumCNPJ.focus();
               return false;
       } 
       return true;
}



//F05
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
nTecla = evtKeyPress.which;
} else if(document.getElementById) { // FireFox
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( " ", "" );
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) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (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 != 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;
}
}

//F06
         function isCNPJ(NumCNPJ) {
                 CNPJ = NumCNPJ.value;
                 erro = new String;
                 if (CNPJ.length < 18  && CNPJ.length > 0) erro += "É necessario preencher corretamente o número do CNPJ! "; 
				 CNPJ = CNPJ.replace(/\./g,'').replace(/\-/g,'').replace(/\//g,'');
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
                 //substituir os caracteres que não são números
               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 verificação de CNPJ suporta apenas números. "; 
               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 +="CNPJ Inválido.";
               }
               if (erro.length > 0){
                       alert(erro);
					   NumCNPJ.value='';			
					   NumCNPJ.focus();
                       return false;
               } 
               return true;
       }


//F07
function isValidData(vfield, vfieldName)
{
var diaStr, mesStr, anoStr
var diaInt, mesInt, anoInt
var tam, sep1, sep2, verAno

tam = vfield.value.length;
	
if(vfield.value.length == 0)
 {
  return false;
 }	

sep1 = parseInt(vfield.value.indexOf("/", 0));

	
		
if (sep1<0)
{
alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
vfield.value='';
vfield.focus();
return false;
}

sep2 = parseInt(vfield.value.indexOf("/", sep1+1))

if (sep2<5)
{
alert("A Data digitada deve ter o seguinte formato: DD/MM/AAAA !");
vfield.value='';
vfield.focus();
return false;
}

verAno = tam-sep2;

if(verAno < 5 )
{
alert("As datas devem ser preenchidas utilizando 4 dígitos para informar o Ano (ex.: DD/MM/AAAA)!");
vfield.value='';
vfield.focus();
return false;
}

diaStr = vfield.value.substring(0, sep1);

if(diaStr.substring(0, 1) == "0")
diaStr = diaStr.substring(1, 2);

	if (isValidNumberValue(diaStr, vfieldName))
	{
	mesStr = vfield.value.substring(sep1+1, sep2); 
	
		if(mesStr.substring(0, 1) == "0")
		mesStr = mesStr.substring(1, 2);
		
		if (isValidNumberValue(mesStr, vfieldName))
		{
		anoStr = vfield.value.substring(sep2+1, tam);
		
		if (isValidNumberValue(anoStr, vfieldName))
		{
		diaInt = parseInt(diaStr);
		mesInt = parseInt(mesStr);
		anoInt = parseInt(anoStr);
			
			if(anoInt <= 1900)
				{
				alert('O ano informado não é válido.\n Informe um ano superior a 1900.');
				vfield.value='';
				vfield.focus();
				return false;
				}
			
			if ((diaInt <= 0) || (diaInt > 31))
			{
			alert("O dia informado não é válido!");
			vfield.value='';
			vfield.focus();
			return false;
			}
			
			if ((mesInt <= 0) || (mesInt > 12))
			{
			alert("O mês informado não é válido!");
			vfield.value='';
			vfield.focus();
			return false;
			}
			
			if ((mesInt == 4) || (mesInt == 6) || (mesInt == 9) || (mesInt == 11))
			{
				if( diaInt > 30)
				{
				alert("O mês informado não possui mais de 30 dias!");
				vfield.value='';
				vfield.focus();
				return false;
				}
			}
			
			if (mesInt == 2)
			{
				if ((anoInt % 4 == 0) && ( (anoInt % 100 != 0) || (anoInt % 400 == 0)))
				{
					if (diaInt > 29)
					{
					alert("O mês informado não possui mais de 29 dias!");
					vfield.value='';
					vfield.focus();
					return false;
					}
				}
				else
				{
					if(diaInt > 28)
					{
					alert("O mês informado não possui mais de 28 dias!");
					vfield.value='';
					vfield.focus();
					return false;
					}
				}
				return true;
			} 
			return true;
			}
						
		else
		return false;
	}
	else
	return false;
}
else
return false;
}


//F08
function isValidNumberValue (objTextControl, strFieldName) 
{
var strValidNumber = "1234567890";

for (nCount=0; nCount < objTextControl.length; nCount++) 
{
strTempChar=objTextControl.substring(nCount,nCount+1);
if ( strValidNumber.indexOf(strTempChar,0)==-1) 
{
alert("O campo " + strFieldName + " deve conter somente números!");
return false; 
}
} 

return true;
}


//F09
function isDateComparison(CampoDe,CampoAte)
	{
		var Data = CampoDe;
		var DataCampoDe = Data.split('/');
		var Dia = DataCampoDe[0];
		var Mes = DataCampoDe[1];
		var Ano = DataCampoDe[2];
		var Data2 = new Date(Ano,--Mes,Dia);
		var Dia = Data2.getDate();
		var Mes = Data2.getMonth();
		var Ano = Data2.getYear();
		
		var DataCampo  = CampoAte;
		var DataCampo2 = DataCampo.split('/');
		var Dia1 = DataCampo2[0];
		var Mes1 = DataCampo2[1];
		var Ano1 = DataCampo2[2];
		var Data1 = new Date(Ano1,--Mes1,Dia1);
		var Dia1 = Data1.getDate();
		var Mes1 = Data1.getMonth();
		var Ano1 = Data1.getYear();
		var ok = 1;
		

		   if(CampoDe != '' && CampoAte != '')
			{
			  
			    if(parseInt(Ano) < parseInt(Ano1))
				        ok = 0;
			    else if(parseInt(Ano) == parseInt(Ano1))
				    {
					    if(parseInt(Mes) < parseInt(Mes1))
						    ok = 0;
					    else if(parseInt(Mes) == parseInt(Mes1))
						    {
							    if(parseInt(Dia) <= parseInt(Dia1))
								    ok = 0;
						    }
		        }
				
			}else if (CampoDe == '' && CampoAte == '')
			    ok=0;
			    

			 //resutado erro=1 correto=0   
			if(ok == 1)
				{
				alert('O campo Período de Execução está preenchido incorretamente');
				return false;
				}
	}


//F10
function HabDesabImg(pos)
{
    var pos0 = document.getElementById('img'+pos);
    var pos1 = document.getElementById('img'+(pos+1));
    //var link0 =document.getElementById('hlimg'+pos); 
    //var link1 =document.getElementById('hlimg'+(pos+1)); 

       if(typeof(pos0)=='object'){
            if(pos0.value==''/* && link0.innerText==''*/){
                    if(pos1!=null)
                    {
                        pos1.disabled=true;
                    }
            }else{
                    if(typeof(pos1)=='object')
                    {
                      pos1.disabled=false;
                    }
            }
       }
       
}


//F11
function isDateCurrent(idData)
	{
		var DataCampo  = document.getElementById(idData).value;
		    DataCampo = DataCampo.split('/');

		var Dia = DataCampo[0];
		var Mes = DataCampo[1];
		var Ano = DataCampo[2];

    	var Hoje = new Date();
		var Dia1 = Hoje.getDate();
		var Mes1 = Hoje.getMonth();
		var Ano1 = Hoje.getFullYear();
		var ok = 1;
        
		   if(DataCampo != '')
			{
			    if(parseInt(Ano) > parseInt(Ano1))
				        ok = 0;
			    else if(parseInt(Ano) == parseInt(Ano1))
				    {
					    if(parseInt(Mes-1) > parseInt(Mes1))
						    ok = 0;
					     else if(parseInt(Mes-1) == parseInt(Mes1))
						    {
							    if(parseInt(Dia) >= parseInt(Dia1))
								    ok = 0;
						    }
		           }
				
			}
			   
			 //resutado erro=0 correto=1   
			if(ok == 0)
				{
				    alert('O Período de Execução não pode ser uma data atual ou futura.');
				    document.getElementById(idData).value='';
				    return false;
				}
	}



//f12
function Img1()
{
    //especifico da foto1
      if (document.getElementById('img1'))
        {
            if(!document.getElementById('Data_Imagem') && document.getElementById('img1').value=='')
            {
                alert('O campo foto1 é obrigatório');
                return false;            
            }
        }
        
        return true;
}


//F13
function menuAtivo(pagina)
{
    //alert(pagina);
	pagina = pagina.toLowerCase();
	if(pagina.indexOf('cliente',0)!=-1)
	{
        document.getElementById('ulcliente').style.display='block';    	
	}
    else if(pagina.indexOf('profissionalsaude',0)!=-1)
	{
        document.getElementById('ulprofissionalsaude').style.display='block';    	
	}
    else if(pagina.indexOf('contato',0)!=-1)
	{
        document.getElementById('ulcontato').style.display='block';    	
	}
    else if(pagina.indexOf('funcionario',0)!=-1)
	{
        document.getElementById('ulfuncionario').style.display='block';    	
	}
    else if(pagina.indexOf('produto',0)!=-1)
	{
        document.getElementById('ulproduto').style.display='block';    	
	}
    else if(pagina.indexOf('documento',0)!=-1)
	{
        document.getElementById('uldocumento').style.display='block';    	
	}
    else if(pagina.indexOf('configuracoes',0)!=-1)
	{
        document.getElementById('ulconfiguracoes').style.display='block';    	
	}
    else if(pagina.indexOf('comunicacao',0)!=-1)
	{
        document.getElementById('ulcomunicacao').style.display='block';    	
	}
    else if(pagina.indexOf('vaga',0)!=-1 || pagina.indexOf('candidato',0)!=-1)
	{
        document.getElementById('ulrecursoshumanos').style.display='block';    	
	}
    else if(pagina.indexOf('treinamento',0)!=-1)
	{
        document.getElementById('ultreinamento').style.display='block';    	
	}
    else if(pagina.indexOf('evento',0)!=-1)
	{
        document.getElementById('ulevento').style.display='block';    	
	}
}


//F14
//F01
function exibirDocLink(id,id2){
    var elemento = document.getElementById(id);
    var elemento2 = document.getElementById(id2);

    if(typeof(elemento)=='object' && typeof(elemento2)=='object'){
        elemento.disabled=false;
        elemento.value='';
        
        elemento2.disabled=true;
        elemento2.value='';
    }else{
        //Criar um log para adicionar os erros
        alert('Elemento não encontrado'+id);
    }
}
