/*****************  Funções de validação de dia, mes e ano ****************************************/
$(document).ready(function(){   
  $("form[name=reinicializarsenhacliente]").submit(function() {
	var email = document.getElementById('dados.email');
	if(email != null){
		if(!isEmailValido(email.value)){
			alert("Email Inválido!");
			return false;
		}else{
			alert("Email VAlido");
		}
	}
   });   
});

function validaDia(inputDia){
	 if (inputDia != "" && ((inputDia>31) || (inputDia==0) || (inputDia.length < 2))){
        alert("Dia inválido.")
        return false;
    }
	 return true;
}
function validaMes(inputMes){
	 if (inputMes != "" && ((inputMes>12) || (inputMes<1) || (inputMes.length < 2))){
        alert("Mês inválido.")
        return false;
    }
	 return true;
}
function validaAno(inputAno){
	 if (inputAno != "" && ((inputAno<1000) || (inputAno==0))){
        alert("Ano inválido.")
        return false;
    }
	 return true;
}

// Validações de datas *********************************************************

// function isDataValida(strData)
// strData - String com data no formato DD/MM/YYYY
// Retorno: verdadeiro se data for válida, falso caso contrário

function isDataValida(strData) {
	if (strData) {
		var partes = strData.split('/')
		var diaAntes = Number(partes[0])
		var mesAntes = Number(partes[1]) - 1
		var anoAntes = Number(partes[2])
		var data = new Date(anoAntes, mesAntes, diaAntes)
		var diaDepois = data.getDate()
		var mesDepois = data.getMonth()
		var anoDepois = data.getFullYear()
		if (diaAntes == diaDepois && mesAntes == mesDepois && anoAntes == anoDepois) {
			return true
		} else {
			return false
		}
	} else {
		return false
	}
}

// Retorna a String passada como parâmetro sem os caracteres não numéricos *****

function deixaNumeros(str)
{
	var strClean = "";
	var ch;

	if (str == null)
		return null;
	
	var tam = str.length;

	for (var cont = 0; cont < tam; cont++)
	{
		ch = str.charAt(cont);

		if (ch > '9' || ch < '0')
			continue;

		strClean += ch;
	}

	return strClean;
}

// Validação de CPF ************************************************************

function validaCPF(str)
{
	var strC = deixaNumeros(str),
		tmn,
		s1 = 0,
		s2 = 0,
		dv1,
		dv2;

	if (strC == null)
		return false;

	tmn = strC.length;

	if (tmn < 11)
		return false;


	if (strC.match(/^(([0]+)|([1]+)|([2]+)|([3]+)|([4]+)|([5]+)|([6]+)|([7]+)|([8]+)|([9]+))$/))
		return false;


	for (var i = 0; i < tmn -2; i++)
	{
		s1 += (tmn -1 -i) * parseInt(strC.charAt(i));
		s2 += (tmn -i) * parseInt(strC.charAt(i));
	}
	
	s1 %= 11;
	dv1 = (s1 == 0 || s1 == 1)?0:11-s1;

	s2 += dv1 * 2;
	s2 %= 11;
	dv2 = (s2 == 0 || s2 == 1)?0:11-s2;

	try
	{
		if (apresentaVerificador)
			window.alert(dv1+''+dv2);
	}
	catch(e)
	{}

	return (dv1 == parseInt(strC.charAt(tmn -2)) && dv2 == parseInt(strC.charAt(tmn -1)))?true:false;
}

// Validação de senha **********************************************************

// function isSenhaOiValida(str)
// str - String representando uma senha
// Retorno - verdadeiro caso a senha seja formada por 4 dígitos numéricos, falso caso contrário

function isSenhaOiValida(str) {
	if (isEmpty(str) || !str.match(/^[0-9]{4}$/)) {
		return false
	} else {
		return true
	}
}

// Validação de e-mail *********************************************************

// function isEmailValido(strEmail)
// Valida se uma String representa um e-mail válido
// strEmail - String a ser avaliada
// Retorno - verdadeiro se a String for um e-mail válido, falso caso contrário

function isEmailValido(strEmail) {
	if (!strEmail.match(/^([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+)(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/)) {
		return false
	} else {
		return true
	}
}

// Deixa apenas números em um campo Javascript *********************************

function numbersonly(myfield, e, dec) {
	var key;
	var keychar;
	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}

	keychar = String.fromCharCode(key);
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) {
		return true;
	// Control-V
	} else if ((key == 118 || key == 86) && e.ctrlKey) {
		return true
	// numbers
	} else if ((("0123456789").indexOf(keychar) > -1)) {
		return true;
	// decimal point jump
	} else if (dec && (keychar == ".")) {
		myfield.form.elements[dec].focus();
		return false;
	} else {
		return false;
	}
}

// autoJump ********************************************************************

var autoJump_downStrokeField

// autoJump(nomeForm, nomeCampo, nomeProximoCampo, comprimentoMaximo, somenteNumeros, mascara)
// Pula automaticamente entre os campos de um determinado formulário
// nomeForm - nome do formulário
// nomeCampo - nome do campo a ser configurado para auto jump
// nomeProximoCampo - próximo campo para o qual o qual o foco será direcionado
// comprimentoMaximo - opcional - comprimento máximo do campo
// somenteNumeros - opcional - se verdadeiro, rejeita entrada de caracteres que não forem dígitos
// mascara - opcional - define uma máscara para o valor do campo (ex: em datas, ##/##/####)

function autoJump(nomeForm, nomeCampo, nomeProximoCampo, comprimentoMaximo, somenteNumeros, mascara) {
	//alert('campo=' + nomeCampo + ' prox=' + nomeProximoCampo)
	var form = document.forms[nomeForm]
	var campo = form.elements[nomeCampo]
	var proximoCampo = form.elements[nomeProximoCampo]
	if (proximoCampo == null) {
		proximoCampo = document.getElementById(nomeProximoCampo)
	}
	campo.nextField = proximoCampo
	campo.maxLength = comprimentoMaximo
	campo.mascara = mascara
	if (campo != null && proximoCampo != null) {
		campo.onkeydown = autoJumpKeyDown
		campo.onkeyup = autoJumpKeyUp
		if (somenteNumeros) {
			campo.somenteNumeros = true
		}
	}
}

function autoJumpKeyDown() {
	this.beforeLength = this.value.length
	autoJump_downStrokeField = this
}

function autoJumpKeyUp() {
	var executarDeixaNumeros = true
	if (window.event) {
		var key = window.event.keyCode
		if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) || (key==36) || (key==37) || (key==39)) {
			executarDeixaNumeros = false
		}
	} 
	if (this.somenteNumeros && executarDeixaNumeros && this.mascara == null) {
		this.value = deixaNumeros(this.value).substring(0, this.maxLength)
	}
	if ((this == autoJump_downStrokeField) && (this.value.length > this.beforeLength) && (this.value.length >= this.maxLength)) {
		try {
			if (this.nextField.type != "select-one" && this.nextField.length > 1) {
				this.nextField[0].focus()
			} else {
				this.nextField.focus()
			}
		} catch(e) {
		}
	}
	if (this.mascara) {
		aplicarMascara(this, this.mascara)
	}
	autoJump_downStrokeField = null
}

// Aplica uma máscara de formatação ao valor de um campo input *****************

function aplicarMascara(campo, mask) {
	var i = campo.value.length
	var saida = mask.substring(0,1)
	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida) {
		campo.value += texto.substring(0,1)
	}
}

// Validação de número Oi ******************************************************

// function isTelefoneOiValido(msisdn)
// Valida se um MSISDN é um telefone Oi válido
// msisdn - DDD + telefone a ser avaliado.
// Retorno - verdadeiro caso o MSISDN seja um telefone Oi válido, falso caso contrário.

function isTelefoneOiValido(msisdn) {
	if (isEmpty(msisdn) || msisdn.length != 10 || isNaN(msisdn)) {
		return false
	}
	//var ddd = msisdn.substr(0, 2)
	//var numero = msisdn.substr(2)
	
	//if (numero.charAt(0) == '8' && numero.charAt(1) >= '5') {
		return true
	//} else {
	//	return false
	//}
}

function validarNumeroOi(what) {
	if (what.value != "") {
		//if (!(what.value.charAt(0) == '8' && what.value.charAt(1) >= '5' && what.value.length== 8)) {
		if (!(what.value.length == 8)) {
			window.alert('O número fornecido não é um número válido!')
			what.value=''
			return false
		}
	}
	return true
}

// *****************************************************************************

    function habilitarRadioBox(obj){

           document.getElementById("rdTemPonto").disabled = true;                    
           document.getElementById("rdSemPonto").disabled = true;
           document.getElementById("rdTemPonto2").disabled = true;                    
           document.getElementById("rdSemPonto2").disabled = true;
            
           if (obj.value == "possui"){                  
                  document.getElementById("rdTemPonto").disabled = false;
                  document.getElementById("rdTemPonto2").disabled = false;
           }//if
    
           if (obj.value == "nao_possui"){
                  document.getElementById("rdSemPonto").disabled = false; 
                  document.getElementById("rdSemPonto2").disabled = false;                          
           }//if

    }//habilitarCampos

 
    function habilitarTxtEspecificarOutros(obj){
           if (document.form.txtEspecificarOutros.disabled){
                  document.form.txtEspecificarOutros.disabled = false;                      
           }//if
          else
           {
                  document.form.txtEspecificarOutros.value = "";      
                  document.form.txtEspecificarOutros.disabled = true;                   
           }
    }//habilitarCampos

     function habilitarCampo(campo){

             document.form.txtOperadora.disabled = true; 
             document.form.txtEmpresa.disabled = true; 
             document.form.txtOutros.disabled = true;
			 document.form.txtCargoGerencial.disabled = true;

               if(campo == "EmpresarioVarejista"){
                  document.form.txtOperadora.disabled = false;
                  document.form.txtEmpresa.value="";
                  document.form.txtOutros.value="";
				  document.form.txtCargoGerencial.value=""; 
             }//if 
             
             if(campo == "FuncionarioEmpresa"){
                  document.form.txtEmpresa.disabled = false;
                  document.form.txtOperadora.value="";
                  document.form.txtOutros.value=""; 
				  document.form.txtCargoGerencial.value=""; 
             }//if
             
             if(campo == "Outros"){
                  document.form.txtOutros.disabled = false;
                  document.form.txtOperadora.value="";
                  document.form.txtEmpresa.value="";
				  document.form.txtCargoGerencial.value="";  
             }//if
			 
			 if(campo == "CargoGerencial"){
                  document.form.txtCargoGerencial.disabled = false;
				  document.form.txtOutros.value = "";
                  document.form.txtOperadora.value="";
                  document.form.txtEmpresa.value="";  
             }//if
  
             
             if (campo != "EmpresarioVarejista" && campo != "Outros" && campo != "FuncionarioEmpresa" && campo != "CargoGerencial" ){  
                    document.form.txtOperadora.value="";
                    document.form.txtEmpresa.value="";   
                    document.form.txtOutros.value="";
					document.form.txtCargoGerencial.value="";                           
             }//if
 
               

    }//habilitarCampo

