// JavaScript Document

function valida_valor( campo ) {
    texto = campo.value;
	var lugar = '';
	var c = 0;
    for( ; c < texto.length; c++){
	  if(texto.charAt(c) == "," || texto.charAt(c) == ":"){
	     alert("Para separar casas decimais, use PONTO e não vírgula.");
		 campo.focus();
	  }
	  
	}   
}

function click() {
if (event.button==2||event.button==3) {
 oncontextmenu='return false';
  }
}

function soNums(e,args){         

	var evt= (e.keyCode?e.keyCode:e.charCode); 
	var chr= String.fromCharCode(evt);    // pegando a tecla digitada 
	// Se o código for menor que 20 é porque deve ser caracteres de controle 
	// ex.: <ENTER>, <TAB>, <BACKSPACE> portanto devemos permitir 
	// as teclas numéricas vao de 48 a 57 
	return (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ); 
}

function soLetra(e,args){         

	var evt= (e.keyCode?e.keyCode:e.charCode); 
	var chr= String.fromCharCode(evt);    // pegando a tecla digitada 
	// Se o código for menor que 20 é porque deve ser caracteres de controle 
	// ex.: <ENTER>, <TAB>, <BACKSPACE> portanto devemos permitir 
	// as teclas numéricas vao de 48 a 57 
	return (evt <20 || (evt >65 && evt<122) || (args.indexOf(chr)>-1 ) ); 
}


function valida_numero( campo ) {
    texto = campo.value;
	var lugar = '';
	var c = 0;
    for( ; c < texto.length; c++){
	  if(texto.charAt(c) != "0" || texto.charAt(c) != "1" || texto.charAt(c) != "2" || texto.charAt(c) != "3" || texto.charAt(c) != "4" || texto.charAt(c) != "1"){
	     alert("Para separar casas decimais, use PONTO e não vírgula.");
		 campo.focus();
	  }
	  
	}   
}

function validarLogin(campo) {
	    var val = campo.value;
		if (val == "") {
			alert('Digite o Login!');
			campo.value = "";
			campo.focus();
			return false;		
		} else {
			return true;
		}
	}
	
	function validarSenha(campo){
		var val = campo.value;
		if (val.length < 6) {
			alert('A senha não deve conter menos de 6(seis) dígitos');
			campo.value = "";
			campo.focus();
			return false;
		}else{
			return true;
		}
	}

	function auto_cpf( campo ) {
	    texto = campo.value;
	    if( texto.length == 3 ) {
    	    texto += '.';
	    } else if( texto.length == 7 ) {
	        texto = texto + '.';
	    } else if( texto.length == 11 ) {
    	    texto = texto + '-';
	    }
    	campo.value = texto;
	}

	function validar_cpf( campo ) {
		texto = campo.value;
		if( texto != '' ) {
			if( texto.length != 14 ) {
				alert( 'CPF Inválido' );
				campo.focus();
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	}

	function auto_data( campo ) {
	    texto = campo.value;
    	if( texto.length == 2 ) {
	        texto += '/';
    	    campo.value = texto;
	    } else if( texto.length == 5 ) {
	        texto += '/';
	        campo.value = texto;
    	}
	}

	function auto_hora( campo ) {
	    texto = campo.value;
    	if( texto.length == 2 ) {
	        texto += ':';
    	    campo.value = texto;
	    } 
	}
	
	function valida_data( campo ) {
		data = campo.value;
		resultado = true;
	
		if( data != "" ) {
			if( data.charAt(0) != '0' ) {
				dia = data.charAt(0) + data.charAt(1);
			} else {
				dia =data.charAt(1);
			}
			dia = parseInt(dia);
	
			if( data.charAt(3) != "0" ) {
				mes = data.charAt(3) + data.charAt(4);
			} else {
				mes = data.charAt(4);
			}
			mes = parseInt(mes);
	
			if( data.charAt(6) != '0' && data.charAt(7) != '0' && data.charAt(8) != '0' ) {
				ano = data.charAt(7) + data.charAt(8) + data.charAt(9);
			} else if( data.charAt(7) != '0' && data.charAt(8) != '0' ) {
				ano = data.charAt(8) + data.charAt(9);
			} else if( data.charAt(8) != '0' ) {
				ano = data.charAt(9);
			} else {
				ano = data.charAt(6) + data.charAt(7) + data.charAt(8) + data.charAt(9);
			}
			ano = parseInt(ano);
	
			if( campo.value.length != 10 ) {
				alert( "Data Inválida!\nVerifique a quantidade de dígitos" );
				campo.focus();
				resultado = false;
			} else if( (mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia > 30 ) {
				alert( "Data Inválida!\nEsse mês não permite dia 31" );
				campo.focus();
				resultado = false;
			} else if( mes == 2 && dia > 29 ) {
				alert( "Data Inválida!\nFevereiro não permite dia com esse valor" );
				campo.focus();
				resultado = false;
			} else if( campo.value.charAt( 2 ) != '/' || campo.value.charAt( 5 ) != '/' ) {
				alert( "Data Inválida!\nVerifique o formato da data" );
				campo.focus();
				resultado = false;
			} else if( dia < 1 || dia > 31 ) {
				alert( "Data Inválida!\nVerifique o valor do dia" );
				campo.focus();
				resultado = false;
			} else if( mes < 1 || mes > 12 ) {
				alert( "Data Inválida!\nVerifique o valor do mês" );
				campo.focus();
				resultado = false;
			} else if( ano < 0 ) {
				alert( "Data Inválida!\nVerifique o valor do ano" );
				campo.focus();
				resultado = false;
			}
			return resultado;
		}
	}

	function auto_cep( campo ) {
		texto = campo.value;
		if( parseInt(texto.length) == 5 ) {
			texto += "-";
			campo.value = texto;
		}
	}
	
	function auto_placa( campo ) {
		texto = campo.value;
		if( texto.length == 3 ){
			texto += '-';
			campo.value = texto.toUpperCase();
		}
	}
	
	function validar_cep( campo ) {
		if( campo.value != '' ) {
			if( campo.value.length != 9 ) {
				alert( "Valor do CEP é inválido" );
				return false;
				campo.focus();
			} else if( campo.value.charAt(0) == '5' ) {
				return true;
			} else {
				//alert( "Valor de CEP inválido não sei" );
				//campo.focus();
				//return false;
			}
		}
	}	

	function auto_fone(campo){
		var data = campo.value;
	    var ndata = '';
    		ndata = ndata + data;
			if (ndata.length == ''){
				ndata = ndata + '(';
		        campo.value = ndata;
			}else if (ndata.length == 3){
				ndata = ndata + ')';
		        campo.value = ndata;
			}else if (ndata.length == 8){
				ndata = ndata + '-';
		        campo.value = ndata;
			}
    		/*if (ndata.length == 4) {
	 	       ndata = ndata + '-';
		        campo.value = ndata;
    		}*/
	
	}
	
	function auto_inscricao( campo ) {
		texto = campo.value;
		if( parseInt(texto.length) == 2 ) {
			texto += ".";
			campo.value = texto;
		} else if( parseInt(texto.length) == 4 ) {
			texto += ".";
			campo.value = texto;
		} else if( parseInt(texto.length) == 8 ) {
			texto += ".";
			campo.value = texto;
		} else if( parseInt(texto.length) == 16 ) {
			texto += "-";
			campo.value = texto;
		}
	}
	
	function validar_inscricao( campo ) {
		resultado = true;
		if( campo.value != '' ) {
			if( campo.value.length != 18 ) {
				resultado = false;
			} else if( campo.value.charAt( 2 ) != '.' ) {
				resultado = false;
			} else if( campo.value.charAt( 4 ) != '.' ) {
				resultado = false;
			} else if( campo.value.charAt( 8 ) != '.' ) {
				resultado = false;
			} else if( campo.value.charAt(16) != '-' ) {
				resultado = false;
			}
		}
	
		if( resultado == false ) {
			alert( 'Inscrição Estadual inválida' );
			campo.focus();
			return false;
		} else {
			return true;
		}
	}

	function auto_cnpj( campo ) {
		texto = campo.value;
		if( parseInt(texto.length) == 8 ) {
			texto += "/";
			campo.value = texto;
		} else if ( parseInt(texto.length) ==13 ) {
			texto += "-";
			campo.value = texto;
		}
	}
	var ncnpj = new Array;

	function valida_cnpj(Form,nForm){
		if (form1.cnpj.value != '') {
			var Campos = eval('document.' + nForm + '.vcnpj.value');
			var Contador = 0;
			var x = 0;
			var i = Campos.indexOf( "," );
			if (i==-1){
				ncnpj[Contador] = Campos.slice(0,Campos.length);
			} else {
				ncnpj[Contador] = Campos.slice(0,i);
				Campos = Campos.slice(i+1,Campos.length);
				//Rotina que recebe os demais campos
				for (;x<Campos.length;x++){
					if (Campos.slice(x,x+1) == ","){
						Contador = Contador + 1;
						ncnpj[Contador] = Campos.slice(0,x);
						Campos = Campos.slice(x+1,Campos.length);
						x = 0;
					}
				}
				ncnpj[ncnpj.length] = Campos;
			}
			x = 0;
			for (;x<ncnpj.length;x++){
				var Obj = eval ("document." + nForm + "." + ncnpj[x])
				if(!verifica_cnpj(Obj)){
				Obj.focus();
				ncnpj = new Array;
				return false;
			}
		}
	}
	return true;
	}

	function verifica_cnpj(S){
		Testa_Tamanho_do_Numero = true;
		Digitos_Verificadores_cnpj = 2;
		Digitos_cnpj = 14; //xx.xxx.xxx/xxxx-xx tem 14 numeros
		/*
		 * Alem de testar os digitos verificadores as funcoes seguintes
		 * tambem devem testar o tamanho dos numeros fornecidos (no caso
		 * desta constante ser True). Se for colocada como False sera'
		 * somente verificada a igualdade dos digitos verificadores.
		*/
		
		// S - é o OBJETO Text e não o valor!!!
		//Verifica se o string esta' ok (CPF ou cnpj)
		
		var Original = Limpa_cnpj(S);
		var Gerado = "";
		var Tamanho = Digitos_cnpj;  //tamanho esperado para o cnpj
		
		teste = (( !Testa_Tamanho_do_Numero) || (Testa_Tamanho_do_Numero && Original.length == Tamanho));
		//alert("Resposta da condição: "+teste);
		if( teste ) {
			//Gerado = Original;
			//retira digitos verificadores
			Gerado = Original.substring( 0, Original.length - Digitos_Verificadores_cnpj )
			Gerado = Completa_cnpj( Gerado ); //Gera numero completo
			
			cnpj_valido = (Gerado == Original) //compara com original
			//alert("Valor de cnpj_valido: "+cnpj_valido)
			if (!cnpj_valido) {
				alert("O CNPJ (cnpj) é inválido, favor corrigi-lo!");
				S.select();
				S.focus();
				return false
			}else{
				return true
			}
		} else {
			alert("A quantidade de números do cnpj é inválida, favor corrigir.");
			S.select();
			S.focus();
			return false    //Nao tem o tamanho certo
		}
	}

	function Limpa_cnpj( S_aux2 ) {
		//Retira tudo o que nao for numero,
		// mas não tira os números do cnpj
		// S_aux2 - é o objeto Text e não o valor. Prestar atenção!!!
		var SAux = '';
		S = S_aux2.value;
		//alert("cnpj: " + S)
		var pos = 0
		for( ; pos < S.length; pos++ ) {
			if( S.charAt(pos) >= '0' && S.charAt(pos) <= '9' ) {
				SAux = SAux + S.charAt(pos);
			}
			return SAux
		}
	}
	//Completa o numero colocando digitos verificadores
	function Completa_cnpj( S ) {
		//   var SAux = Limpa_String(S);
		var SAux = S;
		var Quantos = Digitos_Verificadores_cnpj;
		var c = 1
		for( ; c <= Quantos; c++ ){
			SAux = SAux + Digito_Verificador_cnpj( SAux );
			return SAux
		}
	}
	//Calcula um digito verificador em funcao do numero
	function Digito_Verificador_cnpj( S ) {
		//   S = Limpa_String(S);
		var soma = 0
		var comprimento = S.length
		var i = 1
		for( ; i <= comprimento; i++ ) {
			// fator = 2,3,4,5,6,7,8,9, 2, 3, 4, 5...
			var fator = 2+( (i-1) % 8 );
			soma = soma + parseInt( S.charAt(comprimento-i) ) * fator
		}
		return ((10*soma) % 11) % 10
	}

	function CNPJ(quadro) {
	
		texto = quadro.value;
		if( parseInt(texto.length) == 8 ) {
			texto += "/";
			quadro.value = texto;
		} else if ( parseInt(texto.length) ==13 ) {
			texto += "-";
			quadro.value = texto;
		}
	}
	
	function auto_cep(quadro) {
		texto = quadro.value;
		if( parseInt(texto.length) == 5 ) {
			texto += "-";
			quadro.value = texto;
		}
	}	

 	function Reload(campo1,campo2){
		var	val = campo1.value;
			if (val == "outro" ) {
				campo2.disabled = false;
				campo2.focus();
			} else {
				campo2.value = '';
				campo2.disabled = true;
			}
	}
	

	function auto_tab(campo1,campo2,qtd) {
		var val = campo1.value;
			if (val.length == qtd) {
				campo2.focus();
			}	
	}
	
	function conf_senha(campo1,campo2) {
		var val1 = campo1.value;
		var val2 = campo2.value;
			if (val1 != val2) {
				alert('A senha não confere');
				campo2.value='';
				campo1.value='';
				campo1.focus();
				return false;
			}
			return true;
	}

	function horario() {
		var data = new Date();
		var hora = data.getHours();	
		var minuto = data.getMinutes();	
		var segundo = data.getSeconds();	
			if (hora < 10) {	
				hora = "0"+hora;
			}
			if (minuto < 10) {
				minuto = "0"+minuto;	
			}
			if (segundo < 10) {
				segundo = "0"+segundo;
		}
			document.all['hora'].innerText =hora+":"+minuto+":"+segundo;
			setTimeout ('horario()',1000);
	}					

	function saudacao() {
		var data = new Date();
		var hora = data.getHours();	
		var dias = data.getDay();
		var cumprimento = '';
		var nomedia = new Array();
		nomedia[0] = "domingo";
		nomedia[1] = "segunda-feira";
		nomedia[2] = "terça-feira";
		nomedia[3] = "quarta-feira";
		nomedia[4] = "quinta-feira";
		nomedia[5] = "sexta-feira";
		nomedia[6] = "sábado";
			if (	hora > 0 &&
				hora < 6 ) {
				cumprimento = 'Bom dia';
			}
			if (	hora >= 6 &&
				hora < 12 ) {
				cumprimento = 'Bom dia';
			}
			if (	hora >= 12 &&
				hora < 18 ) {
				cumprimento = 'Boa tarde';
			}
			if (	hora >= 18 &&
				hora <= 23  ) {
				cumprimento = 'Boa noite';
			}
			//document.write(cumprimento+" "+nomedia[dias]);
			document.write(cumprimento);
	}
	
	function barra(esp_atual,esp_inic) {
		if (esp_atual == 0 ) esp_atual = esp_inic;
		var txt = '';	
		for ( i = 0 ; i <= esp_atual ; i++) {
			txt +=' ';
		}
		txt += 'Sisplan 2.6';
		window.status = txt;
		setTimeout('barra('+ (esp_atual-1)+','+esp_inic+')',100); 
	}
	
	function Pagina(){
		if (self == parent){
			parent.location = "index.php";
		}
	}
	
	function maiuscula(campo){
		var val = campo.value;
			campo.value = val.toUpperCase();
	}
	
	function so_letrasT(campo){

		var tecla = event.keyCode;
		
	
		if(tecla > 65 && tecla < 122){ // LETRAS MAIUSCULAS
			return true;
		}else if(tecla > 47 && tecla < 58){
			alert('Apenas Letras!');
			return false;
			campo.focus();
		}
		
		/*if(val==0 && val==1 && val==2 && val==3 && val==4 && val==5 && val==6 && val==7 && val==8 && val==9){
			alert('Apenas Letras são permitidos!');
			campo.focus();
		}else{
			campo.value = val.toUpperCase();
		}*/
	}
	
	function valida_msn( campo ){
    	if (campo.value !=''){
        	if ( campo.value.indexOf('@')==-1 ||
            	 campo.value.indexOf('.')==-1 ||
	             campo.value.indexOf(' ')!=-1 ||
    	         campo.value.indexOf('@.')!=-1 ||
        	     campo.value.indexOf('.@')!=-1 ||
            	 campo.value.length<6) {
		            alert('MSN inválido');
        		    //form1.email.select();
		            campo.focus();
        		    return false;
	        }
    	}
	}
	
	function valida_email( campo ){
    	if (campo.value !=''){
        	if ( campo.value.indexOf('@')==-1 ||
            	 campo.value.indexOf('.')==-1 ||
	             campo.value.indexOf(' ')!=-1 ||
    	         campo.value.indexOf('@.')!=-1 ||
        	     campo.value.indexOf('.@')!=-1 ||
            	 campo.value.length<6) {
		            alert('E-mail inválido');
        		    //form1.email.select();
		            campo.focus();
        		    return false;
	        }
    	}
	}
	
	function validar_vazio(campo, mensagem) {
    	if(campo.value == '') {
	        alert(mensagem);
    	    campo.focus();
        	return false;
	    } else {
    	    return true;
	    }
	}

	function validar_select(campo, mensagem) {
    	if(campo.value == '---') {
	        alert(mensagem);
    	    campo.focus();
        	return false;
	    } else {
    	    return true;
	    }
	}

	function so_numero( campo ) {

    	if(((event.keyCode < 48) || (event.keyCode > 57)) && event.KeyCode != 8 && event.KeyCode !=13  ) {
        	campo.focus();
	        event.returnValue = false;
    	}
	}
	

// Verifica se somente números foram digitados no campo
function so_numeros ( campo, nome ) {
	var nRet = true;
	var strValidNumber="1234567890";
	for (nCount=0; nCount < campo.value.length; nCount++) 	{
		strTempChar=campo.value.substring(nCount,nCount+1);
		if ( strValidNumber.indexOf(strTempChar,0)==-1) 		{
			alert("O campo " + nome + " deve ser numérico!")
			campo.focus()
			return false;
		}
	} 
	return(nRet);
} 


function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}



function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é requerido.\n'; }
  } if (errors) alert('Ocorreram os Seguintes Erros:\n'+errors);
  document.MM_returnValue = (errors == '');
}
