/********************************************************* Constantes Globais */
var clErro   = "red";     // Cor de Caption de Erro;
var clNormal = "#000000"; // Cor Normal de Caption;
var clBranco = "#FFFFFF"; 
var d = document;

/******************************************************************** Funções */
function CampoObrigatorio(objeto, tamanho, operador) {
	vr= objeto.value
//	if (vr <= "0,00" ){
//		return false;
//	}
	objeto.value = vr;
	if((operador == ">")&&(objeto.value.length > tamanho)){
		//alert("1. " + objeto.value);
		return true;
	}
	else{
		if	((operador=="=") && (objeto.value.length == tamanho)) {
		//alert("2. " + objeto.value);
			return true;
	}else{
			if((operador=="<") && (objeto.value.length < tamanho)){		
		//alert("3. " + objeto.value);
				return true;
	}else{
		//alert("Preencher Corretamente");
		return false;		
	}}}
}
// somente numeros
function OnlyNum(){
   switch(event.keyCode){
      case 44:
      case 46:
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
      case 58:
         event.keyCode = event.keyCode;
         break;
      default:
         event.keyCode = '127';
         break;
      }
   }
	
// Valida Campo em Branco
function ValidarCpoObrigatorio (obj, tdDesc, cor){
//	alert("obj.value = "+obj.value)
	if(obj.value=="" || obj.value=="   "){
		tdDesc.style.color= clErro;
		return false;
	}else{
		if (cor != "")
		{
			tdDesc.style.color= cor;			
		}
		else
		{
			tdDesc.style.color= clNormal;
		}

		return true;
	}
}

// Valida Numero de caracteres do Campo
function ValidarComprimentoCpo (obj, iComprMinimo, tdDesc){
	if(obj.value.len<iComprMinimo){
		tdDesc.style.color= clErro;
		return false;
	}else{
		tdDesc.style.color= clNormal;
		return true;
	}
}

// Valida Data
function y2k(number) { return (parseInt(number) < 1000) ? parseInt(number) + 1900 : parseInt(number); }
/*function ValidaData(dt, Obr) { 

	//dt dd/mm/aaaa
	var day   = dt.substr(0,2); 
	var month = dt.substr(3,2);
	var year  = y2k(dt.substr(6,4));
	if (Obr == 1){
		if( (dt.length == 10 || dt.length == 8) ){
   		var today = new Date();

			year = ((!year) ? y2k(today.getYear()):y2k(year));

   		month = ((!month) ? today.getMonth():month-1);

	   	if (!day) return false

			var test = new Date(year,month,day);
			
   		if ( (y2k(test.getYear()) == year) && (month == test.getMonth()) && (day == test.getDate()) )
			{
				return true;
			}else{

				return false;
			}
		}else{
			return false;	
		}
	}
	
	else
	{
		if( dt.length == 10 || dt.length == 8 ){
   		var today = new Date();
   		year = ((!year) ? y2k(today.getYear()):year);
   		month = ((!month) ? today.getMonth():month-1);		
		
	   	if (!day) return false	
   		var test = new Date(year,month,day);
			
   		if ( (y2k(test.getYear()) == year) && (month == test.getMonth()) && (day == test.getDate()) ){
//				eval("document.all." + tdDesc).style.color= "#737373";
				return true;
			}else{
//				eval("document.all." + tdDesc).style.color= "red"; 
				return false;
			}
		}else{
			if(dt.length == ""){
//				eval("document.all." + tdDesc).style.color= "#737373";
				return true;
			}else{
//				eval("document.all." + tdDesc).style.color= "red";
				return true;
			}
		}
	}
}*/

function ValidaData(data) {
	var date = data;
	var array_data = new Array;
	var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
	//vetor que contem o dia o mes e o ano
	array_data = date.split("/");
	erro = false;
	//Valido se a data esta no formato dd/mm/yyyy e se o dia tem 2 digitos e esta entre 01 e 31
	//se o mes tem d2 digitos e esta entre 01 e 12 e o ano se tem 4 digitos e esta entre 1000 e 2999
	if ( date.search(ExpReg) == -1 )
		erro = true;
	//Valido os meses que nao tem 31 dias com execao de fevereiro
	else if ( ( ( array_data[1] == 4 ) || ( array_data[1] == 6 ) || ( array_data[1] == 9 ) || ( array_data[1] == 11 ) ) && ( array_data[0] > 30 ) )
		erro = true;
	//Valido o mes de fevereiro
	else if ( array_data[1] == 2 ) {
		//Valido ano que nao e bissexto
		if ( ( array_data[0] > 28 ) && ( ( array_data[2] % 4 ) != 0 ) )
			erro = true;
		//Valido ano bissexto
		if ( ( array_data[0] > 29 ) && ( ( array_data[2] % 4 ) == 0 ) )
			erro = true;
	}
	if ( erro ) 
	{
		return false;
	}
	else
	{
		return true;
	}
}


function ValidaDataCampo(dt, tdDesc, Obr){
	if(ValidaData(dt, Obr)){
		eval("document.all." + tdDesc).style.color= clNormal;
		return true;
	}
	else{
		eval("document.all." + tdDesc).style.color= clErro;
		return false;
	}
}

/***************************************************************** Formatação */
function FormatarMascara(src, mask)
{
   var i = src.value.length;
   var saida = mask.substring(0,1);
   var texto = mask.substring(i)
   if (texto.substring(0,1) != saida)
   {
      src.value += texto.substring(0,1);
   }
}

function FormataNumLimite(fld, e, limite, decimal) {
    var milSep = '.';
    var decSep = ',';
	var sep = 0;
	var key = '';
	var i = j = 0; 
	var len = len2 = 0; 
	var strCheck = '0123456789'; 
	var aux = aux2 = ''; 
	var whichCode = (window.Event) ? e.which : e.keyCode; 
	
	if (fld.value.length > (limite)) {
		return false;
	}
	if (whichCode == 13)
		return true;
	key = String.fromCharCode(whichCode);// Valor para o código da Chave
	if (strCheck.indexOf(key) == -1)
		return false; // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++) 
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
			break; 
	aux = ''; 
	for(; i < len; i++) 
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
			aux += fld.value.charAt(i); 
	aux += key; 
	len = aux.length; 
	if (len == 0)
		fld.value = '';
	else if (len <= decimal) {
        fld.value = '0'+ decSep;
        for (i=0;i<decimal - aux.length;i++)
            fld.value = fld.value + '0';
		fld.value = fld.value + aux;
    }
	else if (len > decimal) {
		aux2 = '';
		for (j = 0, i = len - (decimal + 1); i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - (decimal + 0), len);
	}
	return false;
}

function valida_cnpj(cnpj , Obg){
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	vr = cnpj;
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");		
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");
	cnpj = vr;
	if (Obg == 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;
		}else{
			if(cnpj.length == "")
				return true;
			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;		
		}
}

function Validar_cnpj (cnpj, tdDesc, Obg){
	if(valida_cnpj(cnpj, Obg) == false){
		eval("document.all." + tdDesc).style.color= clErro;
		return false;
	}else{
		eval("document.all." + tdDesc).style.color= clNormal;
		return true;
	}
}	

function Validar_cpf(cpf, tdDesc, Obg){
	if(Verifica_Cep(cpf) == false){
		eval("document.all." + tdDesc).style.color= clErro;
		return false;
	}else{
		eval("document.all." + tdDesc).style.color= clNormal;
		return true;
	}
}

function valida_cpf(cpf , Obg)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      vr = cpf;
  	  vr = vr.replace(".", "");
	  vr = vr.replace(".", "");		
	  vr = vr.replace("-", "");
	  cpf = vr;
		if (Obg == 1){
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
		}else{
			if(cpf.length == "")
				return true;
			if (cpf.length < 11)
      	return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
			
		}	
}


function Verifica_Cep(sCpf){
	var i; 
/*	if (sCpf.indexOf(".") > 0){
		i = sCpf.indexOf(".");
	}*/
	sCpf = sCpf.replace(".", "");
	sCpf = sCpf.replace(".", "");	
	sCpf = sCpf.replace("-", "");
	s = sCpf;
//	alert(sCpf.indexOf("."));
//	s = "35830790866";
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	for (i = 0; i < 9; i++) {   
		d1 += c.charAt(i)*(10-i);   
	}   
	if (d1 == 0){   
		return false;   
	}   
	d1 = 11 - (d1 % 11);   
	if (d1 > 9) d1 = 0;   
	if (dv.charAt(0) != d1) {
		return false;   
	}   
	d1 *= 2;   
	for (i = 0; i < 9; i++) { 
		d1 += c.charAt(i)*(11-i);   
	}   
	d1 = 11 - (d1 % 11);   
	if (d1 > 9) d1 = 0;   
	if (dv.charAt(1) != d1) { 
		return false;
	}   
	return true;   
}

// Valida Browser
function IniciaHttpRequest(){
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}
	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
}

/* Muda o estilo do cursor */
function MouseStyle(obj,modo){
var sMouseStyle = (modo == null) ?  0 : modo;
  switch(modo){
     case 1:
     case "hand":
        sMouseStyle = "hand";
        break;
     case 2:
     case "wait":
        sMouseStyle = "wait";
        break;
     default:
        sMouseStyle = "default";
        break;
     }
  obj.style.cursor = sMouseStyle;
  }

/* Checar se o CapsLook esta ativado */
function checar_caps_lock(ev) {
	var e = ev || window.event;
	codigo_tecla = e.keyCode?e.keyCode:e.which;
	tecla_shift = e.shiftKey?e.shiftKey:((codigo_tecla == 16)?true:false);
	if(((codigo_tecla >= 65 && codigo_tecla <= 90) && !tecla_shift) || ((codigo_tecla >= 97 && codigo_tecla <= 122) && tecla_shift)) {
		document.getElementById('aviso_caps_lock').style.visibility = 'visible';
	}
	else {
		document.getElementById('aviso_caps_lock').style.visibility = 'hidden';
	}
}
	
var aMaiusculo = ['A','B','C','D','E','F','G','H','I','J','K',
									'L','M','N','O','P','Q','R','S','T','U','V','W',
									'X','Y','Z'];
var aNumero = ['1','2','3','4','5','6', '7','8','9','0'];



function buscaNumero(numero)
{
	var bResultado = false;
	for(var jCont = 0; jCont < aNumero.length; jCont++) 
	{
/*			alert("numero = "+numero);
			alert("aNumero[j] == numero = "+aNumero[j] == numero);*/
		if (aNumero[jCont] == numero)
		{
			bResultado = true;
			break;
		}
	}
	
	return bResultado;
}

function encontraNumero(valor_num) 
{
	bRetornaNum = false;
	//alert(valor_num.length)
	for(var icont = 0; icont < valor_num.length; icont++) 
	{
 //	alert(string.charAt(icont))
		if(buscaNumero(valor_num.charAt(icont)))
		{
			bRetornaNum = true;	
			break;
		}
	}
	return bRetornaNum;
}


function buscaMaiusculo(letra)
{
	var bResultado = false;
	for(j = 0; j < aMaiusculo.length; j++) 
	{
		if (aMaiusculo[j] == letra)
		{
			bResultado = true;
			break;
		}
	}
	return bResultado;
}

function encontraMaiuscula(valor_letra) 
{
	bRetorna = false;
	for(var i = 0; i < valor_letra.length; i++) {
		if(buscaMaiusculo(valor_letra.charAt(i)))
		{
			bRetorna = true;
			break;			
		}
	}
	return bRetorna;
}

