// Javascript com funções comuns às páginas da loja

// Retorna o valor selecionado de um Radio, seja este individual ou um grupo
function getRadioValue(radio) {
    var valorOpcao;
    if(radio.length) {
        for(i = 0; i < radio.length; i++) {
            if(radio[i].checked) {
                valorOpcao = radio[i].value;
            }
        }
    }
    else {
        if(radio.checked) {
            valorOpcao = radio.value;
        }
    }

    return valorOpcao;
}

// Busca Rápida
function validaBuscaRapida() {
    if(document.formBuscaRapida.busca.value == '') {
        alert('Por favor, preencha o campo de busca');
        return false;
    }
    else {
        return true;
    }
}

function buscaRapida() {
    if(validaBuscaRapida()) {
        document.formBuscaRapida.submit();
    }
}

// Material Promocional
function focusMatPromo(campo, texto) {
    if(campo.value == texto) {
        campo.value = '';
    }
}

function blurMatPromo(campo, texto) {
    if(campo.value == '') {
        campo.value = texto;
    }
}

function atualizaMatPromo(acao) {
    if(document.formMatPromo.emailMatPromo.value == '' || document.formMatPromo.emailMatPromo.value == 'Seu e-mail') {
        alert('Por favor, preencha o campo de e-mail');
    }
    else {
        posx = (screen.width/2)-(270/2)
        posy = (screen.height/2)-(170/2)
        features="status=yes,scrolling=no,scrollbars=no,width=" + 270 + ",height=" + 170 + ",top=" + posy + ",left=" + posx

        // obtém o valor, seja este uma combobox ou um radiogroup
        var valorOpcao;
        if(document.formMatPromo.opcaoMatPromo.options) {
            valorOpcao = document.formMatPromo.opcaoMatPromo.options[document.formMatPromo.opcaoMatPromo.selectedIndex].value;
        }
        else {
            valorOpcao = getRadioValue( document.formMatPromo.opcaoMatPromo );
        }

        if(!valorOpcao) {
            alert('Opção inválida');
        }
        else {
            window.open(acao + '&emailMatPromo=' + document.formMatPromo.emailMatPromo.value + '&opcaoMatPromo=' + valorOpcao, 'matPromo', features);
            document.formMatPromo.reset();
        }
    }
    return false;
}

function openUrl(url, target) {
    if(!target) target = "_blank";
    var wnd = window.open(url, target);
    wnd.focus();
}

function openPopup(url, windowName, width, height, resizable) {
    var posx = (screen.width/2)-(width/2);
    var posy = (screen.height/2)-(height/2);
    var resizableStr = resizable? '1': '0';
    features="directories=0,status=0,location=0,menubar=0,toolbar=0,scrollbars=0,resizable=" + resizableStr + ",width=" + width + ",height=" + height + ",top=" + posy + ",left=" + posx;
    window.open(url, windowName, features);
}

function openPopupBoleto(url) {
    window.open(url, 'boleto', 'width=700,height=600,left=0,top=0,menubar=1,toolbar=1,scrollbars=1,resizable=1');
}

function openPopupSeguranca(url) {
    window.open(url, 'seguranca', 'width=400,height=500,left=50,top=50,menubar=0,toolbar=0,scrollbars=1,resizable=1,status=1');
}

function openPopupItauShopline(url) {
    window.open(url, 'itauShopline', 'toolbar=yes,menubar=yes,resizable=yes,status=no,scrollbars=yes,width=675,height=485');
}

function openPopupPagseguro(url) {
    window.open(url, 'pagseguro', 'toolbar=no,menubar=no,resizable=yes,status=no,scrollbars=yes,width=785,height=490');
}


// Impressão de pedido
function imprimePedido(acao) {
    openPopup(acao, 'imprimePedido', 470, 470, true);
}

// Indicação de Loja
function indicaLoja(acao) {
    openPopup(acao, 'indicaLoja', 470, 470, false);
}

// Indicação de Produto
function indicaProduto(acao) {
    openPopup(acao, 'indicaProduto', 470, 470, false);
}

// OnClick para botão de comprar
function comprar(idLoja, idPrd, verificaSelCompra) {
    var prdForm = document.forms["formPrd" + idPrd];
    if(verificaSelCompra) {
        if(!prdForm) {
            window.open('/b2c/loja/Produto.do' + sparam + '?action=view&idLoja=' + idLoja + '&idPrd=' + idPrd, '_self');
        }
        else {
            // Verifica preenchimento das selecoes de compra
            var elem, idNome, id, nome, combo, qtCombos = 0, multiplosItens = false, informouQtd = false;
            for(i = 0; i < prdForm.elements.length; i++) {
                elem = prdForm.elements[i];
                if(elem.name && elem.name.indexOf('idNomeSelCompra') == 0) {
                    qtCombos++;
                    idNome = elem.value;
                    id = idNome.substring(0, idNome.indexOf(','));
                    nome = idNome.substring(idNome.indexOf(',') + 1);
                    combo = prdForm.elements['selsCompra(' + id + ')'];
                    if(combo.selectedIndex == 0) {
                        alert(nome + ': deve ser informado(a).');
                        combo.focus();
                        return;
                    }
                }
                else if(elem.name && elem.name.indexOf('qtds(') == 0 && !informouQtd) {
                    multiplosItens = true;
                    informouQtd = (elem.value != '0');
                }
            }
            if(multiplosItens && !informouQtd) {
                alert('Informe uma quantidade maior que 0.');
                return;
            }
            prdForm.submit();
        }
    }
    else if(prdForm) {
        prdForm.submit();
    }
    else {
        window.open('/b2c/loja/Pedido.do' + sparam + '?action=addItem&idLoja=' + idLoja + '&idPrd=' + idPrd, '_self');
    }
}

// Para manipulação de valores monetários
function monetarioToFloat(strMon) {
    var ret = strMon.replace(',','\.');
    return 1.0 * ret;
}

function floatToMonetario(floatVal) {
    var ret = floatVal + '';
    ret = ret.replace('\.',',');
    var i = ret.indexOf(',');
    if(i == -1) {
        ret = ret + ',00';
    }
    else {
        var qtDec = ret.length - i - 1;
        if(qtDec > 2) {
            ret = ret.substring(0, i + 3);
        }
        else if(qtDec < 2) {
            ret = ret + '00'.substring(0, 2 - qtDec);
        }
    }
    return ret;
}

function isValidMonetario(strMon) {
    return (strMon != '' && !isNaN(monetarioToFloat(strMon)));
}

function getKey(e) {
    if (window.event) return window.event.keyCode;
    else if (e) return e.which;
    else return null;
}

function isValidEventChar(e, chars) {
    var key = getKey(e);
    if(key <= 9) return true;
    var strKey = String.fromCharCode(key);
    return chars.indexOf(strKey) != -1;
}

var canChangeLayerHTML = document.getElementById || document.all || document.layers;
function changeLayerHTML(layerId, newHTML) {
	if(document.getElementById) document.getElementById(layerId).innerHTML = newHTML;
	else if(document.all) document.all[layerId].innerHTML = newHTML;
	else if(document.layers) { with(document.layers[layerId].document) {open();	write(newHTML); close();}}
}

// Cookies
function setCookie(name, value, nDias) {
    var expires = null;
    if(nDias && nDias > 0) {
        var dtHoje = new Date();
        var expires = new Date();
        expires.setTime(dtHoje.getTime() + 3600000*24*nDias);
    }
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "");
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

