function $get(idElemento){
	return document.getElementById(idElemento);
}

function vai (url){
  location.replace(url);
}

// Codificar Strings

function url_encode(str) {  
        var hex_chars = "0123456789ABCDEF";  
        var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
        var n, strCode, hex1, hex2, strEncode = "";  

        for(n = 0; n < str.length; n++) {  
            if (noEncode.test(str.charAt(n))) {  
                strEncode += str.charAt(n);  
            } else {  
                strCode = str.charCodeAt(n);  
                hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
                hex2 = hex_chars.charAt(strCode % 16);  
                strEncode += "%" + (hex1 + hex2);  
            }  
        }  
	return strEncode;  
}  

// Descodificar String 

function url_decode(str) {  
	var n, strCode, strDecode = "";  

	for (n = 0; n < str.length; n++) {  
		if (str.charAt(n) == "%") {  
			strCode = str.charAt(n + 1) + str.charAt(n + 2);  
			strDecode += String.fromCharCode(parseInt(strCode, 16));  
			n += 2;  
		} else {  
			strDecode += str.charAt(n);  
		}  
	}  

	return strDecode;  
} 

function number_format (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}


function processReqChange2() {
	if (xmlhttpCep.readyState == 4){
		if (xmlhttpCep.status == 200){
			var retXml = xmlhttpCep.responseXML.getElementsByTagName('conteudo');
			if (retXml.length){
				for ( x = 0; x < retXml.length; x++){
					msg = (retXml[0].getElementsByTagName('erro')[x].firstChild.nodeval() == 1 ? "Erro!<br>" : "");
					msg += (retXml[0].getElementsByTagName('cepDest')[x].firstChild.nodeval() == 1 ? "Erro!<br>" : "");
					document.getElementById("retorno").innerHTML = msg+"Teste";
				}
			}
		} else {
			alert("Problemas ao carregar o arquivo.");
		}
	}
}

//###################################################################################
function atualiza_carrinho(tip) {
	switch (tip) {
		case "produtos":
			var fr = document.frmEditContact;
			document.getElementById("att_registro").val() = 1;
			fr.submit();
		break;
		case "frete":
			executar_pesquisar_cep();
		break;
	}
}

function send_frete(string) {
	var frm		= document.frmEditContact;
	var vfrete 	= string.split('#');
	
	SndFrtALERTopcaofreteTMP = SndFrtALERTopcaofrete.replace("varOpcaoFrete", ""+vfrete[0])+"";
	SndFrtALERTopcaofreteTMP = SndFrtALERTopcaofreteTMP.replace("varValorFrete", ""+vfrete[1])+"";
	
	var conf_frete = confirm(SndFrtALERTopcaofreteTMP)
	if (conf_frete==true) {
		frm.opcao_frete.val() = vfrete[0];
		frm.frete.val() = vfrete[2];
		frm.cep_frete.val() = vfrete[3];
		frm.codigo_op.val() = vfrete[4];     
    	frm.action = "carrinho.php";
		frm.submit();
	}
}

/**
	Envia informação caso seja transportador a opção desejada
*/
function send_freteTransp(string) {
	var frm		= document.frmEditContact;
	var vfrete = string.split('#');
	var valorFrete = vfrete[1];
	
	if (parseFloat(valorFrete) > 0){ // Verifica se o valor do frete é maior que zero.
		 SndFrtALERTopcaofreteTMP = SndFrtALERTopcaofrete.replace("varOpcaoFrete", ""+vfrete[0])+"";
		 SndFrtALERTopcaofreteTMP = SndFrtALERTopcaofreteTMP.replace("varValorFrete", ""+vfrete[1])+"";
		 
		 var conf_frete = confirm(SndFrtALERTopcaofreteTMP)
		 if (conf_frete==true) {
		   frm.opcao_frete.val() = "TRANSPORTADORA A COBRAR";
		   frm.frete.val() = vfrete[2];
		   frm.cep_frete.val() = vfrete[3];  
		   frm.codigo_op.val() = vfrete[4]; 
		   frm.action = "carrinho.php";
		   frm.submit();
		 }
	}
		
}

/*
	Verefica se o usuario selecionou alguma forma de pagamento 
*/
function check_opcaopag() {
	var chs = $(".tp_frete").get();
	var check = false;
	for (i=0; i < chs.length; i++){
		if (chs[i].checked == true){
			check = true;
			break;
		}
	}
	
	if (check == false) {
		alert(CkOpPagALERTselpag);
	} else {
		document.frmFormaPgto.action = "autentica.php";
		document.frmFormaPgto.submit();
	}
}

function checkFalseRadio(campo) {
	var chs = $("."+campo).get();
	var check = false;
	for (i=0; i < chs.length; i++){
		chs[i].checked = false;
	}
}

function checkOpcaoFrete() {
	var fr = document.frmFrete2;
	var check = false;
	for(a=0;a<fr.elements.length;a++){
		if(fr.elements[a].name == 'tp_frete'){
			if (fr.elements[a].checked == true) {
				return 1;
				break;
			}
		}
	}
	return 0;
}


//###################################################################################
function check_login() {
   var fr = document.autentica;

   if (fr.email.val().length == 0) {
      alert(CkLoginALERTcmpemail);
      fr.email.focus();
      return false;
   }

   if (fr.email.val().indexOf('@', 0) == -1 || fr.user_id.val().indexOf('.', 0) == -1) {
      alert(CkLoginALERTcmpemailinc); 
      fr.email.focus();
      return false;
   }

   if (fr.esquecisenha.checked == false) {
      if (fr.senha.val().length == 0) {
         alert(CkLoginALERTcmpsenha);
         fr.senha.focus();
         return false;
      }
   }
   return true;
}

function checkEmail(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(mail) == "string"){
		if(er.test(mail)){ return true; }
	}else if(typeof(mail) == "object"){
		if(er.test(mail.val())){ 
			return true; 
		}
   }else{
        return false;
   }
}


//###################################################################################
function check_newlogin() {
   var fr = document.novo_usuario;

   if (fr.email.val().length == 0) {
      alert(CkNwLoginALERTcmpemail);
      fr.email.focus();
      return false;
   }

   if (fr.email.val().indexOf('@', 0) == -1 || fr.email.val().indexOf('.', 0) == -1) {
      alert(CkNwLoginALERTcmpemailinc); 
      fr.email.focus();
      return false;
   }
   return true;
}

//###################################################################################
function reenvio_pwd() {
	if ($("#esquecisenha")[0].checked == true) {
      $("#senha").get(0).disabled = true;
      $("#senha").val('');
      $("#autUser").val(RnvPwdALERTreenvsenha);
   } else {
      $("#senha").get(0).disabled = false;
      $("#autUser").val(RnvPwdALERTautentusuario);
   }
}


//###################################################################################
function valida_cadastro(formname,tipoverif) {
	var Form;
	Form = formname;
	
	if ((valida_endereco(Form,'CadUser') == false) || (valida_password(Form) == false)) {
		return false;
	}
	if ((valida_endereco(Form,'Logado') == false)) {
		return false;
	}	
	if ((valida_endereco(Form,'minhaConta') == false)) {
		return false;
	}	
}

//###################################################################################
function valida_password(Form) {
	if (Form.tipo_login.val() == "user_new") {
		if (Form.senha.val().length == 0 || Form.conf_senha.val().length == 0) {
			alert(VldPwdALERTcamposenha);
			Form.senha.focus();
			return false;
		}
		if (Form.senha.val() != Form.conf_senha.val()) {
			alert(VldPwdALERTsenhadif);
			Form.senha.focus();
			return false;
		}
	}

}

//###################################################################################
function valFrmEcommerce() {
	var cob_dif	= $("#cobranca_diferente").get();
	
	if ($("#nome").val().length == 0) {
		alert(VldEndALERTcmpnome);
        $("#nome").focus();
        return false;
	}
       
	var cpf_cob = $("#cpf_b1").val() + $("#cpf_b2").val() + $("#cpf_b3").val() + $("#cpf_b4").val();

	if (cpf_cob.length == 0) {
		alert(VldEndALERTcmpcpf);
		$("#cpf_b1").focus();
		return false;
	}

	s = limpa_string(cpf_cob);
	if (s.length == 11) {
		if (valida_CPF(cpf_cob) == false ) {
			alert(VldEndALERTcmpcpfinc);
			$("#cpf_b1").focus();
			return false;
		}
	}else{
		alert(VldEndALERTcmpcpfinc);
		$("#cpf_b1").focus();
		return false;
	}

	$("#cpf").val(cpf_cob);
/*
	if ($("#rg").val().length == 0) {
		alert(VldEndALERTcmprg);
		$("#rg").focus();
		return false;
	}
*/
    if ($("#ddd").val().length == 0) {
		alert(VldEndALERTcmpddd);
		$("#ddd").focus();
		return false;
	}

	if ($("#telefone").val().length == 0) {
		alert(VldEndALERTcmptel);
		$("#telefone").focus();
		return false;
	}

	if ($("#endereco").val().length == 0) {
		alert(VldEndALERTcmpend);
		$("#endereco").focus();
		return false;
	}
     
	if ($("#numero").val().length == 0) {
		alert(VldEndALERTcmpnum);
		$("#numero").focus();
		return false;
	}

	if ($("#bairro").val().length == 0) {
		alert(VldEndALERTcmpbairro);
		$("#bairro").focus();
		return false;
	}

	if ($("#cidade").val().length == 0) {
		alert(VldEndALERTcmpcidade);
		$("#cidade").focus();
		return false;
	}

    $("#data_nasc").val($("#data_nasc_b3").val() + "-" + $("#data_nasc_b1").val() + "-" + $("#data_nasc_b2").val());

	/*
		Caso o usuario selecione a opcao entregar em outro lugar
	*/
/*	if (cob_dif[0].checked == true){
		if ($("#nome").val().length == 0) {
			alert(VldEndALERTcmpnome);
			$("#nome").focus();
			return false;
		}
       
		if ($("#endereco").val().length == 0) {
			alert(VldEndALERTcmpend);
			$("#endereco").focus();
			return false;
		}
		 
		if ($("#numero").val().length == 0) {
			alert(VldEndALERTcmpnum);
			$("#numero").focus();
			return false;
		}
	
		if ($("#bairro").val().length == 0) {
			alert(VldEndALERTcmpbairro);
			$("#bairro").focus();
			return false;
		}
	
		if ($("#cidade").val().length == 0) {
			alert(VldEndALERTcmpcidade);
			$("#cidade").focus();
			return false;
		}
	} // End do if que verifica a entrega em outro estabelecimento.
		*/
	// Caso as informações estiverem corretas a função ira retorna true 
	return true;

}

function valFrmEcommerce2 () {
	if ($("#nome").val().length == 0) {
		alert(VldEndALERTcmpnome);
        $("#nome").focus();
        return false;
	}
       
	var cpf_cob = $("#cpf_b1").val() + $("#cpf_b2").val() + $("#cpf_b3").val() + $("#cpf_b4").val();

	if (cpf_cob.length == 0) {
		alert(VldEndALERTcmpcpf);
		$("#cpf_b1").focus();
		return false;
	}

	s = limpa_string(cpf_cob);
	if (s.length == 11) {
		if (valida_CPF(cpf_cob) == false ) {
			alert(VldEndALERTcmpcpfinc);
			$("#cpf_b1").focus();
			return false;
		}
	}else{
		alert(VldEndALERTcmpcpfinc);
		$("#cpf_b1").focus();
		return false;
	}

	$("#cpf").val(cpf_cob);

	if ($("#rg").val().length == 0) {
		alert(VldEndALERTcmprg);
		$("#rg").focus();
		return false;
	}

    if ($("#ddd").val().length == 0) {
		alert(VldEndALERTcmpddd);
		$("#ddd").focus();
		return false;
	}

	if ($("#telefone").val().length == 0) {
		alert(VldEndALERTcmptel);
		$("#telefone").focus();
		return false;
	}

	if ($("#email").val().length == 0) {
	  alert(CkLoginALERTcmpemail);
	  $("#email").focus();
	  return false;
	}
	
	if (!checkEmail($("#email").val())) {
	  alert(CkLoginALERTcmpemailinc); 
	  $("#email").focus();
	  return false;
	}

	if ($("#senha").val().length == 0) {	
		alert(VldPwdALERTcamposenha);
		$("#senha").focus();
		return false;
	}
	if ($("#senha").val().length > 0) {	
		if ($("#senha").val().length != $("#conf_senha").val().length) {	
			alert(VldPwdALERTsenhadif);
			$("#senha").focus();
			return false;
		}
	}
	if ($("#endereco").val().length == 0) {
		alert(VldEndALERTcmpend);
		$("#endereco").focus();
		return false;
	}
     
	if ($("#numero").val().length == 0) {
		alert(VldEndALERTcmpnum);
		$("#numero").focus();
		return false;
	}

	if ($("#bairro").val().length == 0) {
		alert(VldEndALERTcmpbairro);
		$("#bairro").focus();
		return false;
	}

	if ($("#cidade").val().length == 0) {
		alert(VldEndALERTcmpcidade);
		$("#cidade").focus();
		return false;
	}

	$("#data_nasc").val($("#data_nasc_b3").val() + "-" + $("#data_nasc_b1").val() + "-" + $("#data_nasc_b2").val());
	return true;
}


function valFrmCadMinhaConta() {
	if ($("#nome").val().length == 0) {
		alert(VldEndALERTcmpnome);
		$("#nome").focus();
		return false;
	}

	if ($("#email").val().length == 0) {
	  alert(CkLoginALERTcmpemail);
	  $("#email").focus();
	  return false;
	}
	
	if (!checkEmail($("#email").val())) {
	  alert(CkLoginALERTcmpemailinc); 
	  $("#email").focus();
	  return false;
	}

	if ($("#rg").val().length == 0) {
		alert(VldEndALERTcmprg);
		$("#rg").focus();
		return false;
	}

	if ($("#endereco").val().length == 0) {
		alert(VldEndALERTcmpend);
		$("#endereco").focus();
		return false;
	}
	 
	if ($("#numero").val().length == 0) {
		alert(VldEndALERTcmpnum);
		$("#numero").focus();
		return false;
	}

	if ($("#bairro").val().length == 0) {
		alert(VldEndALERTcmpbairro);
		$("#bairro").focus();
		return false;
	}

	if ($("#cidade").val().length == 0) {
		alert(VldEndALERTcmpcidade);
		$("#cidade").focus();
		return false;
	}

	if ($("#cep").val().length == 0) {
		alert(VldEndALERTcmpcep);
		$("#cep").focus();
		return false;
	}
	
	if ($("#cep").val().length < 8) {
		alert(VldEndALERTcmptamcep);
		$("#cep").focus();
		return false;
	}

	if ($("#ddd").val().length == 0) {
		alert(VldEndALERTcmpddd);
		$("#ddd").focus();
		return false;
	}

	if ($("#telefone").val().length == 0) {
		alert(VldEndALERTcmptel);
		$("#telefone").focus();
		return false;
	}

	$("#data_nasc").val($("#data_nasc_b3").val() + "-" + $("#data_nasc_b1").val() + "-" + $("#data_nasc_b2").val());
	return true;
}

//###################################################################################
function valida_dadosCobranca(Form) {
	var s;
	
	if (Form.tipcliente[1].checked==true) {
			if (Form.razao_social.val().length == 0) {
				alert(VldEndALERTcmprazaosocial);
				Form.razaosocial_cobranca.focus();
				return false;
			}
			
			var cnpj_cob = Form.cnpj_b1.val() + Form.cnpj_b2.val() + Form.cnpj_b3.val() + Form.cnpj_b4.val() + Form.cnpj_b5.val();

			if (cnpj_cob.length == 0) {
				alert(VldEndALERTcmpcnpj);
				Form.cnpj_b1.focus();
				return false;
			}
			 
			s = limpa_string(cnpj_cob);
			if (s.length == 14) {
				if (valida_CNPJ(cnpj_cob) == false ) {
					alert(VldEndALERTcmpcnpjinc);
					Form.cnpj_b1.focus();
					return false;
				}
			}else{
				alert(VldEndALERTcmpcnpjinc);
				Form.cnpj_b1.focus();
				return false;
			}
			Form.cnpj.val() = cnpj_cob;
		}

	if (Form.nome.val().length == 0) {
		alert(VldEndALERTcmpnome);
        Form.nome.focus();
        return false;
	}
       
	var cpf_cob = Form.cpf_b1.val() + Form.cpf_b2.val() + Form.cpf_b3.val() + Form.cpf_b4.val();
	
	if (cpf_cob.length == 0) {
		alert(VldEndALERTcmpcpf);
		Form.cpf_b1.focus();
		return false;
	}

	s = limpa_string(cpf_cob);
	if (s.length == 11) {
		if (valida_CPF(cpf_cob) == false ) {
			alert(VldEndALERTcmpcpfinc);
			Form.cpf_b1.focus();
			return false;
		}
	}else{
		alert(VldEndALERTcmpcpfinc);
		Form.cpf_b1.focus();
		return false;
	}

	Form.cpf.val() = cpf_cob;

	if (Form.rg.val().length == 0) {
		alert(VldEndALERTcmprg);
		Form.rg.focus();
		return false;
	}

	if (Form.endereco.val().length == 0) {
		alert(VldEndALERTcmpend);
		Form.endereco.focus();
		return false;
	}
     
	if (Form.numero.val().length == 0) {
		alert(VldEndALERTcmpnum);
		Form.numero.focus();
		return false;
	}

	if (Form.bairro.val().length == 0) {
		alert(VldEndALERTcmpbairro);
		Form.bairro.focus();
		return false;
	}

	if (Form.cidade.val().length == 0) {
		alert(VldEndALERTcmpcidade);
		Form.cidade.focus();
		return false;
	}

    if (Form.ddd.val().length == 0) {
		alert(VldEndALERTcmpddd);
		Form.ddd.focus();
		return false;
	}

	if (Form.telefone.val().length == 0) {
		alert(VldEndALERTcmptel);
		Form.telefone.focus();
		return false;
	}

    Form.data_nasc.val() = Form.data_nasc_b3.val() + "-" + Form.data_nasc_b1.val() + "-" + Form.data_nasc_b2.val();
}

// Valida CPF 
function valida_CPF(s){
	var i;
	s = limpa_string(s);

	var vlrInvalido	= new Array('11111111111','22222222222','33333333333','44444444444',
								    '55555555555','66666666666','77777777777','88888888888',
								    '99999999999','00000000000');
	for (x =0; x < vlrInvalido.length; x++) {
		if (s == vlrInvalido[x])
			return false;
	}
	
	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;
	return (dv.charAt(1) != d1 ? false : true);
}

// 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;
	
	return (dv.charAt(1) != d1 ? false : true);
}

// Limpa caracteres
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}
	}
	return temp
}

function atualizaQtd(teclapres){
	var tecla = teclapres.keyCode ? teclapres.keyCode : teclapres.which ? teclapres.which : teclapres.charCode;
	if (tecla == 13){
		 atualiza_carrinho('produtos')
	}
}

function fechaJanela(){
  top.window.close();
}

function imprimir(){
  window.parent.focus();
  window.parent.print();
}

function bloquearCaracterAlfa(evnt){
	evnt = (evnt.keyCode ? evnt.keyCode : evnt.which)  // Internet Explorer
	if (evnt != 13) {
		if ((evnt >= 40 && evnt <= 47) || (evnt >= 96 && evnt <= 122) || (evnt >= 65 && evnt <= 90)){
			return false;
		}
	}
}

function cobDiferente(valor){
	if (valor.checked == true) 
	 	$("#cobDiferente").css("display","block");
	else 
	 	$("#cobDiferente").css("display","none");
}

function pulaCep(){
	var cep = document.getElementById("cep1").value;
	if(cep.length == 5){
		document.getElementById("cep2").focus();
		return false;
	}
}


function excluirEndEntrega(desc_nome,uId) {
    if(window.confirm("Confirma a exclusao deste endereço de entregar: "+desc_nome)){
       location.href = "./e-commerce/actions/Endereco_entrega.php?uId="+uId+"&action=3";
      } 
  } // Fim da Função 


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;
}

