																												//----------------------------------------------------------------------------
//Nome     : Validação de formulários
//Criacao  : 20041101 17:00PM
//Autor    : Gilberto Russo Jenuino <jenuino@gmail.com>
//Versao   : 1.0.0.0
//Local    : Jundiaí - SP, São Paulo
//Copyright: 2004 by Russo Jenuino, Gilberto
//----------------------------------------------------------------------------
///========================================================================
//função ajax

try {
	ajax = new XMLHttpRequest();
	} catch(ee) {
				try {
					ajax = new ActiveXObject("Msxml2.XMLHTTP");
					} catch(e) {
								try {
									ajax = new ActiveXObject("Microsoft.XMLHTTP");
									} catch(E) {
												ajax = false;
												}
									}
}

//função ajax
function fcAjax(a,b){
	var exibeResultado = document.getElementById(a);
				ajax.open("GET",b, true);
					ajax.onreadystatechange = function(){
					exibeResultado.innerHTML = "<h4 style='background:#FFCC66; size:12px; border:1px; font:Verdana, Arial, Helvetica, sans-serif; width:250px; border-color:#999999; border-width:1px'>Carregando...</h4>";
							if (ajax.readyState == 4){
								if(ajax.status == 200){
									var resultado = ajax.responseText;
									resultado = resultado.replace(/\+/g," ");
									resultado = unescape(resultado);
									exibeResultado.innerHTML = resultado;
								}else{
									exibeResultado.innerHTML = "Erro: "+ajax.status;
									}
													}
													}
					ajax.send(null);
}


//exibe resultado do ajax
function fcExibe(id,exibe){
	var exibeResultado = document.getElementById(id);
					exibeResultado.innerHTML = exibe;
}

// JavaScript Document
 function EnviaPedido(){
		var F = document.FormPedido; 
		var id	=	'xFP';
		var exibe = '';
		if(F.nome.value.length < 5){
			exibe = 'Preencha corretamente o Campo Nome';
			fcExibe(id,exibe)
			F.nome.value = '';
			F.nome.focus();
			fcExibe(id,exibe)
			return false;

		}
		
		var EMAIL = F.email.value;
		if (EMAIL.indexOf('@') == -1 || EMAIL.indexOf('.') == -1)
		 {
		   exibe = "Este EMAIL é inválido.";
		   fcExibe(id,exibe)
		    EMAIL = '';
			F.email.focus();
			return false;
		 }

		
//campo cnpf / cpf
	marcado = -1
	for (i=0; i<F.rdC.length; i++)
	{
		if (F.rdC[i].checked)
	   	{
		marcado = i
		var Valor = F.rdC[i].value
		}
	}
	
	if (marcado == -1)
	{
			exibe = 'Selecione CPF ou CNPJ';
			fcExibe(id,exibe)
			F.rdC[0].focus();
			return false;
	}

	var cpf = F.cpf.value;
	
	if(Valor == 1){
		cpf = cpf;
		var erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";	
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			  erro += "Numero de CPF invalido!"
		}
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i <  9) b += (a[i] *  --c);
		}
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] *  c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		status = a[9] + ""+ a[10]
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			erro +="Digito verificador do CPF com problema!";
		}
		if (erro.length > 0){
			fcExibe(id,erro)
			cpf = '';
			F.cpf.focus();
			return false;
		}
	
		}else{
			
		CNPJ = cpf;
		erro = new String;
		if (CNPJ.length < 14) erro += "É necessários 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' necessarios 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 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 +="Digito verificador do CNPJ com problema!";
		}
		if (erro.length > 0){

			fcExibe(id,erro)
			cpf = '';
			F.cpf.focus();
			return false;
		}			
}
//término cnpf / cpf



		 var Fone = F.telefone.value;
		 if(Fone.length != 12){
			exibe = 'Preencha corretamente o Campo Telefone';
			fcExibe(id,exibe)
			Fone = '';
			F.telefone.focus();
			return false;
		}
		var rua = F.rua.value;
		if(rua.length < 3){
			exibe = 'Preencha corretamente o Campo Rua';
			fcExibe(id,exibe)
			rua = '';
			F.rua.focus();
			return false;
		}
		var n = F.numero.value;
		if(n.length == ''){
			exibe = 'Preencha corretamente o Campo Número';
			fcExibe(id,exibe)
			n = '';
			F.numero.focus();
			return false;
		}
		var b = F.bairro.value;
		if(b.length < 3){
			exibe = 'Preencha corretamente o Campo Bairro';
			fcExibe(id,exibe)
			b = '';
			F.bairro.focus();
			return false;
		}
		var c = F.cidade.value;
		if(c.length < 3){
			exibe = 'Preencha corretamente o Campo Cidade';
			fcExibe(id,exibe)
			c = '';
			F.cidade.focus();
			return false;
		}
		var uf = F.uf.value;
		if(uf.length ==''){
			exibe = 'Escolha um Estado';
			fcExibe(id,exibe)
			uf = '';
			F.uf.focus();
			return false;
		}
		var cep = F.cep.value;
		if(cep.length != 9){
			exibe = 'Preencha corretamente o Campo Cep';
			fcExibe(id,exibe)
			cep = '';
			F.cep.focus();
			return false;
		}


        mar = -1
        for (i=0; i<F.TipoPagamento.length; i++)
	{
		if (F.TipoPagamento[i].checked)
	   	{
		mar = i
		var Valor = F.TipoPagamento[i].value
		}
	}
	
	if (mar == -1)
	{
		exibe = "Selecione uma forma de Pagamento.";
		fcExibe(id,exibe)
		F.TipoPagamento[0].focus();
		return false;
	}
		


		var obs = F.obs.value;
		if(obs.length > 255){
			exibe = 'Permitido apenas 255 caracteres\nVocê digitou : '+obs.length+' caracteres';
			fcExibe(id,exibe)
			F.obs.focus();
			return false;
		}

		fcExibe(id,'Formulário ok!!!')
//	return true;

/*	document.forms[0].action = 'FeedBack.asp';
alert(document.forms[0].action);
document.forms[0].submit();
*/
 }




//função para o cep
 function MM_formtCep(e,src,mask) {
if(window.event) { _TXT = e.keyCode; } 
else if(e.which) { _TXT = e.which; }
if(_TXT > 47 && _TXT < 58) { 
 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); } 
    return true; } else { if (_TXT != 8) { return false; } 
 else { return true; }
}
}

//////////////////////
 function MM_formtTel(e,src,mask) {
if(window.event) { _TXT = e.keyCode; } 
else if(e.which) { _TXT = e.which; }
if(_TXT > 47 && _TXT < 58) { 
 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); } 
    return true; } else { if (_TXT != 9) { return false; } 
 else { return true; }
}
}


///funcao inclui pedido
function funcaoIncluiPedido(cod,valor)
{
	var end 		= 'sql/CarrinhoProduto.asp?vOpcao=Incluir&vCodProduto='+cod+'&vValorProduto='+valor;
	location.href=end;
}

///funcao Exclui pedido
function funcaoExluiPedido(vCod)
{
	var end 		= 'CarrinhoCompra.asp?vOpcao=Excluir&vCodProduto='+vCod;
	document.location.href=end;
}

///funcao voltar as compras
function funcaoVoltarProduto()
{
	location.href='Default.asp';
}

//função fecha pedido
function funcaoFechaPedido()
{
	location.href='../index.asp?Opcao=5';
}

//funcção atualiza pedido
function funcaoExluiPedido(vCodPedido)
{
	var end 		= 'CarrinhoDetalhes.asp?vOpcao=Cancela&vCodCesta='+vCodPedido;
	location.href=end;
}

//funcção remover item pedido
function funcaoRemovePedido(vCodCesta)
{
	var end 		= 'CarrinhoDetalhes.asp?vOpcao=Remove&vCodCesta='+vCodCesta;
	location.href=end;
}


//funcção detalhe do produto
function funcaoDetalheProduto(cod)
{
	var end 		= 'ProdutoDetalhe.asp?vCodProduto='+cod;
	location.href=end;
}


//funcçao calcular frete
function funcaoCalFrete(a)
{
	if (document.FormPedido.cepDestino.value.length != 8){
	alert('Cep Inválido');
	document.FormPedido.cepDestino.focus();
	} else {
	vCep	=	document.FormPedido.cepDestino.value;
	UrlResposta = a;
	url	=	'http://www.correios.com.br/encomendas/precos/calculo.cfm?cepOrigem=13201180&cepDestino='+vCep+'&peso=1&resposta='+UrlResposta;
    document.forms[0].action = url
	document.forms[0].submit();}
	//return true;
}

//função Menu
function funcaoVerCarrinho(cesta){
		location.href='CarrinhoDetalhes.asp?vOPcao=verCarrinho';
}

//
function funcaoDownload(arq){
	document.location.href='funcao/download.asp?Arqu='+arq;
}

//------------------------
function fc_janela(chave, largura, altura) {
//------------------------
//  fcBtnCom(chave,'msg1');
  posleft = (((screen.width - largura)/2)-10);
  postop  = (screen.height - altura)/2;
  parametros = 'toolbar=no, location=no, directories=no, status=no, ';
  parametros += 'scrollbars=yes, resizable=yes, menubar=no, ';
  parametros += 'width='+largura+', height='+altura+', left='+posleft+', top='+postop;
  void(window.open('http://www.drogas.org.br/_DIVULGACAO/FRM_20070601.asp', 'FRM', parametros));
}

//postback na página CarrinhoDetalhes.asp ao escolher um novo número de produtos

function MM_jumpMenu(){ 
	document.forms[0].submit();
}

//FUNÇÃO LETRA MAIÚSCULA

function Converte(CAMPO) {
        CAMPO.value = CAMPO.value.toUpperCase();}

						

//------------------------
function _fcGeraBoleto(chave, largura, altura, valor, vCodPed) {
//------------------------
  posleft = (((screen.width - largura)/2)-10);
  postop  = (screen.height - altura)/2;
  parametros = 'toolbar=no, location=no, directories=no, status=no, ';
  parametros += 'scrollbars=no, resizable=no, menubar=no, ';
  parametros += 'width='+largura+', height='+altura+', left='+posleft+', top='+postop;
  void(window.open('objBoleto/2009/vBoleto.asp?vCodCli='+chave+'&vValorCli='+valor+'&vCodPed='+vCodPed, 'BOLETO', parametros));
}

//=======================================================
//função muda de campo
	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;
}
//===================================================================
//conteúdo novo
function EnableKey(intKeyCodeValue,strRange,strOthers)
{
   /*
   Esta função impede que o usuário digite um valor que não é esperado para o campo.
   
   intKeyCodeValue = event *** o primeiro parâmetro desta função deve ser a palavra chave event,
                               para que possamos identificar qual tecla foi pressionada.
                               
   strRange  *** strRange são os valores das chaves que estão habilitadas. Esta variável deve conter dois números
                 inteiros representando o código ASCII da tecla, separados pelo sinal de ':'(dois pontos).
                 Serão habilitadas todas as teclas que forem maiores ou iguais ao primeiro valor(valor antes dos
                 dois pontos) e menores ou iguais ao segundo valor (valor após os dois pontos).
                 Caso o segundo valor seja maior que o primeiro, os valores serão trocados.
   
   strOthers *** strOthers é dividido por ponto-e-vírgulas(;). Os valores ASCII contidos em strOthers são excessões e quando
                 pressionados serão exibidos mesmo que não esteja no escopo do parâmetro strRange.
                 OBS***PASSE PARA strOthers OS CARACTERS ASCII!!!
   */
   
   strRange = strRange.split(":");
   var intFirst = strRange[0];
   var intEnd   = strRange[1];
   var intAux;
   
   if(strOthers.length>0)
   {
      strOthers = strOthers.split(";")
   }
   if(!(isNaN(intFirst) && isNaN(intEnd)))
   {
      if(intEnd < intFirst)
      {
         intAux   = intFirst;
         intFirst = intEnd;
         intEnd   = intAux;
      }
      if((intKeyCodeValue.keyCode < intFirst) || (intKeyCodeValue.keyCode > intEnd))
      {
         if(strOthers.length < 1)
         {
            intKeyCodeValue.keyCode = false;
         }
         
         intAux=0;
         for(var i=0; i<strOthers.length; i++)
         {
            if(!(isNaN(strOthers[i])))
            {
               if(intKeyCodeValue.keyCode == strOthers[i])
               {
                  intAux += 1;
               }
            }
         }
         if(intAux==0)
         {
            intKeyCodeValue.keyCode = false;
         }
      }
   }
}
