/////////////// CHECA CADASTRO ///////////////
function checaCadastro() {
	//PEGA TODOS OS CAMPOS TEXTO
	var arrObj = document.cadastro.getElementsByTagName("input");

	for(var i=0; i<arrObj.length; i++ ) {
		// PESSOA FÍSICA
		if(document.getElementById('cli_tipo').checked==true) {
			if ((arrObj[i].type == "text" && arrObj[i].id!="cli_responsavel" && arrObj[i].id!="cli_ie" && arrObj[i].id!="cli_compl") || arrObj[i].type == "password") {
				if (arrObj[i].value == "" && arrObj[i].id!="cli_nova_senha" && arrObj[i].id!="confirma_senha") {
					alert('Preencha todos os campos corretamente!');
					arrObj[i].focus();
					return false;
				}
			}
			if (valida_CPF(document.getElementById('cli_cpf').value)==false) {
				alert('CPF incorreto!');
				document.getElementById('cli_tipo').focus();
				return false;
			}
		// PESSOA JURÍDICA
		} else {
			if ((arrObj[i].type == "text" && arrObj[i].id!="cli_nasc" && arrObj[i].id!="cli_compl") || arrObj[i].type == "password") {
				if (arrObj[i].value == "" && arrObj[i].id!="cli_nova_senha" && arrObj[i].id!="confirma_senha") {
					alert('Preencha todos os campos corretamente!');
					arrObj[i].focus();
					return false;
				}
			}
			if (valida_CNPJ(document.getElementById('cli_cpf').value)==false) {
				alert('CNPJ incorreto!');
				document.getElementById('cli_cpf').focus();
				return false;
			}
		}
	}
	
	// EMAIL
	endereco=document.getElementById('cli_email').value;
	if (endereco == "") {
		alert('Por favor, digite seu email corretamente!');
		document.getElementById('cli_email').focus();
	    return false;
	}
	invalidChars=" /:,;()='´`^~áéàèíìóòãñüöïç+&#$"
	for (i=0; i<invalidChars.length; i++) {
		badChar=invalidChars.charAt(i)
	    if (endereco.indexOf(badChar,0)>-1) {
			alert('Por favor, digite seu email corretamente');
			document.getElementById('cli_email').focus();
			return false;
		}
	}
	atPos=endereco.indexOf("@",1)
	if (atPos == -1) {
		alert('Por favor, digite seu email corretamente');
		document.getElementById('cli_email').focus();
		return false;
	}
	if (endereco.indexOf("@",atPos+1)>-1) {
		alert('Por favor, digite seu email corretamente');
		document.getElementById('cli_email').focus();
		return false;
	}
	if (endereco.indexOf(".",atPos) == -1) {
		alert('Por favor, digite seu email corretamente');
		document.getElementById('cli_email').focus();
		return false;
	}
	
	if (document.getElementById('cli_senha')) {
		if (document.getElementById('cli_senha').value!=document.getElementById('confirma_senha').value) {
			document.getElementById('confirma_senha').style.borderColor = '#FF0000';
			alert('Por favor, confime sua senha corretamente!');
			document.getElementById('confirma_senha').focus();
			return false;
		}
	} else {
		if (document.getElementById('cli_nova_senha').value!=document.getElementById('confirma_senha').value) {
			document.getElementById('confirma_senha').style.borderColor = '#FF0000';
			alert('Por favor, confime sua senha corretamente!');
			document.getElementById('confirma_senha').focus();
			return false;
		}
	}
	
	return true;
}

//DATA NASCIMENTO
function mascaraData(campoData){
	var data = campoData.value;
	if (data.length == 2){
		data = data + '/';
		campoData.value = data;
		return true;
	}
	if (data.length == 5){
		data = data + '/';
		campoData.value = data;
		return true;
	}
}

//TELEFONE
function mascaraTel(campoTel){
	var tel = campoTel.value;
	if (tel.length == 1){
		tel = '(' + tel;
		campoTel.value = tel;
		return true;
	}
	if (tel.length == 3){
		tel = tel + ') ';
		campoTel.value = tel;
		return true;
	}
	if (tel.length == 9){
		tel = tel + '-';
		campoTel.value = tel;
		return true;
	}
}

//SOMENTE NÚMEROS
function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if ((tecla>47 && tecla<58)) {
		return true;
	} else {
    	if (tecla==8 || tecla==0) {
			return true;
		} else {
			return false;
		}
    }
}


//VALIDA CPF
function valida_CPF(s)	{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}

//LIMPA OS CAMPOS PARA VALIDAÇÃO
function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}

//VALIDA CNPJ
function valida_CNPJ(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
	return true;
}

/////////////// CHECA SENHA ///////////////
function checaSenha() {
	if (document.getElementById('cli_senha')) {
		if (document.getElementById('cli_senha').value!=document.getElementById('confirma_senha').value) {
			document.getElementById('confirma_senha').style.borderColor = '#FF0000';
		} else {
			document.getElementById('confirma_senha').style.borderColor = '#2d86d2';
		}
	} else {
		if (document.getElementById('cli_nova_senha').value!=document.getElementById('confirma_senha').value) {
			document.getElementById('confirma_senha').style.borderColor = '#FF0000';
		} else {
			document.getElementById('confirma_senha').style.borderColor = '#2d86d2';
		}
	}
}

/////////////// CHECA ENDEREÇO ///////////////
function validaEndereco() {
	//LOGRADOURO
	if (document.getElementById('end_rua').value.length<3) {
		alert('Preencha o campo LOGRADOURO corretamente');
		document.getElementById('end_rua').focus();
		return false;
	}
	//NÚMERO
	if (document.getElementById('end_num').value.length<1) {
		alert('Preencha o campo NÚMERO corretamente');
		document.getElementById('end_num').focus();
		return false;
	}
	//BAIRRO
	if (document.getElementById('end_bairro').value.length<3) {
		alert('Preencha o campo BAIRRO corretamente');
		document.getElementById('end_bairro').focus();
		return false;
	}
	//CIDADE
	if (document.getElementById('end_cidade').value.length<2) {
		alert('Preencha o campo CIDADE corretamente');
		document.getElementById('end_cidade').focus();
		return false;
	}
	//ESTADO
	if (document.getElementById('end_estado').value.length<2) {
		alert('Preencha o campo ESTADO corretamente');
		document.getElementById('end_estado').focus();
		return false;
	}
	//CEP
	if (document.getElementById('end_cep').value.length<8) {
		alert('Preencha o campo CEP corretamente');
		document.getElementById('end_cep').focus();
		return false;
	}
	
	return true;
}

/////////////// SETA ENDEREÇO DE ENTREGA ///////////////
function setEndEntrega(id) {
	document.getElementById('ped_endentrega').value = id;
}

/////////////// TROCA SUBMIT ///////////////
function setSubmit(pagina, acao) {
	document.getElementById('cadastro').action = pagina+".php?a="+acao;
}

/////////////// BOX CONFIRMAÇÃO ///////////////
function confirma(pagina,mensagem) {
	if(confirm(mensagem)==true) {
		window.location = pagina;
	}
}

/////////////// CONFIRMA BOLETO ///////////////
function confirmaBoleto(mensagem) {
	if(confirm(mensagem)==true) {
		return true;
	}
	return false;
}

/////////////// BOX CONFIRMAÇÃO COMPRA ///////////////
function confirmaCompra(pagina,mensagem) {
	if(confirm(mensagem)==true) {
		document.getElementById('confirmaCompra').action = pagina;
	} else {
		return false;
	}
}

/////////////// PARCELAS ///////////////
function parcelar() {
	if (document.getElementById('TRANSACAO').value=='08') {
		document.getElementById('tr_parcelas').style.display = '';
		document.getElementById('PARCELAS').selectedIndex = 1;
	} else {
		document.getElementById('tr_parcelas').style.display = 'none';
		document.getElementById('TRANSACAO').selectedIndex = 0;
		document.getElementById('PARCELAS').selectedIndex = 0;
	}
}

function parcelar2() {
	if (document.getElementById('PARCELAS').value=='00') {
		document.getElementById('tr_parcelas').style.display = 'none';
		document.getElementById('TRANSACAO').selectedIndex = 0;
		document.getElementById('PARCELAS').selectedIndex = 0;
	}
}

/////////////// TIPO DE FRETE ///////////////
function frete(valor, valortotal, tipo) {

	//DEFINE O TIPO DE FRETE
	document.getElementById('tipodefrete').value = tipo;
	//DEFINE O VALOR DO FRETE
	document.getElementById('frete').value = valor;
	//SOMA OS VALORES PARA MÓDULO DA REDECARD
	var valorTotalComFrete = parseFloat(valortotal) + parseFloat(valor);
	document.getElementById('valor_total').value = valorTotalComFrete.toFixed(2);
	
	//EXIBE O BOTÃO REALIZAR COMPRA
	document.getElementById('BTcomprar').style.display = '';
}

/////////////// CHECA TIPO PESSOA ///////////////
function tipo_(t) {
	if (t==0) {
		document.getElementById('resp').style.display='none';
		document.getElementById('ie').style.display='none';
		document.getElementById('sexo').style.display='';
		document.getElementById('nasc').style.display='';
		document.getElementById('nomerazao').innerHTML='Nome:';
		document.getElementById('cpfcnpj').innerHTML='CPF:';
	} else {
		document.getElementById('resp').style.display='';
		document.getElementById('ie').style.display='';
		document.getElementById('sexo').style.display='none';
		document.getElementById('nasc').style.display='none';
		document.getElementById('nomerazao').innerHTML='Raz&atilde;o:';
		document.getElementById('cpfcnpj').innerHTML='CNPJ:';
	}
}

/////////////// VALIDA CONTATO ///////////////
function validarContato(contato) {
	// Verificação do nome
	if (contato.nome.value.length < 2) {
		alert("Digite o campo nome corretamente, no mínimo 2 caracteres!");
		document.contato.nome.style.color = "red";
		contato.nome.focus();
		return false; }
	// Verificação do email
	if (contato.email.value.length < 5) {
		alert("Digite o campo email corretamente, no mínimo 5 caracteres!");
		document.contato.email.style.color = "red";
		contato.email.focus();
		return false; }
	// verificação da mensagem
	if (contato.mensagem.value.length < 2) {
		alert("Digite o campo mensagem corretamente, no mínimo 2 caracteres!");
		document.contato.mensagem.style.color = "red";
		contato.mensagem.focus();
		return false; }
    return true;
}

/////////////// CHECA LOGIN ///////////////
function inputLogin(campo) {
	var valor = document.getElementById(campo).value;
	if (valor=='') {
		document.getElementById(campo).value = document.getElementById(campo).defaultValue;
		document.getElementById(campo).style.color = '#999';
	} else {
		if (valor==document.getElementById(campo).defaultValue) {
			document.getElementById(campo).value = '';
			document.getElementById(campo).style.color = '#000';
		}
	}
}

/////////////// RASTREAMENTO CORREIOS ///////////////
function BT_PAGE_OnClick(ctl) {
   document.getElementById('Z_ACTION').value = ctl.value;
   document.getElementById('rastreamentoCorreios').submit();
   return true;
}
function BT_PAGE_OnClick2(ctl2) {
   document.getElementById('Z_ACTION2').value = ctl2.value;
   document.getElementById('rastreamentoCorreios2').submit();
   return true;
}

/////////////// NOVA JANELA ///////////////
function NewWindow(pagina, w, h) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',resizable';
window.open(pagina, 'teste', winprops);
}

/////////////// LISTA DE PRESENTES ///////////////
function VerificaData(dt_evento) 
{
    var bissexto = 0;
    var data = dt_evento; 
    var tam = data.length;
    if (tam == 10) 
    {
        var dia = data.substr(0,2);
        var mes = data.substr(3,2);
        var ano = data.substr(6,4);
        if ((ano > 1900)||(ano < 2100))
        {
            switch (mes) 
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if  (dia <= 31) 
                    {
                        return true;
                    }
                    break
                
                case '04':        
                case '06':
                case '09':
                case '11':
                    if  (dia <= 30) 
                    {
                        return true;
                    }
                    break
                case '02':
                    /* Validando ano Bissexto / fevereiro / dia */ 
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) 
                    { 
                        bissexto = 1; 
                    } 
                    if ((bissexto == 1) && (dia <= 29)) 
                    { 
                        return true;                 
                    } 
                    if ((bissexto != 1) && (dia <= 28)) 
                    { 
                        return true; 
                    }            
                    break                        
            }
        }
    }    
    alert("Sua data de evento "+data+" é inválida!");
	document.procura.dt_evento.style.color = "red";
	procura.dt_evento.focus();
    return false;
}

function txtBoxFormat(objeto, 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 = objeto.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( ")", "" );
    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++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
  }

function validarBuscaLista(procura) {
		// Verificação da email
	if (procura.nome.value.length < 3 && procura.dt_evento.value.length < 10) {
		alert("Informe o nome do aniversariante ou a data do evento!");
		document.procura.nome.style.color = "red";
		procura.nome.focus();
		return false; }
}		

function validarBusca() {
	//CONVERTE PARA UTF-8
	UTF8 = {
		encode: function(s){
			for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
				s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
			);
			return s.join("");
		},
		decode: function(s){
			for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
				((a = s[i][c](0)) & 0x80) &&
				(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
				o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
			);
			return s.join("");
		}
	};

	var p_busca = document.getElementById('palavra').value;
	//FORMATA A STRING CORRETAMENTE
	var p = UTF8.encode(p_busca.toLowerCase());
	
	p = p.replace(/á/gi,"a");
	p = p.replace(/à/gi,"a");
	p = p.replace(/â/gi,"a");
	p = p.replace(/ã/gi,"a");
	p = p.replace(/ä/gi,"a");
	
	p = p.replace(/é/gi,"e");
	p = p.replace(/è/gi,"e");
	p = p.replace(/ê/gi,"e");
	p = p.replace(/ë/gi,"e");
	
	p = p.replace(/í/gi,"i");
	p = p.replace(/ì/gi,"i");
	p = p.replace(/î/gi,"i");
	p = p.replace(/ï/gi,"i");
	
	p = p.replace(/ó/gi,"o");
	p = p.replace(/ò/gi,"o");
	p = p.replace(/ô/gi,"o");
	p = p.replace(/õ/gi,"o");
	p = p.replace(/ö/gi,"o");
	
	p = p.replace(/ú/gi,"u");
	p = p.replace(/ù/gi,"u");
	p = p.replace(/û/gi,"u");
	p = p.replace(/ü/gi,"u");
	
	p = p.replace(/ç/gi,"c");
	
	document.getElementById('palavra').value = p;
	
}

/////////////// LOAD IMAGENS ///////////////
<!--
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_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
