//---------------------ATENÇÃO-----------------------//
//-----TODOS OS CÓDIGOS UTILIZADOS NESSA PÁGINA------//
//----SÃO DE AUTORIA DA GENIART E DEMAIS AUTORES-----//
//-------DEVIDAMENTE IDENTIFICADOS PELO NOME.--------//
//------A UTILIZAÇÃO INDEVIDA DOS CÓDIGOS SEM O------//
//------CONSENTIMENTO POR PARTE DA GENIART SERÁ------//
//---TRATADO SEGUNDO AS LEIS DE DIREITOS AUTORAIS----//
//---------------------------------------------------//

function validaCampos(qual){
	if(qual == "2"){
		with (document.frm_cadastro){
			if(txt_nome.value == ""){
				alert('Por favor informe seu nome');
				txt_nome.focus();
				return false;
			}
			if(txt_email.value == ""){
				alert('Por favor informe seu e-mail');
				txt_email.focus();
				return false;
			}else if (!validaEmail(txt_email, "frm_contato", 2)){
				txt_email.focus();
				txt_email.select();
				return false;
			}else{
				submit();
				return true;
			}
		}
	}else if(qual == "1"){
		with (document.frm_contato){
			if(txt_nome.value == ""){
				alert('Por favor informe seu nome');
				txt_nome.focus();
				return false;
			}
			if(txt_email.value == ""){
				alert('Por favor informe seu e-mail');
				txt_email.focus();
				return false;
			}
			if(ls_assunto.value == "NM"){
				alert('Por favor selecione o assunto');
				ls_assunto.focus();
				return false;
			}
			if(txt_mensagem.value == ""){
				alert('Por favor digite uma mensagem');
				txt_mensagem.focus();
				return false;
			}
			
			if(ls_conheceu.value == "NM"){
				alert('Por favor informe como nos conheceu');
				ls_conheceu.focus();
				return false;
			}
			submit();
			return true;
		}
	}else if(qual == "3"){
		with (document.frm_endereco){
			if(st_endereco.value == ""){
				alert('O campo Endereço é obrigatório.');
				st_endereco.focus();
				return false;
			}else if(st_numero.value == ""){
				alert('O campo Número é obrigatório.');
				st_numero.focus();
				return false;
			}else if(st_bairro.value == ""){
				alert('O campo Bairro é obrigatório.');
				st_bairro.focus();
				return false;
			}else if(ls_uf.value == "0"){
				alert('O campo Estado é obrigatório.');
				ls_uf.focus();
				return false;
			}else if(st_cidade.value == ""){
				alert('O campo Cidade é obrigatório.');
				st_cidade.focus();
				return false;
			}else if(st_fone.value == ""){
				alert('O campo Telefone é obrigatório.');
				st_fone.focus();
				return false;
			}else{
				submit();
				return true;
			}
		}
	}
}

function validaCnpj(cnpj) {
//	alert(cnpj);
	CNPJ = cnpj;
	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 +="CNPJ Inválido!";
	}
	if (erro.length > 0){
//		alert(erro);
		return false;
	}
	return true;
}

function criaLista(p, l){
// 	if(l == "bairro"){
// 		with(document.frm_busca){
// 			for(var i = 0; i < ls_bairro.options.length; i++){
// 				ls_bairro.options[i] = '';
// 			}
// 		}
// 	}
	window.open('cria_lista.php?listar=' + l + '&p=' + p, 'ifr_executa');
}

function mostraImagem(a,l,pg){
	l = eval(l) + 17;
	a = eval(a) + 4;
	if(a > 427) a = 435
	if(l > 640) l = 660
	nova_janela = window.open('','mostra_imagem','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,menubar=no,width=' +l+ ',height=' + a);
	nova_janela.document.writeln('<HTML><HEAD><TITLE></TITLE></HEAD><BODY style="margin=0px;text-align=center;"><IMG style="cursor=hand;" src="'+pg+'" onClick="window.close()" alt="Clique na imagem para fechar"></BODY></HTML>');
	nova_janela.document.close();
}

// Valida endereço de e-mail
function validaEmail(email){
	var resultado = false
	var emailStr = new String(email)
	var index = emailStr.indexOf("@");
	if (index > 0){
		var indice = emailStr.indexOf(".",index);
		if ((indice > index+1) && (emailStr.length > indice+1)){
			resultado = true;
		}
	}
	return resultado;
}

//Formata CEP
function ajustarCep(input, evento){
    if(!soNumero(evento)){
	    return false;
	} else { 
		if (input.value.length == 5) {
		   input.value = input.value + "-";
		}
	}
	return true;
}

function ajustarCpf(input, evento){
	tecla = evento.keyCode;
    if(!soNumero(evento)){
	    return false;
	}else{
		if((tecla<48)||(tecla>57)){
			evento.returnValue =false;
			return false;
		}else{
			if ((input.value.length == 3)||(input.value.length == 7)) {
				input.value = input.value + "." ;
			}
			if (input.value.length == 11) {
				input.value = input.value + "-" ;
			}
			if(input.value.length == 15){
				input.value = input.value.replace('.','');
				input.value = input.value.replace('.','');
				input.value = input.value.replace('-','');
				input.value = input.value.substr(0, 2) + '.' + input.value.substr(2, 3) + '.' + input.value.substr(5, 3) + '/' + input.value.substr(8, 4);
				input.value = input.value + "-" ;
			}
		}
	}
	return true;
}

function ajustarFone(input, evento){
	var tecla = evento.keyCode;
	valor = input.value;
	valor = valor.replace( "(", "" );
	valor = valor.replace( ")", "" );
	valor = valor.replace( " ", "" );
	valor = valor.replace( "-", "" );
	tamanhoMaximo = 10;
	tamanho = valor.length;
    if(!soNumero(evento)){
	    return false;
	} else { 
		if (tamanho < tamanhoMaximo && tecla != 8) {
		tamanho = valor.length + 1 ;
		}
		if (tecla == 8 ) {
			tamanho = tamanho - 1 ;
		}
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
			if ( tamanho <= 4 ) { 
		 		input.value = valor ;
			}
		 	if ( (tamanho > 4) && (tamanho <= 8) ) {
		 		input.value = valor.substr(0,tamanho-4) + '-' + valor.substr( tamanho - 4, tamanho ) ;
			}
		 	if ( (tamanho >= 9) && (tamanho <= 10) ) {
				input.value = '(' + valor.substr(0,2) + ') ' + valor.substr(2,tamanho-6) + '-' + valor.substr(tamanho-4,tamanho) ;			
			}
		}
	}
	return true;
}

//Completa a data com as barras "/"
function ajustarData(input, evento){
    if(!soNumero(evento)){
	    return false;
	} else { 
		if ((input.value.length == 2)||(input.value.length == 5)) {
		   input.value = input.value + "/" ;
		   }
	}
	return true;
}

function soNumero(evento){
	var BACKSPACE=  8; 
	var TAB= 9;
    var DEL=  46; 
    var FRENTE=  39; 
    var TRAS=  37; 
    var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
    
    if (( tecla == BACKSPACE )||(tecla == DEL)||(tecla == FRENTE)||(tecla == TRAS)||(tecla == TAB)){
         return true; 
	}
    if ( tecla == 13 )     return false; 

	if ((tecla >= 48 && tecla <= 57) || (tecla == 44)) {
		return true;
	}else{
		evento.returnValue = false; 
		return false;
	}
}

function abreDigitacao(fim, tpCampos, sel){
	var campo1 = document.getElementById("tt_indique");
	var campo2 = document.getElementById("cont_indique");
	if(tpCampos == 2){
		if((sel != "Indicacao") && (sel != "Outros")){
			fim = 0;
		}
	}
	if(fim == 1){
		campo1.style.display="";
		campo2.style.display="";
	}else if(fim == 0){
		campo1.style.display="none";
		campo2.style.display="none";
	}
}

function acrescentaValor(idProduto, opcao, valor){
	var valorTotal;
	var novoValor;
	var tudoOk = false;
	
	// econtra o campo referente ao produto escolhido
	campoValor = eval('document.frm_cesta.qtde_'+idProduto);
	
	// econtra o campo referente ao produto escolhido
	campoQtdeEspec = eval('document.frm_cesta.qtde_espec_'+idProduto);
	
	if(opcao == ">"){
	
		// Para produtos especiais
		if(valor != 0){
			// Qtde
			novoValor = parseInt(Math.abs(campoQtdeEspec.value)) + 1;
			// Qtde no campo
			campoQtdeEspec.value = novoValor;
			tudoOk = true;
		// Para produtos normais
		}else{
			// acrescenta a qtde
			novoValor = parseInt(Math.abs(campoValor.value)) + 1;
			// joga o valor no html
			campoValor.value = novoValor;
			tudoOk = true;
		}
		
	}else if(opcao == "<"){
		
			// Para produtos especiais
			if(valor != 0){
				if(campoQtdeEspec.value != '1'){
					// Qtde
					novoValor = parseInt(Math.abs(campoQtdeEspec.value)) - 1;
					// Qtde no campo
					campoQtdeEspec.value = novoValor;
					tudoOk = true;
				}
			// Para produtos normais
			}else{
				if(campoValor.value != '1'){
					// acrescenta a qtde
					novoValor = parseInt(Math.abs(campoValor.value)) - 1;
					// joga o valor no html
					campoValor.value = novoValor;
					tudoOk = true;
				}
			}
		
	}
}

function novaJanela(l,a){
	window.open('','janela','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=no,menubar=no,width='+l+',height='+a);
}

function abreDescricao(id){
	window.open('descricao.php?id='+id,'ifr_executa');
}

function limpaDesc(){
	var div = document.getElementById("popGeral");
	div.style.display = "none";
}

function selsProdutos(q) {
	var ps = 0;
	for (var i = 0; i < q; i++) { if (document.getElementById('ps_'+i)) { if (document.getElementById('ps_'+i).checked) { ps++;  } } }
	
	if (ps > 0) {
		document.frm_cesta.submit();
	} else {
		alert("Não foi selecionado nenhum produto.");
	}
}

function selVend() {
	if (document.getElementById('fk_vendedor').selectedIndex > 0) {
		document.frm_cesta.submit();
	} else {
		alert('Selecione um vendedor');
	}
}

function janelaEnd(id, cp) {
	if (!cp) { cp = 'nao'; }
	window.open("endereco.php?id="+id+"&cp="+cp, 'Endereço', 'width=520,height=283,scrollbars=0');
}

function trocaSenha() {
	window.open("troca_senha.php", "_blank", "scrollbars=0, width=350, height=210");
}

function validaCadastro(){
	with(document.frm_cadastro){
		if (st_razao.value == ""){
			alert("Por favor informe sua Razão Social.");
			st_razao.focus();
			return false;
		}else if(st_cnpj.value == ""){
			alert("Por favor informe seu CNPJ.");
			st_cnpj.focus();
			return false;
		}else if (!validaCnpj(st_cnpj.value)){	
			alert("CNPJ inválido!");
			st_cnpj.focus();
			return false;
		}else if(st_email.value == ""){
			alert("Por favor informe seu Email.");
			st_email.focus();
			return false;
		}else if (!validaEmail(st_email.value)){
			alert("Email inválido!.");
			st_email.focus();
			return false;	
		}else if (st_senha.value == ""){
			alert("Por favor informe sua Senha.");
			st_senha.focus();
			return false;
		}else if (st_senha_confirma.value==""){
			alert("Por favor redigite a sua Senha.");
			st_senha_confirma.focus();
			return false;
		}else if (st_senha_confirma.value != st_senha.value){
			alert("As senhas não conferem.");
			return false;
		}else{
			submit();
			return true;
		}
	}
	
}
