/* 
+---------------------------------------------+
| Bibblioteca de funções gerais em JavaScript |
| Funções coletadas por: Felipe Rebelo Lopes  |
| Empresa: BCJ Soluções Inteligentes          |
| Contato: suporte@bcj.com.br                 |
+---------------------------------------------+
*/

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

// Valida se o conteúdo da string email é um e-mail válido
function notNull(campo, nmcampo) {
	if (campo.value == "") {
		window.alert('O campo ' + nmcampo + ' é obrigatório!');
		campo.focus();
		return false;
	}
	return true;
}

function isY(campo, cpf) {
	if (campo.value != "Y") {
		if (campo.value == "E") {
			window.alert('O cpf "' + cpf + '" não foi econtrado em nosso banco de Dados.\n\nÉ obrigatório que o player já esteja cadastrado no site!!!');
			return false;
		}

		if (campo.value == "T") {
			window.alert('O cpf "' + cpf + '" já está cadastrado nesta localidade por outro time.\n\nEm caso de problemas com o cadastro entre em contato com a administração!!!');
			return false;
		}
	}
	return true;
}

function SubmitFormOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( (en == 13) )
  {
    Obj.submit();
  }
}

function DateFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( ((Obj.value.length == 2) || (Obj.value.length == 5)) && (en != 8) )
  {
    Obj.value = Obj.value + '/';
  }
  if( ((Obj.value.length == 10) && (en != 8)) )
  {
//    Obj.value = Obj.value + ' '; só quando tem horas
    Obj.value = Obj.value + '';
}

  if( ((Obj.value.length == 13) && (en != 8)) )
  {
    Obj.value = Obj.value + ':';
  }

}

function DateMySqlOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( ((Obj.value.length == 4) || (Obj.value.length == 7)) && (en != 8) )
  {
    Obj.value = Obj.value + '-';
  } 

  if( Obj.value.length == 10)
  {
    Obj.value = Obj.value + ' ';
  }

  if(  ((Obj.value.length == 13) || (Obj.value.length == 16))  && (en != 8) )
  {
    Obj.value = Obj.value + ':';
  } 

}

function HourFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( (Obj.value.length == 2) && (en != 8) )
  {
    Obj.value = Obj.value + ':';
  }
}

function CEPFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 

  if( (Obj.value.length == 5) && (en != 8) )
  {
    Obj.value = Obj.value + '-';
  }
}

function RGFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( ((Obj.value.length == 2) || (Obj.value.length == 6)) && (en != 8) )
  {
    Obj.value = Obj.value + '.';
  }
  else if( (Obj.value.length == 10) && (en != 8) )
  {
    Obj.value = Obj.value + '-';
  }
  
}


function CPFFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( ((Obj.value.length == 3) || (Obj.value.length == 7)) && (en != 8) )
  {
    Obj.value = Obj.value + '.';
  }
  else if( (Obj.value.length == 11) && (en != 8) )
  {
    Obj.value = Obj.value + '-';
  }
  
}

function CNPJFieldOnKeyUp(Obj, e)
{
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 
  
  if( ((Obj.value.length == 2) || (Obj.value.length == 6)) && (en != 8) )
  {
    Obj.value = Obj.value + '.';
  }
  else if( (Obj.value.length == 10) && (en != 8) )
  {
    Obj.value = Obj.value + '/';
  }
  else if( (Obj.value.length == 15) && (en != 8) )
  {
    Obj.value = Obj.value + '-';
  }
  
}

function validaEmail(obj) {
    invalidChars = " ~\'^\`\"*+=\\|][(){}$&!#%/:,;";
	email = obj.value;

    if (email == "") {
        return true;
    }
    for (i=0; i<invalidChars.length; i++) {
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1) {
			alert('O Campo de Email contém caracteres inválidos!');
			obj.focus();
            return false;
        }
    }
    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
		alert('Campo Email inválido!');
		obj.focus();
        return false;
    }
    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".") {
		alert('Campo Email inválido!');
		obj.focus();
		return false;
    }
    while ((Pos < lengthOfEmail) && ( Pos != -1)) {
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".") {
			alert('Campo Email inválido!');
			obj.focus();
            return false;
        }
        if (Pos != -1) {
            Pos++;
        }
    }

    atPos = email.indexOf("@",1);
    if (atPos == -1) {
		alert('Campo Email inválido!');
		obj.focus();
        return false;
    }

    if (email.indexOf("@",atPos+1) != -1) {
		alert('Campo Email inválido!');
		obj.focus();
        return false;
    }

    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) {
		alert('Campo Email inválido!');
		obj.focus();
        return false;
    }
    if (periodPos+3 > email.length) {
		alert('Campo Email inválido!');
		obj.focus();
        return false;
    }
    return true;
}

function numbersonly(e){
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 

  if ( (en == 8) || (en == 13) || (en == 0) ) 
    return true
  else if (en < 48 || en > 57)
    return false
}	

function validaCEP(obj){
	if ((obj.value.length == 9)||(obj.value.length == 0)) {
		return true;
	}
	else{
		alert('O Campo de CEP deve ter 9 digitos');
//		obj.focus();
		return false;
	}
}
// Funcação que valida o con
function validaCPF(sCPF) {
        cpf = sCPF;
        erro = new String;
        if (cpf.length < 11) erro += "Um CPF deve conter 11 digitos! ";
        var nonNumbers = /\D/;
        if (nonNumbers.test(cpf)) erro += "O CPF deve conter apenas números! ";
        if (cpf == "00000000000" || 
			cpf == "11111111111" || 
			cpf == "22222222222" || 
			cpf == "33333333333" || 
			cpf == "44444444444" || 
			cpf == "55555555555" || 
			cpf == "66666666666" || 
			cpf == "77777777777" || 
			cpf == "88888888888" || 
			cpf == "99999999999"){
                erro += "Numero de CPF invalido!"
       }
       var a = [];
       var b = new Number;
       var c = 11;
       for (i=0; i<11; i++){
               a[i] = cpf.charAt(i);
               if (i < 9) b += (a[i] * --c);
       }
       if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
       b = 0;
       c = 11;
       for (y=0; y<10; y++) b += (a[y] * c--);
       if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
       if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
               erro +="Digito verificador incorreto!";
       }
       if (erro.length > 0){
               alert(erro);
               return false;
       }
       return true;
}

 function validaCNPJ(obj) {
	 	 if (obj.value == ""){
			 return true;
		 }
		 CNPJ = obj.value;
		 erro = new String;
		 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! ";
		 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
		 }
		 //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 +="Dígito verificador com problema!";
	   }
	   if (erro.length > 0){
			   alert(erro);
//			   obj.value = "";
			   obj.focus();
			   return false;
	   }
	   return true;
}

 function JustDateVerify(data, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	var strdata = data.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
 			alert("Formato da data não é válido.\nFormato correto: dd/mm/aaaa hh:mi.");
 			data.focus();
 			return false;
 		}
 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1) ){
 			alert("Formato da data não é válido.\nFormato correto: dd/mm/aaaa hh:mi.");
 			data.focus();
 			return false;
 		}
 		dia = strdata.substr(0,2);
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);

 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Dia informado não é válido.");
 			data.focus();
 			return false;
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mês informado não possui 31 dias.");
 				data.focus();
 				return false;
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mês informado possui somente 29 dias.");
 					data.focus();
 					return false;
 				}
 			}
			else{
 				if (dia > 28){
 					alert("O mês informado possui somente 28 dias.");
 					data.focus();
 					return false;
 				}
 			}
 		}
 	//Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
			alert("Mês informado não é válido.");
 			data.focus();
 			return false;
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Ano informado não é válido.");
 			data.focus();
 			return false;
 		}
 	}
	return true;
 }

 function DateVerify(data, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	var strdata = data.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 16){
 			alert("Formato da data não é válido.\nFormato correto: dd/mm/aaaa hh:mi.");
// 			data.focus();
 			return false;
 		}
 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1) || ":" != strdata.substr(13,1)){
 			alert("Formato da data não é válido.\nFormato correto: dd/mm/aaaa hh:mi.");
// 			data.focus();
 			return false;
 		}
 		dia = strdata.substr(0,2);
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);
		hora = strdata.substr(11,5);
		// verifica hora
		 if(hora.substr(0,2) > 23 || isNaN(hora.substr(0,2))){
 			alert("Formato da hora inválido.\nO valor deve estar entre 0 e 23 horas");
// 			hora.focus();
 			return false;
 		}
 		if(hora.substr(3,2) > 59 || isNaN(hora.substr(3,2))){
 			alert("Formato do minuto inválido.\nO valor deve estar entre 0 e 59 minutos");
// 			hora.focus();
 			return false;
 		}
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Dia informado não é válido.");
// 			data.focus();
 			return false;
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mês informado não possui 31 dias.");
// 				data.focus();
 				return false;
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mês informado possui somente 29 dias.");
// 					data.focus();
 					return false;
 				}
 			}
			else{
 				if (dia > 28){
 					alert("O mês informado possui somente 28 dias.");
// 					data.focus();
 					return false;
 				}
 			}
 		}
 	//Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
 			alert("Mês informado não é válido.");
// 			data.focus();
 			return false;
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Ano informado não é válido.");
// 			data.focus();
 			return false;
 		}
 	}
	return true;
 }
 
function HourVerify(hora, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){
 		if(hora.value.length < 5){
 			alert("Formato da hora inválido. Por favor, informe a hora no formato correto: hh:mm");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){
 			alert("Formato da hora inválido.");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
 			alert("Formato do minuto inválido.");
 			hora.focus();
 			return false
 		}
 	}
	return true
 }

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent != null)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent != null)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


function numbersdot(e){
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 

  if ( (en == 8) || (en == 13) || (en == 0) || (en == 46) ) 
    return true
  else if (en < 48 || en > 57) 
    return false
}	

function lockColcheteOnKeyPress(e){
  if(document.all) { //it's IE 
    var en = window.event.keyCode; 
  }
  else
  { 
    en = e.which; 
  } 

  if ( (en != 91) && (en != 93) && (en != 64)) 
    return true
  else 
    return false
}	

// Registra o Flash para o Update do Internet Explorer
function clearObject(obj){
	if(obj==null){
		var theObjects = document.getElementsByTagName("object");
		for (var i=0; i < theObjects.length; i++) {
			 theObjects[i].outerHTML=theObjects[i].outerHTML;
		}
	}
	else{
		obj.outerHTML = obj.outerHTML;
	}
}

function FmtValorMonetario(Dado){
      var Result, i;
      Dado = PassaDominio(Dado,"0123456789");
      if (Dado.length > 2){
            Result = "," + Dado.substr(Dado.length-2, 2);
            for (i=5; i<=Dado.length; i+=3){
                  Result = Dado.substr(Dado.length-i, 3) + Result;
                  if (Dado.length > i) Result = "." + Result;
            }
            Result = Dado.substr(0, Dado.length-i+3) + Result;
      }
      else{
             Result = Dado;
      }

      if (Result.indexOf("-") > -1){
            if (Result.substring(1,2) == "."){
                  Result = Result.substring(0,1) + Result.substring(2,Result.length)
            }
      }     
      return Result;
}

function PassaDominio(StrDado, Dominio){
	var i, j, c;
	var Result;
	
	Result = "";
	for (i=0; i<StrDado.length; i++){
		c = StrDado.substr(i,1);
		for (j=0; j<Dominio.length; j++){
			if (c == Dominio.substr(j,1)) break;
		}
		if (j < Dominio.length){
			Result = Result + c;
		}
	}
	return Result;
}
