// JavaScript Document 
//Input somente numeros usado: onkeypress="return campo_numerico(event)" 
function campo_numerico(evt)
{
         var charCode = (evt.which) ? evt.which : event.keyCode;
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
}
//Mascaras Uso: onkeyup="mascara(this.value, this.id, '####.##.##.#######-#/#', event)"
function mascara(valor, id, mascara, evento){

//inicializa a variavel que vai conter o valor final
var valorFinal = "";
//verifica o que foi digitada para que seja verificado se é somente números ou não
var tecla = evento.keyCode;
//manetem o tamanho original do campo sem retirar a máscara
var valorOriginal = valor;
//inicializa um array com todos os caracteres que serão retirado
var arrNaoPermitidos = new Array("-", ".", "/", "\\", "|", "(", ")", ":", " ");
//retira qualquer máscatra que já tenho sido colocada
for(i1=0;i1<valor.length;i1++)
{
for(i2=0;i2<arrNaoPermitidos.length;i2++)
{
if(valor.charAt(i1) == arrNaoPermitidos[i2])
{
valor = valor.toString().replace( arrNaoPermitidos[i2], "" );
}
}
}
//verifica se foi precionado o backspae
if(tecla != 8)
{
//verifica se já não ultrapassou o tamanha máximo da máscara
if(mascara.length >= valorOriginal.length)
{
//loop em cima do valor do campo sem a máscara
jaTemMascara = false;
for(i=0;i<valor.length;i++)
{
//verifica se a string já recebeu alguma máscara ou não
if(jaTemMascara == false)
{
//verifica se o tipo da entrada de dados tem que ser némerica
if(mascara.charAt(i) == "#")
{
//verifica se foi digitado somente números
if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
{
//0 = 96 ou 48
//1 = 97 ou 49
//2 = 98 ou 50
//3 = 99 ou 51
//4 = 100 ou 52
//5 = 101 ou 53
//6 = 102 ou 54
//7 = 103 ou 55
//8 = 104 ou 56
//9 = 105 ou 57
//tecla == 9 = tab
valorFinal = valorFinal+ valor.charAt(i);
}
else//se não foi digitado um número é retirado o caracter da string
{
valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
}
}
else if(mascara.charAt(i) == "@")//verifica se o tipo da entrada é qualquer caracter
{
valorFinal = valorFinal+ valor.charAt(i);
}
else//se não for quelaquer caracter é algum elemento da máscara
{
//verifica se o próxima depois da máscara é númerica 
if(mascara.charAt(i + 1) == "#")
{
//verifica se foi digitado somente números
if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
{
//0 = 96 ou 48
//1 = 97 ou 49
//2 = 98 ou 50
//3 = 99 ou 51
//4 = 100 ou 52
//5 = 101 ou 53
//6 = 102 ou 54
//7 = 103 ou 55
//8 = 104 ou 56
//9 = 105 ou 57
//tecla == 9 = tab
valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)+ valor.charAt(i);
jaTemMascara = jaTemMascara + 1;
}
else//se não foi digitado um número é retirado o caracter da string
{
valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
}
}
else// se não é númerico então pode ser qualuqer caracter
{
valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)+ valor.charAt(i);
jaTemMascara = jaTemMascara + 1;
}
}
}
else//else da verificação da máscara
{
//verifica se foi digitado somente números
if(mascara.charAt(i + jaTemMascara) == "#")
{
//verifica se foi digitado somente números
if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
{
//0 = 96 ou 48
//1 = 97 ou 49
//2 = 98 ou 50
//3 = 99 ou 51
//4 = 100 ou 52
//5 = 101 ou 53
//6 = 102 ou 54
//7 = 103 ou 55
//8 = 104 ou 56
//9 = 105 ou 57
//tecla == 9 = tab
valorFinal = valorFinal+ valor.charAt(i);
}
else//se não foi digitado um número é retirado o caracter da string
{
valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
}
}
else if(mascara.charAt(i + jaTemMascara) == "@")//verifica se o tipo da entrada é qualquer caracter
{
valorFinal = valorFinal+ valor.charAt(i);
}
else
{
//verifica se foi digitado somente números
if(mascara.charAt(i + jaTemMascara +1) == "#")
{
//verifica se foi digitado somente números
if(((tecla > 95) && (tecla < 106)) || ((tecla > 47) && (tecla < 58)) || tecla == 9 || tecla == 16)
{
//0 = 96 ou 48
//1 = 97 ou 49
//2 = 98 ou 50
//3 = 99 ou 51
//4 = 100 ou 52
//5 = 101 ou 53
//6 = 102 ou 54
//7 = 103 ou 55
//8 = 104 ou 56
//9 = 105 ou 57
//tecla == 9 = tab
valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)+ valor.charAt(i);
jaTemMascara = jaTemMascara + 1;
}
else//se não foi digitado um número é retirado o caracter da string
{
valorFinal = valorOriginal.substring(0, valorOriginal.length -1);
}
}
else// se não é númerico então pode ser qualuqer caracter
{
valorFinal = valorFinal + mascara.charAt(i + jaTemMascara)+ valor.charAt(i);
jaTemMascara = jaTemMascara + 1;
}
}
}//fim da verificação da máscara
}
}
else
{
valorFinal = valorOriginal.substring(0, mascara.length);
}//final da verificação do tamanha máximo da string
}
else
{
//valorFinal = valorOriginal.substring(0, valorOriginal.length -1)
valorFinal = valorOriginal.substring(0, valorOriginal.length);
}//final da verificação do backspace
document.getElementById(id).value = valorFinal;
}

var req;
function loadXMLDoc(url,local)
{
    var xmlhttp=false;
    
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }

    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }

    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    
    // Procura por um objeto nativo (Mozilla/Safari)
    if (xmlhttp) {
        req = xmlhttp;
        switch(local) {
           case("codigo_area"):
              req.onreadystatechange = codigo_area;
           break;
           case("sub_categorias"):
              req.onreadystatechange = mostrar_subcategorias;
           break;
           case("internacional"):
              req.onreadystatechange = internacional;
           break;
           case("nacional"):
              req.onreadystatechange = nacional;
           break;   
           case("cartao"):
           	   req.onreadystatechange = cartao;
           break;        
        }
        
        req.open("GET", url, true);
        req.send(null);
    
    // Procura por uma versão ActiveX (IE)
    } else if (window.ActiveXObject) {
        alert('ie');
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange()
{
   if (req.readyState == 4) {
      if (req.status == 200) {
         return true
      } else {
         return false
      }
   }
}

function buscardados(obj,local_fonte)
{
    loadXMLDoc(obj,local_fonte);
}

function textLineBreak(sString, sReplaceThis, sWithThis) {
    if (sReplaceThis != "" && sReplaceThis != sWithThis) {
        var counter = 0;
        var start = 0;
        var before = "";
        var after = "";
        while (counter<sString.length) {
            start = sString.indexOf(sReplaceThis, counter);
            if (start == -1) {
                break;
            } else {
                before = sString.substr(0, start);
                after = sString.substr(start + sReplaceThis.length, sString.length);
                sString = before + sWithThis + after;
                counter = before.length + sWithThis.length;
            }
        }
    }
    return sString;
}


function swap_color(cod,cor){
    if(cor==1){
        cod.className='linha_focada';
    }else if(cor=="#eeeeee"){
        cod.className='linha_normal2';
    }else{
        cod.className='linha_normal';
    }
}

function pegar_subcategorias(cod_categoria,admin)
{
    if(admin==1){
        buscardados('../../includes/ajax.php?acao=subcategorias&codigo='+cod_categoria,'sub_categorias');
    }else{
        buscardados('includes/ajax.php?acao=subcategorias&codigo='+cod_categoria,'sub_categorias');
    }
}

function mostrar_subcategorias()
{
   if (req.readyState == 4) {
      if (req.status == 200) {      
        if(req.responseText){
            document.getElementById('sub_categorias').innerHTML = req.responseText;
        }else{
            document.getElementById('sub_categorias').innerHTML = "<select class='combobox' name='subcategorias' style='width:338px;'><option value='' selected>Selecione</option></select>";
        }        
      }
   }    
}

function setar_subcategoria(codigo)
{
    document.getElementById('cod_subcategoria').value = codigo;
}

function formatar(campo, mask, key)
{
      var n = campo.value.length;
      var saida = mask.substring(0,1);
      var texto = mask.substring(n);
      if ((texto.substring(0,1) != saida) && key != 8)  {
         campo.value += texto.substring(0,1);
      }
}

function nacional() 
{ 
    if (req.readyState == 4) { 
        if (req.status ==200) { 
            var temp = req.responseText.split("||");
            document.getElementById('resultado').value = "R$"+temp[0]; 
            document.getElementById('total_pedido').value = "R$" + temp[1]; 
            if(document.getElementById('cartao_visa').checked){
            	document.getElementById('pagamento').value = "1001";
                buscardados("includes/ajax.php?acao=pagamento_visa&valor="+document.getElementById('total_pedido').value+"&tipo=1","cartao");
            }else if(document.getElementById('cartao_visa_electron').checked){
            	document.getElementById('pagamento').value = "A001";
                buscardados("includes/ajax.php?acao=pagamento_visa&valor="+document.getElementById('total_pedido').value+"&tipo=2","cartao");
            }else{
                document.getElementById('pagamento_boleto').checked = true;
                document.getElementById('cartao_visa').innerHTML = "";
            }            
        } else { 
            alert("Houve um problema ao obter os dados:n" + req.statusText);    
        } 
    } 
} 

function internacional() 
{ 
    if (req.readyState == 4) {     
        if (req.status ==200) { 
            var msg = req.responseText.split('||');
            if(msg[0]){
                msg = msg[0];
                while(msg.search("<br />")>-1){
                    msg = msg.replace("<br />","\n");
                }                
                document.getElementById('resultado_internacional').value = "R$0.00"; 
                alert(msg);
            }else{
                document.getElementById('resultado_internacional').value = "R$"+msg[1]; 
                document.getElementById('total_pedido').value = "R$" + msg[2];
                if(document.getElementById('cartao_visa').checked){
                	document.getElementById('pagamento').value = "1001";
                	buscardados("includes/ajax.php?acao=pagamento_visa&valor="+document.getElementById('total_pedido').value+"&tipo=1","cartao");
                }else if(document.getElementById('cartao_visa_electron').checked){
                	document.getElementById('pagamento').value = "A001";
                	buscardados("includes/ajax.php?acao=pagamento_visa&valor="+document.getElementById('total_pedido').value+"&tipo=2","cartao");
                }else{
                	document.getElementById('pagamento_boleto').checked = true;
                	document.getElementById('cartao_visa').innerHTML = "";
                }
            }            
        } else { 
            alert("Houve um problema ao obter os dados:n" + req.statusText); 
        } 
    } 
} 


function Checacep(servico,origem,destino,peso) 
{ 
    //FUNÇÃO QUE MONTA A URL E CHAMA A FUNÇÃO AJAX 
    if(peso>30){
        alert("Pedidos acima de 30KG são entregues através de transportadoras.");
        document.getElementById('resultado').value = "R$0.00";
    }else{
        //url="calcula.php?servico="+servico+"&origem="+origem+"&destino="+destino+"&peso="+peso+"&desconto_compra="+desconto; 
        url="calcula.php?servico="+servico+"&origem="+origem+"&destino="+destino+"&peso="+peso; 
        buscardados(url,'nacional');     
    }
} 

function ChecacepInternacional(destino,peso,total,rua,cidade,estado,pais) 
{ 
    //FUNÇÃO QUE MONTA A URL E CHAMA A FUNÇÃO AJAX                                                                         
    if(document.getElementById('local_outro').checked){                                                                                        
        url="Rate.php?destino="+destino+"&peso="+peso+"&total_compra="+total+'&rua='+document.getElementById('endereco').value+'&cidade='+document.getElementById('cidade').value+'&estado='+document.getElementById('estado').value+'&pais='+document.getElementById('pais').value; 
    }else{
        url="Rate.php?destino="+destino+"&peso="+peso+"&total_compra="+total+'&rua='+rua+'&cidade='+cidade+'&estado='+estado+'&pais='+pais; 
    }
    buscardados(url,'internacional'); 
} 

function recuperar_senha()
{
    document.location = 'recuperar_senha.php';
}

function escolher_tipo_cartao(tipo)
{
	if(tipo==2){
		document.getElementById('pagamento').value = "A001";
	}else{
		document.getElementById('pagamento').value = "1001";
	}
      buscardados("includes/ajax.php?acao=pagamento_visa&valor="+document.getElementById('total_pedido').value+"&tipo="+tipo,"cartao");
}

function cartao() 
{ 
    if (req.readyState == 4) { 
        if (req.status ==200) { 
            document.getElementById('conteudo_visa').innerHTML= req.responseText; 
        } else { 
            alert("Houve um problema ao obter os dados:n" + req.statusText);    
        } 
    } 
} 

function selecionar_parcela(valor,valor_parcela)
{
	document.getElementById('pagamento').value = valor;
	document.getElementById('valor_parcela').value = valor_parcela;
}
