// JavaScript Document

//Somente para menu de navegação
function toggleMenu(id,ico){
	var element = document.getElementById(id).style.backgroundImage;
	var element2 = document.getElementById(ico);
	element2.style.display = (element2.style.display == 'inline') ? "none" : "inline";
	
	if(element.length == 0){
		var newImage = "url(images/bkg_menu_minus.jpg)";
		document.getElementById(id).style.backgroundImage = newImage;
	}else{
		if(document.getElementById(id).style.backgroundImage == 'url(images/bkg_menu_plus.jpg)'){
			var newImage = "url(images/bkg_menu_minus.jpg)";
		}else{
			var newImage = "url(images/bkg_menu_plus.jpg)";
		}
		
		document.getElementById(id).style.backgroundImage = newImage;
	}
}

function textCounter(field, countfield, maxlimit){
	if(field.value.length > maxlimit){ // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
	} else {
		countfield.value = maxlimit - field.value.length;
	}
}

function formataData(val){
	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;                
				  continue;            
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
					 var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;            
				}
		
				if    ((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
			 }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;            
			  }
		  }
	 }
	
	 if(pass.length>10)
		val.value = val.value.substring(0, 10);
		 return true;
}

function toggle(elementID){
	var target1 = document.getElementById(elementID);
	if (target1.style.display == 'none') {
		target1.style.display = 'block';
	} else {
		target1.style.display = 'none';
	}
}

function isNumberKey(e){
	if (!e){ e = window.event;  }
	var code;   
	if (e.keyCode) code = e.keyCode;   
		  
	else if (e.which) code = e.which; // Netscape 4.?   
		  
	if (e.altKey)  
	{  
		  return false;  
	}  
		  
	if (code > 31 && (code < 48 || code > 57))  
	{  
		  return false;  
	}
}

function isNumberKey2(e){
	if (!e){ e = window.event;  }
	var code;   
	if (e.keyCode) code = e.keyCode;   
		  
	else if (e.which) code = e.which; // Netscape 4.?   
		  
	if (e.altKey)  
	{  
		  return false;  
	}  
		  
	if (code > 31 && (code < 48 || code > 57) && code != 46)  
	{  
		  //alert(code);
		  return false;  
	}
}

function fone(obj,prox) {
	switch (obj.value.length) {
	    case 1:
	        obj.value = "(" + obj.value;
	        break;
	    case 3:
	        obj.value = obj.value + ")";
	        break;    
	    case 8:
	        obj.value = obj.value + "-";
	        break;    
	    /*case 13:
	        prox.focus();
	        break;*/
	}
}

function validarCPF(obj){
   var oCpf = obj.value;
   oCpf = oCpf.replace('-', '');
   oCpf = oCpf.replace('.', '');
   oCpf = oCpf.replace('.', '');
   oCpf = oCpf.replace('/', '');
   
   var cpf = oCpf;
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	  obj.value = '';
	  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))){
	 window.alert("CPF inválido. Tente novamente.");
	 obj.value = '';
	 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))){
     window.alert("CPF inválido. Tente novamente.");
	 obj.value = '';
	 return false;
   }
   
   if(document.getElementById("id_perfil")){
   	cpfSearch.location.href="adm/buscaCPF.cfm?cpf="+cpf;
   } else {
	cpfSearch.location.href="buscaCPF.cfm?cpf="+cpf;
   }
   
   return true;
}

function validarCNPJ(obj){
	CNPJ = obj.value;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ\n\n";
	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\n\n";
	}
	//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\n\n";
	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!";
			erro +="CNPJ inválido. Digite novamente.";
	}
	if (erro.length > 0){
	        alert(erro);
			obj.value='';
			obj.focus();
	        return false;
	} else {
	        //alert("CNPJ válido!");
	}
	return true;
}

function FormataCNPJ(Campo, teclapres){
   if(window.event){
    var tecla = teclapres.keyCode;
   }else  tecla = teclapres.which;

   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1;

  
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
}

function FormataCPF(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	if(tecla != 9 && tecla !=8){
	if(tam > 3 && tam < 7)
	Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
	if(tam >= 7 && tam <10)
	Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
	if(tam >= 10 && tam < 12)
	Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
	}
} 

var valido;
function ValidaEmail(obj){
	//Form = document.cadastrosite;
	var str = obj.value;
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if(filter.test(str)){
	  valido = true;
	}else{
	  if(obj.value.length!=0){
		  alert("E-mail inválido.");
		  obj.value='';
		  valido = false;
	  }
	}
	return valido;
}

function compareDates(data1, data2, obj){
	//Verifica se data2 é maior que data1
	//var data1 = "10/10/2000";
	//var data2 = "15/10/2000";
	
	if(data2.length == 10){
		if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) >= parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) )
		{
		  //alert( "maior" );
		  //return false;
		}
		else
		{
		  //alert( "menor" );
		  alert("A data de término dever ser maior que a data de início.");
		  obj.value='';
		  obj.focus();
		  return false;
		}
	}
}

/*Verifica se data é válida*/
function checaData(obj){//função de validação das data
	if(obj.value.length > 0){
		var min_year=1950;
		var dia=obj.value.substr(0,2),mes=obj.value.substr(3,2),ano=obj.value.substr(6,4);
		if (isNaN(dia) || isNaN(mes) || isNaN(ano)){//verifica se e numerico
			alert("A data deve ser numérica");
			obj.value='';
			return(false);
		}
		if (dia<=0 || dia>31 || mes<=0 || mes>12 || ano<min_year){
			alert("A data é invalida");
			obj.value='';
			return(false);
		}
		if (mes==2 && dia>28){
			alert("A data é invalida");
			obj.value='';
			return(false);
		}
		if (mes==4 || mes==6 || mes==9 || mes==11){
			if (dia>30){
				alert("A data é invalida");
				obj.value='';
				return(false);
			}
			return(true);
		}
		return(true);
	}
}

/*Janela opaca para edição*/

end_opacity = 50; //end opacity, 25 = 25%, 50 = 50%, 100 = 100%, etc.
increase_opacity_by = 10; //how much to increase by each time the timeout ends
timeout = 100; //timeout in miliseconds, 0 = instant fade-out

win = document.getElementById('thewindow');
winbackground = document.getElementById('thewindowbackground');
wincontent = document.getElementById('thewindowcontent');
cur_opacity = 0;

var timer = null;

function showWindow(page,n) {
	window.ifrEdit.location.href=page+'?id='+n;
	
	if(timeout > 0) {
		cur_opacity = 0;
	
		winbackground.style.opacity = cur_opacity / 100;
		winbackground.style.filter = "alpha(opacity=" + cur_opacity + ")";
		win.style.display = 'block';
		wincontent.style.display = 'none';
	
		timer = setTimeout("increase_opacity()",timeout);
	}
	else {
		winbackground.style.opacity = end_opacity / 100;
		winbackground.style.filter = "alpha(opacity=" + end_opacity + ")";
		win.style.display = 'block';
		wincontent.style.display = 'block';
	}
}

function increase_opacity() {
	cur_opacity += increase_opacity_by;

	winbackground.style.opacity = cur_opacity / 100;
	winbackground.style.filter = "alpha(opacity=" + cur_opacity + ")";
	
	if(cur_opacity < end_opacity) {
		timer = setTimeout("increase_opacity()",timeout);
	}
	else {
		wincontent.style.display = 'block';
	}
}

function hideWindow() {
	win.style.display = 'none';
}

function formatar_moeda(campo, separador_milhar, separador_decimal, tecla) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? tecla.which : tecla.keyCode;
	
	if (whichCode == 13) return true; // Tecla Enter
	if (whichCode == 8) return true; // Tecla Delete
	if (whichCode == 9) return true; // Tecla TAB
	if (whichCode == 0) return true; // Tecla TAB FireFox
	key = String.fromCharCode(whichCode); // Pegando o valor digitado
	if (strCheck.indexOf(key) == -1) return false; // Valor inválido (não inteiro)
	len = campo.value.length;
	for(i = 0; i < len; i++)
	if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_decimal)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) campo.value = '';
	if (len == 1) campo.value = '0'+ separador_decimal + '0' + aux;
	if (len == 2) campo.value = '0'+ separador_decimal + aux;

	if (len > 2 && len < 7) {//&& len < 7 limita a moeda em 4 posições e 2 casas decimais
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += separador_milhar;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}

		campo.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		campo.value += aux2.charAt(i);
		campo.value += separador_decimal + aux.substr(len - 2, len);
	}

	return false;
}

function formatar_decimal(campo, separador_milhar, separador_decimal, tecla) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? tecla.which : tecla.keyCode;
	
	if (whichCode == 13) return true; // Tecla Enter
	if (whichCode == 8) return true; // Tecla Delete
	if (whichCode == 9) return true; // Tecla TAB
	if (whichCode == 0) return true; // Tecla TAB FireFox
	key = String.fromCharCode(whichCode); // Pegando o valor digitado
	if (strCheck.indexOf(key) == -1) return false; // Valor inválido (não inteiro)
	len = campo.value.length;
	for(i = 0; i < len; i++)
	if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_decimal)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) campo.value = '';
	if (len == 1) campo.value = '0'+ separador_decimal + '0' + aux;
	if (len == 2) campo.value = '0'+ separador_decimal + aux;

	if (len > 2 && len < 4) {
		aux2 = '';

		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += separador_milhar;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}

		campo.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		campo.value += aux2.charAt(i);
		campo.value += separador_decimal + aux.substr(len - 2, len);
	}

	return false;
}
