/*
CSS Browser Selector v0.3.4 (Sep 29, 2009)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

function showmenu(elmnt)
        {
            document.getElementById(elmnt).style.display = "block";	
        }
        
function hidemenu(elmnt)
        {
	        document.getElementById(elmnt).style.display = "none";
        }    





//Esta função valida se o CPF é válido, usando um cálculo matemático que verifica se o dígito verificador é correspondente.
function isCPF(campo){
	//Declarando as variáveis e instanciando o númeor do CPF passado
	var dacDez, dacUni, soma, i;
	var numCPF = campo.value;

	//Verificando se o valor do CPF passado é diferente de número ou vazio
	if (numCPF == ''){
	    return false;	
	}
	else{
	    numCPF = numCPF.replace(".","");
	    numCPF = numCPF.replace(".","");
	    numCPF = numCPF.replace("-","");
	}

	//Percorrendo os 9 primeiros dígitos e executando uma somatória com eles
	soma = 0;
	for (i=0; i<=8; i++){
		soma = soma + (eval(numCPF.substring(i,i+1)) * (10-i));
	}

	//Verificando o módulo da somatória com 11
	if ((soma % 11) == 0 || (soma % 11) == 1){
	   dacDez = 0;
	}
	else{
	   dacDez = 11 - (soma % 11);
	}

	//Percorrendo os 9 primeiros dígitos e executando uma somatória com eles
	soma = 0;
	for (i=0; i<=8; i++){
		soma = soma + (eval(numCPF.substring(i,i+1)) * (11-i));
	}
	soma = soma + (dacDez * 2);

	//Verificando o módulo da somatória com 11
	if ((soma % 11) == 0 || (soma % 11) == 1){
	   dacUni = 0;
	}
	else{
	   dacUni = 11 - (soma % 11);
	}

	//Caso os 2 últimos dígitos sejam diferentes da concatenação do DACdez + DACuni, o CPF é falso
	if (numCPF.substring(numCPF.length - 2,numCPF.length) != (dacDez.toString() + dacUni.toString())){
	    campo.value = '';
	    campo.focus();
	    alert('CPF invalido, tente digitar novamente.');
		return false;
	}
	return true;
}

// Adicionando um produto
function addProduto(id, qtd, limite)
{  
    qtd = document.getElementById(qtd).value;
    
    if (isNaN(qtd) || parseInt(qtd) > parseInt(limite) || parseInt(qtd) < 1)
    {
        alert("Por favor, informe um numero na quantidade do produto para este produto.\nLimite minimo = 1\nLimite maximo = " + limite);
    }
    else
    {
        var xmlHttp = getRequestXml();
        var loading = document.getElementById("loading");
        var hoje = new Date();
        var time = hoje.getTime();
        var url = "/ajax/produto_ajax.aspx?";
        url += "&id=" + id;
        url += "&qtd=" + qtd;
        url += "&time=" + time;

        xmlHttp.onreadystatechange = function() {produto_changed(xmlHttp);}
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
        loading.style.display = 'block'; 
    }
    
    return false;
}

// Recuperando o carrinho atualizado
function produto_changed(xmlHttp)
{
    if (xmlHttp.readyState == 4)
    {          
        if (xmlHttp.status == 200)
        {
            var carrinho = document.getElementById("MiniCarrinho");
            var loading = document.getElementById("loading");
            var resposta = xmlHttp.responseText;
            
            loading.style.display = 'none';
            
            if (resposta.substr(0, 2) == '##')
            {
                alert(resposta);
            }
            else
            {
                carrinho.innerHTML = resposta;
                alert('Produto adicionado no carrinho de compras.');
            }
        }
    }
}

// Adicionando o CEP e o produto
function addCep(id, qtd, limite)
{    

    var Cep = document.getElementById("txtCep");
    qtd = document.getElementById(qtd).value;    
    
    if (Cep.value.length < 9)
    {
        alert('CEP incorreto');
        Cep.value = "";
        Cep.focus();
    }
    else if (isNaN(qtd) || parseInt(qtd) > parseInt(limite))
    {
        alert("Por favor, informe um numero na quantidade do produto para este produto.Limite maximo = " + limite);
    }
    else
    {           
        var xmlHttp = getRequestXml();        
        var loading2 = document.getElementById("loading2");        
        var fechar = document.getElementById("cepFechar");
        var botao = document.getElementById("botao");
        var hoje = new Date();
        var time = hoje.getTime();    
        var url = "/ajax/produto_ajax.aspx?";
        url += "cep=" + Cep.value;
        url += "&id=" + id;
        url += "&qtd=" + qtd;
        url += "&time=" + time;        
        xmlHttp.onreadystatechange = function() {cep_changed(xmlHttp);}
        xmlHttp.open("GET", url, true);        
        xmlHttp.send(null);         
        loading2.style.display = 'block';
        fechar.style.display = 'none';
        botao.style.display = 'none';        
    }
    
    return false;
}

// Recuperando a validacao do cep
function cep_changed(xmlHttp)
{
    if (xmlHttp.readyState == 4)
    {        
        if (xmlHttp.status == 200)
        {
            
            var resposta = xmlHttp.responseText;
            var loading2 = document.getElementById("loading2");
            var fechar = document.getElementById("cepFechar");
            var botao = document.getElementById("botao");

            loading2.style.display = 'none'; 
            
            if(resposta == 'CEP invalido')
            {
                fechar.style.display = 'block';
                botao.style.display = 'block';
                alert(resposta);
            }
            else
            {
                if(resposta != 'OK')
                {
                    alert(resposta);
                }
                else
                {
                    alert('Produto adicionado no carrinho de compras.');
                }                
                document.forms[0].submit();            
            }
        }
    }
}

// Modificando o CEP e alterando mostrando a nova cesta
function modifCep()
{
    var Cep = document.getElementById("txtCep");

    if (Cep.value.length < 9)
    {
        alert('CEP incorreto');
        Cep.value = "";
        Cep.focus();
    }
    else
    {
        var xmlHttp = getRequestXml();
        var lista = document.getElementById("lista_troca");
        var loading2 = document.getElementById("loading2");
        var hoje = new Date();
        var time = hoje.getTime();    
        var url = "/ajax/trocar_cep.aspx?";
        url += "cep=" + Cep.value;
        url += "&time=" + time;

        xmlHttp.onreadystatechange = function() {cep_trocar(xmlHttp);}
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null); 
        lista.style.display = 'none';
        loading2.style.display = 'block'; 
    }
    
    return false;
}

// Recuperando a lista de troca
function cep_trocar(xmlHttp)
{
    if (xmlHttp.readyState == 4)
    {
        if (xmlHttp.status == 200)
        {
            var lista = document.getElementById("lista_troca");
            var resposta = xmlHttp.responseText;
            var loading2 = document.getElementById("loading2");

            loading2.style.display = 'none'; 
            lista.style.display = 'block';
            lista.innerHTML = resposta;
        }
    }
}

// Adicionando um produto na lista
function addLista(id, qtd, limite)
{  
    qtd = document.getElementById(qtd).value;
    
    if (isNaN(qtd) || parseInt(qtd) > parseInt(limite) || parseInt(qtd) < 1)
    {
        alert("Por favor, informe um numero na quantidade do produto para este produto.\nLimite minimo = 1\nLimite maximo = " + limite);
    }
    else
    {
        var xmlHttp = getRequestXml();
        var loading = document.getElementById("loading");
        var hoje = new Date();
        var time = hoje.getTime();
        var url = "/ajax/lista_ajax.aspx?";
        url += "&id=" + id;
        url += "&qtd=" + qtd;
        url += "&time=" + time;

        xmlHttp.onreadystatechange = function() {lista_changed(xmlHttp);}
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
        loading.style.display = 'block'; 
    }
    
    return false;
}

// Recuperando a lista atualizado
function lista_changed(xmlHttp)
{
    if (xmlHttp.readyState == 4)
    {
        if (xmlHttp.status == 200)
        {
            var loading = document.getElementById("loading");
            var resposta = xmlHttp.responseText;
            
            loading.style.display = 'none';
            
            if (resposta.substr(0, 2) == '##')
            {
                alert(resposta);
            }
            else
            {
                alert('Produto adicionado na lista com sucesso.');
            }
        }
    }
}

// Instanciando um ajax
function getRequestXml()
{
    var http_request;

    try{ 
        http_request = new XMLHttpRequest();
        
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    }catch(e){
        try{
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            try{
                http_request= new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                http_request = null;
            }
        }
    }
  
    if (http_request == null)
        alert('Sem suporte há esta funcionalidade');
    else
        return http_request;
}

// Formatando o CEP
function Formato_CEP(input, e)
{
    var keyCode;
    
	if (window.event)
		keyCode = window.event.keyCode;
	else if (e)
		keyCode = e.which;
	
    if (keyCode != 8)
	{ 
		if(input.value.length == 5)
			input.value = input.value+'-';
	}
}

function onlynumber2(myfield, e,tolerado)
{
	if (myfield.length ==0)
		myfield.value=0;  
	
	var key;
	var keychar;
	
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	
	keychar = String.fromCharCode(key);
	
	if ((key > 97) && (key < 105))
		return true;
	if ((key==null) || (key==0) || (key==8) || (key==9)|| (key==13)|| (key==27) )
		return true;
	else if ((("0123456789"+tolerado).indexOf(keychar) > -1)){
		if (((myfield.value).indexOf(tolerado) > -1)&&(keychar==tolerado))
			return false;
		else if ((myfield.value.length==0)&&(keychar==tolerado))
		{
			myfield.value = "0";
			return true;	
		}
		else
			return true;
	}
	else
		return false;	
} 

// Somente numeros
function onlynumber(myfield, e,tolerado)
{
	if (myfield.length ==0)
		myfield.value=0;  
	
	var key;
	var keychar;
	
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
		
	keychar = String.fromCharCode(key);
	
	if ((key > 95) && (key < 106))
		return true;
	if ((key==null) || (key==0) || (key==8) || (key==9)|| (key==13)|| (key==27) )
		return true;
	else if ((("0123456789"+tolerado).indexOf(keychar) > -1)){
		if (((myfield.value).indexOf(tolerado) > -1)&&(keychar==tolerado))
			return true;			
		else if ((myfield.value.length==0)&&(keychar==tolerado))
		{
			myfield.value = "0";
			return true;	
		}
		else
			return true;
	}
	else
		return false;	
}

// Formatacao
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

Restrict = function(form){
    this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
    var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
    var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
    for(var _ in $ = this.field)
        if(/text|textarea|password/i.test(__[_].type)){
            x = $[_].split(""), c = j = 0, sp, s = [[],[]];
            for(var i = 0, l = x.length; i < l; i++)
                if(x[i] == "\\" || sp){
                    if(sp = !sp) continue;
                    s[j][c++] = p[x[i]] || x[i];
                }
                else if(x[i] == "^") c = (j = 1) - 1;
                else s[j][c++] = x[i];
            o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
            __[_].pt = s, addEvent(__[_], "keydown", function(e){
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
                setTimeout(o.onchanged, r.e = 1);
            });
            addEvent(__[_], "keyup", function(e){
                (Restrict.field = e.target).e = 0;
            });
            addEvent(__[_], "keypress", function(e){
                o.restrict(e) || e.preventDefault();
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                if(!r.e){
                    r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
                    setTimeout(o.onchanged, 1);
                }
            });
        }
}
Restrict.prototype.restrict = function(e){
    var o, c = e.key, n = (o = e.target).name, r;
    var has = function(c, r){
        for(var i = r.length; i--;)
            if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true;
        return false;
    }
    var inRange = function(c){
        return has(c, o.pt[0]) && !has(c, o.pt[1]);
    }
    return (c < 30 || inRange(String.fromCharCode(c))) ?
        (this.onKeyAccept && this.onKeyAccept(o, c), !0) :
        (this.onKeyRefuse && this.onKeyRefuse(o, c),  !1);
}
Restrict.prototype.onchanged = function(){
    var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
    if(o.l == o.value.length) return;
    if(si = o.selectionStart) moz = true;
    else if(o.createTextRange){
        var obj = document.selection.createRange(), r = o.createTextRange();
        if(!r.setEndPoint) return false;
        r.setEndPoint("EndToStart", obj); si = r.text.length;
    }
    else return false;
    for(var i in m = m.split(""))
        if(m[i] != "#")
            t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
    var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
    for(i = 0; i < l; i++)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
        }
        else{
            if(!t[j] && !(h = "")) break;
            (t[j] = h + t[j++]) && (h = "");
        }
    o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
    if(ob.c && ob.c != 46 && ob.c != 8){
        if(si != lt){
            while(m[si] != "#" && m[si]) si++;
            ini && m[0] != "#" && si++;
        }
        else si = o.value.length;
    }
    !moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si);
}

function AbrirImagemPopUp(pImagem)
{
    var lar = 300;
	var alt = 300;
	var hor = (window.screen.width - lar) / 2;
	var ver = (window.screen.height - lar) / 2;
	
	window.open(pImagem ,'Imagem_Produto','scrollbars=no,location=no,directories=no,status=no,menubar=no,resizable=no,toolbar=no,top='+ ver +',left='+ hor +',width='+ lar +',height='+ alt);	
}

function clickButton(e, buttonid){ 

      var evt = e ? e : window.event;

      var bt = document.getElementById(buttonid);

      if (bt){ 

          if (evt.keyCode == 13){ 

                bt.click(); 

                return false; 

          } 

      } 

}

function showHide(divNivel)
{
    if(document.getElementById(divNivel).style.display == 'block')
        document.getElementById(divNivel).style.display = 'none';
    else
        document.getElementById(divNivel).style.display = 'block';
}        


function fechar_alerta_carrinho(){
	document.getElementById('alerta_carrinho').style.display = 'none';
    }
	
function fechar_floater(){
	document.getElementById('ctl00_ContentPlaceHolder1_bannerFloater').style.display = 'none';
	document.getElementById('Floater_fechar').style.display = 'none';
    }