// JavaScript Document

<!-- Validação de Resolução
if (parseInt(navigator.appVersion) >= "4") {

	if (screen.width <= "800") {
		var ck_qtde_linhas = 16; //qtde de linhas das listagens
	}

	if (screen.width > "800") {		
		var ck_qtde_linhas = 19;
	}
	
	//cookie com a qtde de linhas das listagens
	deleteCookie("qtde_linhas");
	setCookie("qtde_linhas",ck_qtde_linhas);
}
//-->

function paginar(local){
	window.location = local;
}

function getCookie(name) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function setCookie(name,value,path,domain,secure) {
	var today = new Date();
	var zero_date = new Date(0,0,0);
	today.setTime(today.getTime() - zero_date.getTime());
	var expires = new Date(today.getTime() + (8 * 7 * 86400000)); 

	var cookieString = name + "=" +escape(value) +
		 ( (expires) ? ";expires=" + expires.toGMTString() : "") +
		 ( (path) ? ";path=" + path : "") +
		 ( (domain) ? ";domain=" + domain : "") +
		 ( (secure) ? ";secure" : "");
	document.cookie = cookieString;
}

function deleteCookie(name,path,domain) {
   if (getCookie(name)) document.cookie = name + "= '' " +
      ( (path) ? ";path=" + path : "") +
      ( (domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
} 

function confirmBox(texto)
{
	if (confirm("Tem certeza que deseja excluir "+texto+"?"))
	{
		location.href="delete.php";
	}
	else
	{
		 return false;
	}
}

function validarFormulario(formulario){
	var erros = "Erros Encontrados:\n\n";
	
	for(var i = 0; i < formulario.elements.length; i++){
		
		if(formulario.elements[i].type == "text" || formulario.elements[i].type == "textarea" || formulario.elements[i].type == "password"){
			
			if(formulario.elements[i].alt == "*" && formulario.elements[i].value == ""){
				erros += "* Campo "+formulario.elements[i].id+" não preenchido!\n";
			}
			if(formulario.elements[i].title == "*" && formulario.elements[i].value == ""){
				erros += "* Campo "+formulario.elements[i].id+" não preenchido!\n";
			}
			
		}else if(formulario.elements[i].type == "select-one"){
			
			var index = formulario.elements[i].selectedIndex;
							
			if(formulario.elements[i].title == "*" && formulario.elements[i].options[index].value == "0"){
				erros += "* Campo "+formulario.elements[i].id+" não selecionado!\n";
			}
			
		}			
	}
	if(erros != "Erros Encontrados:\n\n"){
		alert(erros);
		return false;
	}else{
		return true;
	}
}
	

function excluir(local){
	if(confirm('Deseja Realmente Excluir este Registro?')){
		window.location = local;
	}
}

/***********************************************/
/* Funcao mapearTeclado(caracter) 
/* 		descricao: permite o mapeamento de teclas
/*							digitadas pelo usuario no documento
/*		uso: <body onkeydown="mapearTeclado(event);">
/************************************************/
function mapearTeclado(caracter) {
	if(document.all) { // Internet Explorer
		var tecla = event.keyCode;
	} else if(document.layers) { // Nestcape
		var tecla = caracter.which;
	} else {
		var tecla = caracter.which;				
	}
	
	if(tecla == 27) { // tecla ESC
		window.close();
	} else {
		return false;
	}			
}

/***********************************************/
/* Funcao apenasnumericos(caracter) 
/* 		descricao: permite apenas a digitação 
/*								de caracteres numericos.
/*		uso: <input type="text" name="onono" onKeyPress="apenasnumericos(event);">
/************************************************/
function apenasnumericos(caracter) {
	if(document.all) { // Internet Explorer
		var tecla = event.keyCode;
	} else if(document.layers) { // Nestcape
		var tecla = caracter.which;
	} else {
		var tecla = caracter.which;				
	}
	
	if(tecla > 47 && tecla < 58) { // numeros de 0 a 9
		return true;
	} else {
		if (tecla != 8) { // backspace
			return false;
		} else {
			return true;
		}
	}			
}

/*************************************************************/
/* Funcao txtBoxFormat(objForm, strField, sMask, evtKeyPress)
/* 		descricao: formata um campo de acordo com a mascara informada.
/*		uso: <input type="text" name="data" onKeyPress="txtBoxFormat(formulario, 'data', '99/99/9999', event);">
/**************************************************************/
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 {
		nTecla = evtKeyPress.which;
		if (nTecla == 8) {
				return true;
		}
	}
	
	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( " ", "" );
	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) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((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;
	}
}
		
/*******************************************************/
/* Funcao para validar um e-mail
/******************************************************/		
function ValidaEmail(obj) {			
	if(obj.value != ""){
		if (obj.value.indexOf ('@',0) == -1 || obj.value.indexOf ('.',0) == -1){
			alert("Esse não é um e-mail válido!\nPor favor entre com um e-mail válido.")
			obj.focus();   
		}			
	}
}
		
		
/*******************************************************/
/* Funcao para validar um CPF no formato 999.999.999-99
/******************************************************/
function validarCpf(pcpf){
	campo = pcpf;
	pcpf = pcpf.value;
	
	pcpf = pcpf.toString().replace( ".", "" );
	pcpf = pcpf.toString().replace( ".", "" );
	pcpf = pcpf.toString().replace( ".", "" );
	pcpf = pcpf.toString().replace( "-", "" );
	
	if (pcpf.length == 0) {return false;}
	if (pcpf.length != 11) {sim=false}
	else {sim=true}

	if (sim )  // valida o primeiro digito
	{
	for (i=0;((i<=(pcpf.length-1))&& sim); i++)
	{
	 val = pcpf.charAt(i)
	 if

 ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4")

 &&    (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {sim=false}
	 }

	 if (sim)
	{
	soma = 0
	for (i=0;i<=8;i++)
	{
	 val = eval(pcpf.charAt(i))
	 soma = soma + (val*(i+1))
	}

	resto = soma % 11
	if (resto>9) dig = resto -10
	else  dig = resto
	if (dig != eval(pcpf.charAt(9))) { sim=false }
	 else   // valida o segundo digito
	{

	 soma = 0
	for (i=0;i<=7;i++)
	 {
	 val = eval(pcpf.charAt(i+1))
		soma = soma + (val*(i+1))
	}

	 soma = soma + (dig * 9)
	resto = soma % 11
	 if (resto>9) dig = resto -10
	 else  dig = resto
	 if (dig != eval(pcpf.charAt(10))) { sim = false }
	else sim = true
	 }
	 }
	}

	if (sim) { 
		//alert("Valor Valido de CPF") ;
		return true;
	}else{
		alert("Erro Encontrado:\n\n* CPF Inválido!");
		campo.focus();
		return false;
	}
}
	
/*******************************************************/
/* Funcao converter um valor de 1.000,00 para 1000.00
/******************************************************/		
function converte_val(valor){
	valor = valor.replace('.','');
	valor = valor.replace(',','.');
	return valor;
}		
		
//formata 5000 em 5.000,00 
function formata_valor(numero) {				
	if(numero.substr(numero.length - 3,1) == "." || numero.substr(numero.length - 3,1) == ","){
		if(numero.substr(numero.length - 3,1) == "."){
			numero_formatado = numero.replace(",","");
			numero_formatado = numero_formatado.replace(",","");
			numero_formatado = numero_formatado.replace(",","");
			numero_formatado = numero_formatado.replace(",","");
		}else{
			if(numero.substr(numero.length - 3,1) == ","){
				numero_formatado = numero.replace(".","");						
				numero_formatado = numero_formatado.replace(".","");
				numero_formatado = numero_formatado.replace(".","");
				numero_formatado = numero_formatado.replace(".","");
				numero_formatado = numero_formatado.replace(",",".");
			}
		}
		numero_formatado = (parseFloat(numero_formatado) * 100);				
		numero_formatado = Math.round(numero_formatado);
		numero_formatado = (parseFloat(numero_formatado) / 100);								
		numero_formatado = numero_formatado.toString();				
		var tam = numero_formatado.length;
		if ( tam <= 1 ){
		numero_formatado = '0,0' + numero_formatado.substr( tam - 2, tam ); }
		if ( tam == 3 ){
		numero_formatado = numero_formatado.substr( 0, tam - 2 ) + ',' + numero_formatado.substr( tam - 1, tam )+'0'; }
		if ( (tam >= 4) && (tam <= 6) ){
		numero_formatado = numero_formatado.substr( 0, tam - 3 ) + ',' + numero_formatado.substr( tam - 2, tam ); }
		if ( (tam >= 7) && (tam <= 9) ){
		numero_formatado = numero_formatado.substr( 0, tam - 6 ) + '.' + numero_formatado.substr( tam - 6, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 10) && (tam <= 12) ){
		numero_formatado = numero_formatado.substr( 0, tam - 9 ) + '.' + numero_formatado.substr( tam - 9, 3 ) + '.' + numero_formatado.substr( tam - 6, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 13) && (tam <= 15) ){
		numero_formatado = numero_formatado.substr( 0, tam - 12 ) + '.' + numero_formatado.substr( tam - 12, 3 ) + '.' + numero_formatado.substr( tam - 8, 3 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 16) && (tam <= 18) ){
		numero_formatado = numero_formatado.substr( 0, tam - 15 ) + '.' + numero_formatado.substr( tam - 15, 3 ) + '.' + numero_formatado.substr( tam - 11, 3 ) + '.' + numero_formatado.substr( tam - 8, 3 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ;}
	}else{
		numero_formatado = (parseFloat(numero) * 1000)/10;
		numero_formatado = Math.round(numero_formatado);
		numero_formatado = parseFloat(numero_formatado);
		numero_formatado = numero_formatado.toString();
		var tam = numero_formatado.length;
		if ( tam <= 1 ){
		numero_formatado = '0,0' + numero_formatado.substr( tam - 2, tam ); }
		if ( tam == 2 ){
		numero_formatado = '0,' + numero_formatado.substr( tam - 2, tam ); }
		if ( (tam > 2) && (tam <= 5) ){
		numero_formatado = numero_formatado.substr( 0, tam - 2 ) + ',' + numero_formatado.substr( tam - 2, tam ); }
		if ( (tam >= 6) && (tam <= 8) ){
		numero_formatado = numero_formatado.substr( 0, tam - 5 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 9) && (tam <= 11) ){
		numero_formatado = numero_formatado.substr( 0, tam - 8 ) + '.' + numero_formatado.substr( tam - 8, 3 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 12) && (tam <= 14) ){
		numero_formatado = numero_formatado.substr( 0, tam - 11 ) + '.' + numero_formatado.substr( tam - 11, 3 ) + '.' + numero_formatado.substr( tam - 8, 3 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ; }
		if ( (tam >= 15) && (tam <= 17) ){
		numero_formatado = numero_formatado.substr( 0, tam - 14 ) + '.' + numero_formatado.substr( tam - 14, 3 ) + '.' + numero_formatado.substr( tam - 11, 3 ) + '.' + numero_formatado.substr( tam - 8, 3 ) + '.' + numero_formatado.substr( tam - 5, 3 ) + ',' + numero_formatado.substr( tam - 2, tam ) ;}
	}
	return numero_formatado;		
}
		 
function tiraDizima(valor){
	var ind = valor.indexOf('.');
	var decimal = "";
	
	if(ind != -1){
		decimal = valor.substr(ind+1,2);
		valor = valor.substr(0,ind+1) + decimal;
		return formata_valor(valor);
	}else{
		return formata_valor(valor);
	}
}

/*********************************************/
/* Funcao de Mascara para Horas
/*  onkeypress=" txtFormatHora(this.value);"
/*********************************************/
function txtFormatHora(f){
	var s = document.formulario.hora.value;
	if(document.formulario.hora.value.length == 2){
		f = f + ":" + s.substr(2,2);
		document.formulario.hora.value = f;
	}
}
		
		
/***
* AUTO TAB - ao prencher o campo, automaticamente manda o foco para o próximo!
***/
//var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
		var keyCode = (isNN) ? e.which : e.keyCode;
		var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
		if(input.value.length >= len && !containsElement(filter,keyCode)) {
				input.value = input.value.slice(0, len);
				input.form[(getIndex(input)+1) % input.form.length].focus();
		}

function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
				found = true;
		else
				index++;
				return found;
		}

function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
				if (input.form[i] == input)index = i;
				else i++;
				return index;
		}
		return true;
}
//Fim da Função AutoTab
		
		
/*************************************************************/
/* Funcao para mudar a cor da linha da tabela de listagem
/* 	parametros:
/*		@id : sequencia associado a linha da tabela
/*		@classe : classe ultilizada pela linha atualmente
/*************************************************************/
function colorir(id, qtde_colunas){
	var style_class = "";
	
	for(var i = 1; i <= qtde_colunas; i++){

		if(i == 1){
			style_class = "text_consulta_selecionado_left";
		}else if(i > 1 && i < qtde_colunas){
			style_class = "text_consulta_selecionado_center";
		}else if(i == qtde_colunas){
			style_class = "text_consulta_selecionado_right";
		}
		
		eval("document.getElementById('coluna"+i+""+id+"').className = style_class");				
	}
	
}

function descolorir(id, classe, qtde_colunas){
	for(var i = 1; i <= qtde_colunas; i++){
		eval("document.getElementById('coluna"+i+""+id+"').className = classe");
	}
}


/*******************************************************/
/* Funcao para permitir que a tecla ENTER seja usada para postar o formulario
/******************************************************/
function consultarEnter(caracter) {
	if(document.all) { // Internet Explorer
		var tecla = event.keyCode;
	} else if(document.layers) { // Nestcape
		var tecla = caracter.which;
	} else {
		var tecla = caracter.which;				
	}
	
	if(tecla == 13) { // tecla enter
		document.formulario.submit();
		return true;
	}		
}

/************************************************************/
/* Funcao para validar um CNPJ no formato 99.999.999/9999-99
/************************************************************/
function validarCnpj(obj) {
	CNPJ = obj.value;
	erro = new String;
	
	if(CNPJ != ""){
		if (CNPJ.length < 18) erro += "E' necessario preencher corretamente o numero do CNPJ! \n\n";
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "E' necessario preencher corretamente o numero do CNPJ! \n\n";
		}
		//substituir os caracteres que nao sao numeros
		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 verificacao de CNPJ suporta apenas numeros! \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 +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			alert(erro);
			return false;
		} else {
			//alert("CNPJ válido!");
		}
	}
	return true;
}

	/******************************************/
	/* Funcao para destacar a borda dos campos
	/*  que estao sendo preenchidos.
	/******************************************/
	
	function destacarBorda(obj){
		var classe_atual = obj.className;
		var classe_borda = "campo_selecionado";
		
		if(classe_atual == ""){
			obj.className = classe_borda;
		}else if(classe_atual == classe_borda){
			obj.className = "";
		}
	}
	
	function exibirConfirmacao(act){
		var msg = "";
		//cadastro ja existe
		if(act == "ce"){
				msg = "* Este CPF já está Cadastrado!";
				document.getElementById('CPF').focus();
		}
		
		if(act == "nc"){
				msg = "* Este CPF não está Cadastrado!";
				document.getElementById('CPF').focus();
		}
		
		if(act == "si"){
				msg = "* Senha Incorreta!";
				document.getElementById('CPF').focus();
		}
		
		if(msg != ""){
			alert("AVISO:\n\n"+msg);
		}
	}