
initFullPage = function() {
    setPostBackRebuild();
    setShowTodasAsCategorias();
    fixTelerikRadwindow();
    arrumaPrateleiras();
    arrumaEndereco();
    criaCarrosseis();
    buscaCepCampos();
    corrigeLinksJanelas();
    criaBuscaPaginaProduto();
    defineAvaliacaoProduto();
    igualaAlturaItensTodos();
    definePopups();
    corrigePosicao();
    //	thickboxInit();


};
initJSCallBack = function() {
    //fixTelerikRadwindow();
    arrumaPrateleiras();
    arrumaEndereco();
    criaCarrosseis();
    buscaCepCampos();
    criaBuscaPaginaProduto();
    defineAvaliacaoProduto();
    corrigeLinksJanelas();
    igualaAlturaItensTodos();
};
/* fim Manter no topo */

setPostBackRebuild = function() {
    if (typeof (Sys) != 'undefined') {
        if (typeof (Sys.WebForms) != 'undefined')
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initJSCallBack);
    }
}

fixTelerikRadwindow = function() {
    if ((typeof window.Telerik != 'undefined') && (typeof window.Telerik.Web.UI.RadWindow != 'undefined')) {
        window.Telerik.Web.UI.RadWindow._createUI = window.Telerik.Web.UI.RadWindow.prototype._createUI = novoIframeTelerik;
    }
};





criaCarrosseis = function() {
    if (($('body.popup div.mais-imagens')).size() > 0) {
        $('body.popup div.mais-imagens').criaCarrossel({ 'pos': 'h3 + span', 'eh': 70, 'vertical': true, 'min': 4 });
        $('body.popup div.mais-imagens .maisImagensWrapper').parent().carrossel();
    }

    if (($('body.sku div.consumidores-tambem-compraram')).size() > 0) {
        $('body.sku div.consumidores-tambem-compraram').criaCarrossel({ 'pos': 'h2', 'dest': 'ul', 'elem': 'li', 'vertical': false, 'min': 4 });
        $('body.sku div.consumidores-tambem-compraram .maisImagensWrapper').parent().carrossel({ 'vertical': false, 'step': 1068, 'offset': 30 });
    }

    if (($('body.sku div.lista-comprar')).size() > 0) {
        $('body.sku div.lista-comprar').criaCarrossel({ 'pos': 'h2', 'dest': 'ul', 'elem': 'li', 'vertical': false, 'min': 3 });
        $('body.sku div.lista-comprar .maisImagensWrapper').parent().carrossel({ 'vertical': false, 'step': 600 });
    }

    if (($('div.vitrine-tags')).size() > 0) {
        $('div.vitrine-tags').criaCarrossel({ 'pos': 'div.titulo', 'dest': 'ul', 'elem': 'li', 'vertical': false, 'min': 4 });
        $('div.vitrine-tags .maisImagensWrapper').parent().carrossel({ 'vertical': false, 'step': 225, 'offset': 0 });
    }

    if (($('div.usuarios-utilizaram-tag')).size() > 0) {
        $('div.usuarios-utilizaram-tag').criaCarrossel({ 'pos': 'div.titulo', 'dest': 'ul', 'elem': 'li', 'vertical': false, 'min': 6 });
        $('div.usuarios-utilizaram-tag .maisImagensWrapper').parent().carrossel({ 'vertical': false, 'step': 151, 'offset': 7 });
    }

    if ($('body.lista-casamento  #titListaCasamento').size() > 0) {
        $('body.lista-casamento  #titListaCasamento').show();
    }

    if ($('body.lista-casamento div.vitrines a.btn-nav-esquerda').size() > 0) {
        $('body.lista-casamento div.vitrines a.btn-nav-esquerda').add('body.lista-casamento div.vitrines a.btn-nav-direita').remove();
    }
    if ($('body.lista-casamento  #titListaCasamento').size() <= 0) {
        $('body.lista-casamento div.vitrines').prepend('<h3 id="titListaCasamento">Lista</h3>');
    }
    if ($('body.lista-casamento div.vitrines').size() > 0) {
        $('body.lista-casamento div.vitrines').criaCarrossel({ 'pos': '#titListaCasamento', 'dest': 'ul', 'elem': 'li', 'vertical': false, 'min': 4 });
        $('body.lista-casamento div.vitrines .maisImagensWrapper').parent().carrossel({ 'vertical': false, 'step': 219, 'offset': 0 });
    }
    if ($('body.lista-casamento  #titListaCasamento').size() > 0) {
        $('body.lista-casamento  #titListaCasamento').hide();
    }

};

/* outras listas over - IE6  */
setTodasAsListasOver = function() {
    if ($.browser.msie && $.browser.version < 7) {
        $('#outras-listas-lista-container')
			.unbind()
			.mouseover(function() { $(this).addClass('over'); })
			.mouseout(function() { $(this).removeClass('over'); });
    }
};

/* Todas as Categorias */
setShowTodasAsCategorias = function() {
    //formataDivTodasCategorias();	
    $('#header div.menu-sub')
		.hide()
		.unbind()
		.mouseover(showTodasCategorias)
		.mouseout(hideTodasCategoriasTimer);
    $('#liCategoriasTodas a').unbind().mouseover(showTodasCategorias).mouseout(hideTodasCategoriasTimer);
    setTodasAsListasOver();
};


/* Passou par ao CSS */
formataDivTodasCategorias = function() {
    $('#header div.menu-sub').each(function() {
        var lnkObj = $('#liCategoriasTodas');
        var lnk = $(lnkObj).get(0);
        $(this)
			.show()
			.css({
			    top: (($(lnk).offset()).top + $(lnk).height() - 2),
			    left: ($.browser.msie && $.browser.version < 7) ? (1024 - this.clientWidth - 22 - 2) : (lnk.offsetLeft - (this.offsetWidth - lnk.offsetWidth) - 2)
			})
			.hide();
    });
    //return false;
};

getFullOffset = function(obj) {
    var x = 0;
    var y = 0;
    for (var tmpObj = obj; tmpObj.offsetParent != null; tmpObj = tmpObj.offsetParent) {
        x += tmpObj.offsetLeft;
        y += tmpObj.offsetTop;
    }
    return { 'x': x, 'y': y };
};

showTodasCategorias = function(e) {
    if (typeof showCatsTimer != 'undefined') {
        clearTimeout(showCatsTimer);
    }
    $('#header div.menu-sub').show();
    if ($.browser.msie && $.browser.version < 7) {
        $('#main div.barra-resultado-busca select').hide();
        $('#conteudo-central-produto fieldset select').css('visibility', 'hidden');
        if (typeof window.frames['wdwOutrasFormasPagamento'] != 'undefined') {
            $('div.cartao select', window.frames['wdwOutrasFormasPagamento'].document).hide();
        }
    }
    return false;
};

hideTodasCategorias = function(e) {
    if ($.browser.msie && $.browser.version < 7) {
        $('#main div.barra-resultado-busca select').show();
        $('#conteudo-central-produto fieldset select').css('visibility', 'visible');
        if (typeof window.frames['wdwOutrasFormasPagamento'] != 'undefined') {
            $('div.cartao select', window.frames['wdwOutrasFormasPagamento'].document).show();
        }
    }
    $('#header div.menu-sub').hide();
    return false;
};
hideTodasCategoriasTimer = function() {
    showCatsTimer = setTimeout('hideTodasCategorias();', 100);
};

/* Fim Todas as Categorias */

function EnviaBusca(Form, txtTexto, comboCategoria, Url) {

    textoBusca = (Form.elements[txtTexto].value.replace(/[\,\+\;\"\'\/\\\<\>]/g, ""));

    if (textoBusca == "Digite aqui")
        textoBusca = "";
    if (textoBusca != "") {
        if (textoBusca.length >= 100)
            textoBusca = textoBusca.substr(0, 99);

        Url = Url.replace("BUSCATEXTBOX", textoBusca);
        FiltroParam = "&";
        if (Form.elements[comboCategoria][document.aspnetForm.elements[comboCategoria].selectedIndex].value != "")
            FiltroParam += "fq=C:" + Form.elements[comboCategoria][Form.elements[comboCategoria].selectedIndex].value + "&";
        FiltroParam += "gravaBusca=1";
    }
    window.location = encodeURI(Url + FiltroParam);

}

function EnviaBuscaPersonalizada(Form, txtTexto, comboCategoria, Url, comboCampo) {
    aux = (Form.elements[txtTexto].value.replace(/[\,\+\;\"\'\/\\\<\>]/g, ""));
    aux = aux.replace(' ', '');

    if (aux.length < 3) {
        alert(unescape('%C9 necess%E1rio informar no m%EDnimo 3 caracteres para efetuar sua busca.'));
        return;
    }

    if (Form.elements[comboCategoria][document.aspnetForm.elements[comboCategoria].selectedIndex].value != '754' &&
        Form.elements[comboCategoria][document.aspnetForm.elements[comboCategoria].selectedIndex].value != '832') {
        EnviaBusca(Form, txtTexto, comboCategoria, Url);
    }
    else {
        FiltroParam = "";
        if (Form.elements[comboCategoria][document.aspnetForm.elements[comboCategoria].selectedIndex].value != "")
            FiltroParam = "Filtro=C" + Form.elements[comboCategoria][Form.elements[comboCategoria].selectedIndex].value + "&";
        textoBusca = (Form.elements[txtTexto].value.replace(/[\,\+\;\"\'\/\\\<\>]/g, ""));
        if (textoBusca == "Digite aqui")
            textoBusca = "";
        if (textoBusca != "") {
            if (textoBusca.length >= 100)
                textoBusca = textoBusca.substr(0, 99);
            FiltroParam += "gravaBusca=1&strBusca=" + textoBusca + "&IdCampo=" + Form.elements[comboCampo][Form.elements[comboCampo].selectedIndex].value + "&IdCategoria=&IdFaixaPreco=&IdCampoValor=";
        }
        window.location = Url + FiltroParam;
    }
}

function addCategorias(valor) {
    if (document.getElementById('userHdnIdsCategorias').value.match(valor + '_'))
        document.getElementById('userHdnIdsCategorias').value = document.getElementById('userHdnIdsCategorias').value.replace(valor + '_', '');
    else
        document.getElementById('userHdnIdsCategorias').value += valor + '_';

    //alert(document.getElementById('userHdnIdsCategorias').value);
}

function addCampos(valor) {
    if (document.getElementById('userHdnIdsCampos').value.match(valor + '_'))
        document.getElementById('userHdnIdsCampos').value = document.getElementById('userHdnIdsCampos').value.replace(valor + '_', '');
    else
        document.getElementById('userHdnIdsCampos').value += valor + '_';

    //alert(document.getElementById('userHdnIdsCampos').value);
}

function addFaixas(valor) {
    if (document.getElementById('userHdnIdsFaixasPreco').value.match(valor + '_'))
        document.getElementById('userHdnIdsFaixasPreco').value = document.getElementById('userHdnIdsFaixasPreco').value.replace(valor + '_', '');
    else
        document.getElementById('userHdnIdsFaixasPreco').value += valor + '_';

    //alert(document.getElementById('userHdnIdsFaixasPreco').value);
}

function addAgrupamentos(valor) {
    if (document.getElementById('userHdnIdsCampoValores').value.match(valor + '_'))
        document.getElementById('userHdnIdsCampoValores').value = document.getElementById('userHdnIdsCampoValores').value.replace(valor + '_', '');
    else
        document.getElementById('userHdnIdsCampoValores').value += valor + '_';

    //alert(document.getElementById('userHdnIdsFaixasPreco').value);
}

function EnviarPesquisaPersonalizada() {
    window.location = "~/Vitrine/Busca/BuscaPersonalizada.aspx?Filtro=C" + document.getElementById('ctl00_Conteudo_ctl02_ctl01_userHdnFiltro').value +
                "&strBusca=" + document.getElementById('ctl00_Conteudo_ctl02_ctl01_userHdnTextoBusca').value +
                "&IdCampo=" + document.getElementById('userHdnIdsCampos').value +
                "&IdCategoria=" + document.getElementById('userHdnIdsCategorias').value +
                "&IdFaixaPreco=" + document.getElementById('userHdnIdsFaixasPreco').value +
                "&IdCampoValor=" + document.getElementById('userHdnIdsCampoValores').value;
}

//    if(textoBusca == "Digite aqui")
//        textoBusca = "";
//    if (textoBusca != "")
//        FiltroParam += "gravaBusca=1&Filtro=#B#" + Form.elements[txtTexto].value;
//    
//    if (Form.elements[comboCategoria][document.aspnetForm.elements[comboCategoria].selectedIndex].value != "")
//    {
//        if (textoBusca != "")
//            FiltroParam += "_C" + Form.elements[comboCategoria][Form.elements[comboCategoria].selectedIndex].value + "&";
//        else
//            FiltroParam += "Filtro=C" + Form.elements[comboCategoria][Form.elements[comboCategoria].selectedIndex].value + "&";
//    }


function EnviaFiltroPedido(Form, campoStatus, campoCompra, campoDataDe, campoDataAte, Url) {
    FiltroParam = "";
    flagAtiva = Form.elements[campoStatus][Form.elements[campoStatus].selectedIndex].value;
    idCompra = Form.elements[campoCompra].value;
    dataDe = Form.elements[campoDataDe].value;
    dataAte = Form.elements[campoDataAte].value;
    FiltroParam = "flagAtiva=" + flagAtiva + "&idCompra=" + idCompra + "&dataDe=" + dataDe + "&dataAte=" + dataAte;
    window.location = Url + FiltroParam;

}

function EnviaMarca(Form, comboMarca, Url) {
    if (Form.elements[comboMarca][document.aspnetForm.elements[comboMarca].selectedIndex].value != "")
        PaginaMarca = Form.elements[comboMarca][Form.elements[comboMarca].selectedIndex].value;
    window.location = PaginaMarca;

}

function onEnter(evt, frm, btnEnter) {
    var keyCode = null;

    if (evt.which) {
        keyCode = evt.which;
    }
    else if (evt.keyCode) {
        keyCode = evt.keyCode;
    }
    if (13 == keyCode) {
        frm.elements[btnEnter].click();
        return false;
    }
    return true;
}


function Popup(url, width, height) {
    if (document.all && window.print) //ie5+
    //window.showModalDialog (url,"Popup","help:0;resizable:1;dialogWidth:'+mwidth+'px;dialogHeight:'+mheight+'px");
        window.open(url, "Popup", "width='+width+'px,height='+height+'px,resizable=1,scrollbars=1,status=yes");
    else
        window.open(url, "Popup", "width='+width+'px,height='+height+'px,resizable=1,scrollbars=1,status=yes");
}
function VerifiedByVisa_SaibaMais() {
    window.open('http://www.visa.com.br/vbv/vbv_saibamais.asp', 'principal', 'height=435,width=270,top=0,left=0,resizable=no,status=1')
}

/**
*
* Salta para o próximo campo se o campo informado tiver atingido o tamanho máximo.
*
*/
var dicionarioSaltaCampo;
function SaltaCampo(campo, prox, tammax, teclapres) {
    var tecla = teclapres.keyCode;
    var vr = campo.value;
    var tam = vr.length;

    // Desconsidera o [tab] e o [shift+tab]
    if ((tecla != 9) && (tecla != 16))
        if (campo.value.length >= tammax) {
        // Trunca o conteudo para o tamanho máximo, no caso de CTRL+V
        campo.value = campo.value.substring(0, tammax);

        // Muda o foco para o próximo componente
        prox.focus();
    }


    /*    
    var tamanhoAnterior = 0;
    
    if(dicionarioSaltaCampo != null)
    {
    tamanhoAnterior = dicionarioSaltaCampo[campo.id];
    }
    else
    {
    dicionarioSaltaCampo = new Array();
    }
    if(tamanhoAnterior == null)
    {
    tamanhoAnterior = campo.tamanhoAnterior == null ? 0 : campo.tamanhoAnterior;
    }
    if(tamanhoAnterior < tam)
    {
    dicionarioSaltaCampo[campo.id] = tam;
    if ( tam == tammax )
    prox.focus();
    }    
    */
}
/**
*
* Salta para o campo anterior se o campo informado tiver atingido o tamanho máximo.
*
*/
function SaltaCampoTras(campo, prox, tammax, e) {
    //    var tecla = e.keyCode != null ? e.keyCode : (e.charCode != null ? e.charCode : e.which);
    //    if (tecla == 9 && e.shiftKey && !e.ctrlKey && !e.altKey)
    //    {
    //         //prox.focus();
    //	     e.returnValue = false;
    //    }
    //    else
    //    e.returnValue = true;  
}

function checkKeySetClick(srcClickObj, e) {
    var key;

    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //firefox

    if (key == 13) {
        //var btn = document.getElementById(srcClickObj);
        //if (btn != null) {
        //btn.click();
        //event.keyCode = 0
        return false;
        //}
    }
}

function Seleciona(ObjSrc, DefValue) {
    if (ObjSrc.value == DefValue) { ObjSrc.value = '' } else { ObjSrc.select() }
}

function Abandona(ObjSrc, DefValue) {
    if (ObjSrc.value == '') ObjSrc.value = DefValue
}

function PopUpWindow(url, width, height, name, scroll) {
    var top = (screen.height - height) / 2;
    var left = (screen.width - width) / 2;
    window.open(url, name, 'scrollbars=' + scroll + ',status=0,menubar=0,resize=0,width=' + width + ',height=' + height + ',top=' + top + ',left=' + left);
}

function mascara(o, f) {
    v_obj = o
    v_fun = f
    setTimeout("execmascara()", 1)
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value)
}

function cpf(v) {
    v = v.replace(/\D/g, "")                    //Remove tudo o que não é dígito
    v = v.substring(0, 11);                     //Trunca digitos excedentes
    v = v.replace(/(\d{3})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cnpj(v) {
    v = v.replace(/\D/g, "")                           //Remove tudo o que não é dígito
    v = v.substring(0, 14);                            //Trunca digitos excedentes
    v = v.replace(/^(\d{2})(\d)/, "$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v = v.replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v = v.replace(/\.(\d{3})(\d)/, ".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v = v.replace(/(\d{4})(\d)/, "$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function validaData(oSrc, args) {
    var arrDtIn = args.Value.split('/');
    var strDtIn = ('00' + arrDtIn[0]).replace(/^0+(\d\d)/, '$1');
    strDtIn += ('/' + ('00' + arrDtIn[1]).replace(/^0+(\d\d)/, '$1'));
    strDtIn += ('/' + ('0000' + arrDtIn[2]).replace(/^0+(\d\d\d\d)/, '$1'));


    if (arrDtIn.length < 3)
        return args.IsValid = false;

    var dtIn = new Date(parseInt(arrDtIn[2], 10), parseInt(arrDtIn[1], 10) - 1, parseInt(arrDtIn[0], 10));

    var strDtOut = ('00' + dtIn.getDate()).replace(/^0+(\d\d)/, '$1');
    strDtOut += ('/' + ('00' + (dtIn.getMonth() + 1)).replace(/^0+(\d\d)/, '$1'));
    strDtOut += ('/' + dtIn.getFullYear());


    if (strDtIn != strDtOut)
        args.IsValid = false;
    else
        args.isValid = true;

    return false;
}

function validaDataNasc(oSrc, args) {
    var arrDtIn = args.Value.split('/');
    var strDtIn = ('00' + arrDtIn[0]).replace(/^0+(\d\d)/, '$1');
    strDtIn += ('/' + ('00' + arrDtIn[1]).replace(/^0+(\d\d)/, '$1'));
    strDtIn += ('/' + ('0000' + arrDtIn[2]).replace(/^0+(\d\d\d\d)/, '$1'));

    if (arrDtIn.length < 3)
        args.IsValid = false;

    var dtIn = new Date(parseInt(arrDtIn[2], 10), parseInt(arrDtIn[1], 10) - 1, parseInt(arrDtIn[0], 10));

    var strDtOut = ('00' + dtIn.getDate()).replace(/^0+(\d\d)/, '$1');
    strDtOut += ('/' + ('00' + (dtIn.getMonth() + 1)).replace(/^0+(\d\d)/, '$1'));
    strDtOut += ('/' + dtIn.getFullYear());

    alert(strDtIn + ">>" + strDtOut);

    if ((strDtIn != strDtOut) || (dtIn > new Date()))
        args.IsValid = false;

    args.isValid = true;
}

function validaDataEvento(oSrc, args) {
    var arrDtIn = args.Value.split('/');
    var strDtIn = ('00' + arrDtIn[0]).replace(/^0+(\d\d)/, '$1');
    strDtIn += ('/' + ('00' + arrDtIn[1]).replace(/^0+(\d\d)/, '$1'));
    strDtIn += ('/' + ('0000' + arrDtIn[2]).replace(/^0+(\d\d\d\d)/, '$1'));


    if (arrDtIn.length < 3)
        return args.IsValid = false;

    var dtIn = new Date(parseInt(arrDtIn[2], 10), parseInt(arrDtIn[1], 10) - 1, parseInt(arrDtIn[0], 10));

    var strDtOut = ('00' + dtIn.getDate()).replace(/^0+(\d\d)/, '$1');
    strDtOut += ('/' + ('00' + (dtIn.getMonth() + 1)).replace(/^0+(\d\d)/, '$1'));
    strDtOut += ('/' + dtIn.getFullYear());


    if ((strDtIn != strDtOut) || (dtIn < new Date()))
        args.IsValid = false;
    else
        args.isValid = true;

    return false;
}

function valida_CPFCNPJ(oSrc, args) {

    if (args.Value.replace(/[^\d]/g, '').length == 11) {
        valida_CPF(oSrc, args);
    }
    else if (args.Value.replace(/[^\d]/g, '').length == 14) {
        valida_CNPJ(oSrc, args);
    }
    else {
        args.IsValid = false;
    }

}

function CpfCnpjIsValid(value) {
    var cpfCnpj = value.replace(/[^\d]/g, '');

    if (cpfCnpj.length == 11)
        return CpfIsValid(cpfCnpj);

    else if (cpfCnpj.length == 14)
        return CnpjIsValid(cpfCnpj);

    else
        return false;

}

//Validação de CPF
function valida_CPF(oSrc, args) {
    args.IsValid = CpfIsValid(args.Value);
}

function CpfIsValid(value) {
    var i;

    s = value.replace(/[^\d]/g, '');

    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;
}

//Validação de CNPJ
function valida_CNPJ(oSrc, args) {
    args.IsValid = CnpjIsValid(args.Value);
}

function CnpjIsValid(value) {
    var cnpj = value;
    var valida = new Array(6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2);
    var dig1 = new Number;
    var dig2 = new Number;

    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace(exp, "");
    var digito = new Number(eval(cnpj.charAt(12) + cnpj.charAt(13)));

    for (i = 0; i < valida.length; i++) {
        dig1 += (i > 0 ? (cnpj.charAt(i - 1) * valida[i]) : 0);
        dig2 += cnpj.charAt(i) * valida[i];
    }
    dig1 = (((dig1 % 11) < 2) ? 0 : (11 - (dig1 % 11)));
    dig2 = (((dig2 % 11) < 2) ? 0 : (11 - (dig2 % 11)));

    if (((dig1 * 10) + dig2) != digito) {
        return false;
    }
    return true;
}

function soNumeros(v) {
    return v.replace(/\D/g, "")
}

function AlertDesenvolvimento() {
    alert("Funcionalidade em Desenvolvimento\n Aguarde pr�ximos releases.");
}
function AlertSemEspecificacao() {
    alert("Especifica��o pendente.\n Aguarde pr�ximos releases.");
}

var incItensCompara = 0;
var objComparacao;

function MarcarComparacao(idProd, marcado) {
    var obj = objComparacao;
    var vet = obj.value.split(",");
    var achou;


    //Adiciono os ids clicados
    if (marcado) {
        incItensCompara++;
        achou = false;
        for (i = 0; i <= vet.length - 1; i++) {
            if (idProd == vet[i])
                achou = true;
        }
        if (!achou) {
            if (obj.value.length > 0)
                obj.value += "," + idProd;
            else
                obj.value += idProd;
        }
    }
    else //Apago os ids clicados
    {
        incItensCompara--;
        if (obj.value.length > 0) {
            for (i = 0; i <= vet.length - 1; i++) {
                if (idProd == vet[i]) {
                    if (i == 0) {
                        if (vet.length > 1)
                            obj.value = obj.value.replace(idProd + ",", "");
                        else
                            obj.value = obj.value.replace(idProd, "");
                    }
                    else
                        obj.value = obj.value.replace("," + idProd, "");
                }
            }
        }
    }
    if (document.getElementById("NumeroSuperior") != null) {
        document.getElementById("NumeroSuperior").innerHTML = incItensCompara;
        document.getElementById("NumeroInferior").innerHTML = incItensCompara;
    }
}

function Comparar(ClientID, Url) {
    var obj = document.getElementById(ClientID);
    var MsgErro = document.getElementById("divAlerta");
    objComparacao = obj;
    var vet = obj.value.split(",");

    if (vet.length >= 2 && vet.length <= 4) {
        window.location = "../../Site/ComparacaoProduto.aspx?ProdutosCompara=" + obj.value + "&ReturnUrl=" + Url;
    }
    else if (vet.length < 2) {
        MsgErro.innerHTML = "<p><strong>Aten&ccedil;&atilde;o: </strong> M&iacute;nimo de 2 produtos para comparar.</p>";
        MsgErro.style.display = 'block';
    }
    else if (vet.length > 4) {
        MsgErro.innerHTML = "<p><strong>Aten&ccedil;&atilde;o:: </strong> M&aacute;ximo de 4 produtos para comparar.</p>";
        MsgErro.style.display = 'block';
    }

}


function MontaAlerta(msgAlerta) {
    var MsgErro = document.getElementById("divAlerta");
    MsgErro.innerHTML = "<p><strong>Aten&ccedil;&atilde;o: </strong>" + msgAlerta + "</p>";
    MsgErro.style.display = 'block';
}


function MontaUrl(url, ClientID) {
    var obj = document.getElementById(ClientID);
    objComparacao = obj;
    window.location = url + '&ComparacaoProdutos=' + obj.value;
}

function CarregaTela(ClientID) {
    var obj = document.getElementById(ClientID);
    objComparacao = obj;
    var vet = obj.value.split(",");

    if (incItensCompara == 0) {
        if (vet[0] != "")
            incItensCompara = vet.length;
        if (document.getElementById("NumeroSuperior") != null) {
            document.getElementById("NumeroSuperior").innerHTML = incItensCompara;
            document.getElementById("NumeroInferior").innerHTML = incItensCompara;
        }
    }
}

function chat(url) {
    var hWnd = window.open(url, "chat", "width=400,height=450,resizable=no,toolbar=0,location=0,directories=0,status=no,menubar=0,scrollbars=0");
    //window.open(url,"chtsub","width=620,height=428,resizable=no,toolbar=0,location=0,directories=0,status=no,menubar=0,scrollbars=0");
    if (hWnd != null) {
        if (hWnd.opener == null) {
            hWnd.opener = self;
            hWnd.location.href = url;
        }
    }
}

function checkFormValidation(oDivMensagem, sRedirecionamentos) {
    if (BuscandoCEP) {
        BuscandoCEP = false;
        return;
    }

    if (typeof (Page_IsValid) != "undefined") {
        for (i = 0; i < Page_Validators.length; i++) {
            var sCtrl = Page_Validators[i].controltovalidate;
            var oCtrl = document.getElementById(sCtrl);

            if (typeof (oCtrl) != "undefined" && oCtrl != null) {
                try {
                    if ((oCtrl.tagName && oCtrl.tagName == 'SELECT') || (oCtrl == "[object HTMLSelectElement]")) {
                        oCtrl.className = oCtrl.className.replace(/^erroSelect$/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/^erroSelect\s/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/\serroSelect$/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/\serroSelect\s/gi, ' ');
                    }
                    else {
                        oCtrl.className = oCtrl.className.replace(/^erro$/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/^erro\s/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/\serro$/gi, ' ');
                        oCtrl.className = oCtrl.className.replace(/\serro\s/gi, ' ');
                    }
                }
                catch (err)
                 { }
            }

            var arrRedirecionamentos = sRedirecionamentos.split('#');
            for (k = 0; k < arrRedirecionamentos.length; k++)
                if ((arrRedirecionamentos[k] != null) && (arrRedirecionamentos[k] != '')) {
                oCtrl = document.getElementById(arrRedirecionamentos[k].split('|')[1]);
                if (typeof (oCtrl) != "undefined" && oCtrl != null) {
                    oCtrl.className = oCtrl.className.replace(/^erro$/gi, ' ');
                    oCtrl.className = oCtrl.className.replace(/^erro\s/gi, ' ');
                    oCtrl.className = oCtrl.className.replace(/\serro$/gi, ' ');
                    oCtrl.className = oCtrl.className.replace(/\serro\s/gi, ' ');
                }
            }
        }

        if (!Page_IsValid) {

            var arrRedirecionamentos = sRedirecionamentos.split('#');
            var arrObjInvalidos = new Array();

            document.getElementById(oDivMensagem).style.display = 'block';

            for (i = 0; i < Page_Validators.length; i++) {
                var sCtrl = Page_Validators[i].controltovalidate;
                var oCtrl = document.getElementById(sCtrl);

                if (!Page_Validators[i].isvalid) {
                    for (k = 0; k < arrRedirecionamentos.length; k++) {
                        if (arrRedirecionamentos[k] != null)
                            if (arrRedirecionamentos[k].split('|')[0] == sCtrl)
                            arrObjInvalidos[arrObjInvalidos.length] = document.getElementById(arrRedirecionamentos[k].split('|')[1]);
                    }

                    arrObjInvalidos[arrObjInvalidos.length] = oCtrl;
                }
            }

            for (i = 0; i < arrObjInvalidos.length; i++)
                if ((typeof (arrObjInvalidos[i]) != 'undefined') && (arrObjInvalidos[i] != null)) {
                if ((arrObjInvalidos[i].tagName && arrObjInvalidos[i].tagName == 'SELECT') || (arrObjInvalidos[i] == "[object HTMLSelectElement]")) {
                    arrObjInvalidos[i].className += " erroSelect";
                } else {
                    arrObjInvalidos[i].className += " erro";
                }
            }

            return false
        }
    }
}


// ########################   
// Carrossel usando jQuery
// ########################

(function($) {
    $.fn.carrossel = function(o) {
        return this.each(function() {
            new $.carrossel(this, o);
        });
    };
    var defaults = {
        vertical: true,
        step: 70,
        min: 4,
        offset: 0,
        btprev: '.btn-sobeCar',
        btnext: '.btn-desceCar',
        inner: '.maisImagensInner',
        dest: 'img',
        elem: 'img',
        ew: false,
        eh: false
    };

    $.carrossel = function(e, o) {
        this.options = $.extend({}, defaults, o || {});

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        this.options.inner = $(e).find(this.options.inner);
        this.options.btprev = $(e).find(this.options.btprev);
        this.options.btnext = $(e).find(this.options.btnext);

        this.car = {
            elDim: 0,
            parDim: 0,
            limits: {
                prev: 0,
                next: 0
            },
            start: function() {
                $(obj.options.inner).css('top', 0).css('left', 0);
                $(e).addClass(((!obj.options.vertical) ? 'carHorizontal' : 'carVertical'));

            },
            prev: function() {
                obj.walk(this, $(obj.options.inner), obj.wh, obj.lt, true);
                return false;
            },
            next: function() {
                obj.walk(this, $(obj.options.inner), obj.wh, obj.lt, false);
                return false;
            },
            walk: function(bt, el, dim, dir, sinal) {
                var newPos = parseInt($(el).css(dir));
                obj.getDim();
                newPos = (sinal) ? newPos + obj.options.step : newPos - obj.options.step;
                newPos = obj.checkLimits(bt, newPos);
                if (obj.options.vertical) {
                    $(el).animate({ 'top': newPos }, 500);
                } else {
                    $(el).animate({ 'left': newPos }, 500);
                }
                //$(el).css(dir, newPos);
            },
            checkLimits: function(bt, pos) {
                obj.reenableButtons(bt);
                if (pos >= obj.limits.next) {
                    pos = 0;
                    obj.disableButton(obj.options.btnext, 'nextDisabled');
                } else if (pos <= (obj.limits.prev + obj.options.offset)) {
                    pos = obj.limits.prev + obj.options.offset;
                    obj.disableButton(obj.options.btprev, 'prevDisabled');
                } else {

                }
                return pos;
            },
            disableButton: function(el, classe) {
                var cl = (typeof classe != 'undefined') ? classe : '';
                $(el).addClass(cl + ' btDisabled');
            },
            reenableButtons: function(bt) {
                $(bt).parent().find('a.btCarrossel').removeClass('nextDisabled prevDisabled btDisabled');
            },
            getDim: function() {
                if (obj.elDim == 0 && obj.parDim == 0 && obj.limits.prev == 0) {
                    obj.elDim = !obj.options.vertical ? parseInt($(obj.options.inner).width()) : parseInt($(obj.options.inner).height());
                    obj.parDim = !obj.options.vertical ? parseInt($(obj.options.inner).parent().width()) : parseInt($(obj.options.inner).parent().height());
                    obj.limits = {
                        prev: (obj.parDim - obj.elDim),
                        next: 0
                    };
                }
            }
        };

        this.self = $.extend(this, this.car);
        var obj = this.self;
        obj.start();
        obj.getDim();
        $(obj.options.btprev).unbind().click(obj.prev);
        $(obj.options.btnext).unbind().click(obj.next);
    };

    $.fn.criaCarrossel = function(o) {
        return this.each(function() {
            new $.criaCarrossel(this, o);
        });
    };
    $.criaCarrossel = function(e, o) {
        this.options = $.extend({}, defaults, o || {});
        var pos, carContainer, imgs, self, els;
        self = this;

        if ($(self).find('div.maisImagensWrapper').length > 0) {
            return this;
        }

        els = $(e).find(self.options.elem);
        if ($(els).length <= self.options.min) {
            return this;
        }
        pos = $(e).find(self.options.pos);
        $(pos).after('<div class="carrosselProdutos">');
        carContainer = $(e).find('div.carrosselProdutos');
        $(carContainer).html('<a href="#" class="btn-nav-esquerda btn-sobeCar btCarrossel">sobe</a><div class="maisImagensWrapper"><div class="maisImagensInner"></div></div><a href="#" class="btn-nav-direita btn-desceCar btCarrossel">desce</a>');
        $(e).find(self.options.dest).each(function() {
            $(e).find('.maisImagensInner').append($(this).clone(true));
            $(this).remove();
        });

        $(e).find('.maisImagensInner').each(function(count, el) {
            var numLi, tw, th;
            numLi = $(el).find(self.options.elem);

            if (self.options.vertical) {
                th = $(numLi).length * (self.options.eh || ($(numLi).eq(0).height() + parseInt($(numLi).eq(0).css('marginTop')) + parseInt($(numLi).eq(0).css('marginBottom'))));
                //$(el).find(self.options.dest).eq(0).height(th);
                $(el).height(th);
            } else {
                tw = $(numLi).length * (self.options.ew || ($(numLi).eq(0).width() + parseInt($(numLi).eq(0).css('marginLeft')) + parseInt($(numLi).eq(0).css('paddingLeft')) + parseInt($(numLi).eq(0).css('paddingRight')) + parseInt($(numLi).eq(0).css('marginRight'))));
                $(el).find(self.options.dest).eq(0).width(tw);
                $(el).width(tw);
            }

            /*
            $(el).
            css('width', (self.options.dest == self.options.elem) ? tw : $(el).find(self.options.dest).eq(0).width(tw).width()).
            css('height', (self.options.dest == self.options.elem) ? th : $(el).find(self.options.dest).eq(0).height(th).height()
            );
            */
        });

    };
})(jQuery);

// ########################
arrumaPrateleiras = function() {
    var tamanhoMaximo = 0;
    $(".prateleira").each(
		function alteraNome(item) {
		    //$(this).removeClass("prateleira");
		    //$(this).addClass("ativo");
		    tamanhoMaximo = 0;
		    var lis = $(this).find("ul > li");
		    $(lis).each(
					function mostraTamanho(item) {
					    //if ($(this).parent().parent().hasClass("ativo")) {
					    var tamanho = $(this).height();
					    if (tamanhoMaximo < tamanho) {
					        tamanhoMaximo = tamanho;
					    }
					    //}
					}
				)
		    $(lis).height(tamanhoMaximo);
		    //$(this).removeClass("ativo");
		}
	)
}



//arrumaPrateleiras = function() {
//    var tamanhoMaximo = 0;
//    $(".prateleira").each(
//		function alteraNome(item) {
//		    //$(this).removeClass("prateleira");
//		    $(this).addClass("ativo");
//		    tamanhoMaximo = 0;

//		    $(".ativo ul > li").each(
//					function mostraTamanho(item) {
//					    //if ($(this).parent().parent().hasClass("ativo")) {
//					        var tamanho = $(this).height();
//					        if (tamanhoMaximo < tamanho) {
//					            tamanhoMaximo = tamanho;
//					        }
//					    //}
//					}
//				)
//		    $(".ativo ul li").height(tamanhoMaximo);
//		    $(this).removeClass("ativo");
//		}
//	)
//}

novoIframeTelerik = function() {
    if (!this._popupElement) {
        var _85 = this.get_id();
        var _86 = "RadWindowWrapper_" + _85;
        var _87 = document.createElement("DIV");
        _87.id = _86;
        _87.className = this._getFullSkinName();
        _87.style.width = this._width;
        _87.style.height = this._height;
        _87.setAttribute("unselectable", "on");
        this._popupElement = _87;
        var _88 = document.createElement("TABLE");
        _88.cellSpacing = 0;
        _88.cellPadding = 0;
        this._tableElement = _88;
        var _89 = ["corner topleft", "titlebar", "corner topright", "corner bodyleft", "windowcontent", "corner bodyright", "corner bodyleft", "statusbar", "corner bodyright", "corner footerleft", "footercenter", "corner footerright"];
        var _8a = ["titlerow", "contentrow", "statusbarrow", "footerrow"];
        var _8b = 0;
        for (var i = 0; i < 4; i++) {
            var row = _88.insertRow(-1);
            row.className = _8a[i];
            for (var j = 1; j <= 3; j++) {
                var _8f = row.insertCell(-1);
                _8f.innerHTML = "&nbsp;";
                _8f.className = _89[_8b];
                _8b++;
            }
        }
        var _90 = _88.rows[0].cells[1];
        _90.innerHTML = "";
        this._titleCell = _90;
        var _91 = document.createElement("DIV");
        _91.className = "topresize";
        _91.innerHTML = "<!-- / -->";
        this._topResizer = _91;
        this._titleCell.appendChild(this._topResizer);
        var _92 = this._createDefaultTable();
        _92.className = "titlebarcontrols";
        this._titlebarElement = _92;
        this._titleCell.appendChild(this._titlebarElement);
        var _93 = this._getTitleIcon();
        var _94 = this._titlebarElement.rows[0].insertCell(-1);
        _94.appendChild(_93);
        var _95 = this._getTitleElement();
        var _90 = this._titlebarElement.rows[0].insertCell(-1);
        _90.appendChild(_95);
        this.set_title(this._title);
        var _96 = this._titlebarElement.rows[0].insertCell(-1);
        _96.noWrap = true;
        _96.style.whiteSpace = "nowrap";
        _96.appendChild(this._getTitleCommandButtonsHolder());
        var _97 = _88.rows[1].cells[1];
        _97.vAlign = "top";
        _97.innerHTML = "";
        this._contentCell = _97;
        var _98 = this.get_name();
        var _99 = ($telerik.isIE) ? document.createElement("<iframe src='" + dDominioSite + "/Js/blank.html' allowtransparency='true' name='" + _98 + "'>") : document.createElement("iframe");
        _99.name = _98;
        _99.src = "javascript:'<html></html>';";
        _99.style.width = "100%";
        _99.style.height = "100%";
        _99.style.border = "0px";
        _99.frameBorder = "0";
        this._iframe = _99;
        this._contentCell.appendChild(this._iframe);
        var _9a = this._createDefaultTable();
        _9a.style.width = "100%";
        this._statusCell = _88.rows[2].cells[1];
        this._statusCell.innerHTML = "";
        this._statusCell.appendChild(_9a);
        var _9b = _9a.rows[0].insertCell(-1);
        _9b.style.width = "100%";
        var _9c = this._getStatusMessageElement();
        _9b.appendChild(_9c);
        var _9d = _9a.rows[0].insertCell(-1);
        _9d.style.width = "15px";
        var _9e = document.createElement("DIV");
        _9d.appendChild(_9e);
        this._bottomResizer = _9e;
        this._createBackReference();
        this._popupElement.appendChild(this._tableElement);
        this._popupElement.style.display = "none";
        this._popupElement.style.position = "absolute";
        this._addWindowToDocument();
        this.set_behaviors(this._behaviors);
        this._registerTitlebarHandlers(true);
        this.set_visibleTitlebar(this._visibleTitlebar);
        this.set_visibleStatusbar(this._visibleStatusbar);
    }
    if (!this._popupBehavior) {
        this._popupBehavior = $create(Telerik.Web.PopupBehavior, {
            "id": (new Date() - 100) + "PopupBehavior",
            "parentElement": null,
            "overlay": this._overlay,
            "keepInScreenBounds": this._keepInScreenBounds
        }, null, null, this._popupElement);
    }
}

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 false;
        else return true;
    }
}

var BuscandoCEP;
function AvancaCampo(campo, prox, tammax, teclapres) {
    //alert('AvancaCampo2');
    BuscandoCEP = true;
    var tecla = teclapres.keyCode;
    var Origem = document.getElementById(campo);
    var Destino = document.getElementById(prox);

    // Desconsidera o [tab] e o [shift+tab]
    if ((tecla != 9) && (tecla != 16))
        if (Origem.value.length >= tammax) {
        // Trunca o conteudo para o tamanho m?ximo, no caso de CTRL+V
        Origem.value = Origem.value.substring(0, tammax);

        //D? o submit para carregar o endere?o.
        if (Origem.value.length == 5 && Destino.value.length == 3) {
            if (typeof SubmitCep == 'function')
                SubmitCep();
            else
                $('#form').submit();
        }
        else if (Origem.value.length == 3) {
            if (typeof SubmitCep == 'function')
                SubmitCep();
            else
                $('#form').submit();
        }

        // Muda o foco para o pr?ximo componente
        Destino.focus();
    }
}

// Ajusta o tamanho dos boxs dos enderecos
arrumaEndereco = function() {
    var alturaMaxima = 0;
    var divs = $(".lista-endereco ul li .endereco");

    $(divs).each(function(item) {
        var altura = $(this).attr('offsetHeight');
        alturaMaxima = (altura > alturaMaxima) ? altura : alturaMaxima;
    });
    $(divs).each(function(item) {
        $(this).height(alturaMaxima);
    });
};

/* Cadastra campos de CEP para a validacao */
buscaCepCampos = function() {
    $('#labelTxtCepPrefixo input')
		.keyup(function(event) { SaltaCampo(this, $('#labelTxtCepSufixo input').get(0), 5, event); })
		.keypress(campoApenasNumeros);
    $('#labelTxtCepSufixo input').keypress(campoApenasNumeros);
};

campoApenasNumeros = function(event) {
    if (event.keycode == 13) {
        return false;
    }
    mascara(this, soNumeros);
};

function GetRadWindow() {
    var oWindow = null;

    if (window.radWindow) {
        oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog
    } else if (window.frameElement.radWindow) {
        oWindow = window.frameElement.radWindow; //IE (and Moz az well)
    }
    return oWindow;
}


function CloseOnReload() {
    GetRadWindow().Close();
}


function RefreshParentPage() {
    GetRadWindow().BrowserWindow.location.reload();
}



// ---------------------------------------------------------
// Fun��es para controle das opera��es na p�gina de produto.
// ---------------------------------------------------------

//
// Select de sku do produto. 
//

var _fieldsetselecaosku = null;


//
// Inicia as vari�veis da p�gina de produto. 
//
function setIdFieldsetSelecaoSku(idFieldsetSelecaoSku) {
    _fieldsetselecaosku = document.getElementById(idFieldsetSelecaoSku);
}

//
// Esconde os elementos no menu de navegacao lateral da pagina de produto.
//
function ConfiguraVejaNestaPagina() {
    if ($("#" + idQvct).html() == null || $("#" + idQvct).html().trim().length == 0) { $("#lnkQvct").hide(); }
    if ($("#" + idQcct).html() == null || $("#" + idQcct).html().trim().length == 0) { $("#lnkQcct").hide(); }
    if ($("#" + idQvvt).html() == null || $("#" + idQvvt).html().trim().length == 0) { $("#lnkQvvt").hide(); }
}

//
// Muda todas as informa��es da imagem principal.
//
function setImage(thumbId, mainId, texto) {
    //var mainImg = document.getElementById(mainId).src;
    //var thumbImg = document.getElementById(thumbId).src;
    //document.getElementById(mainId).src = thumbImg;
    //document.getElementById("txtLegenda_Popup").innerHTML = texto;
}
//
// Fun��o que troca o source de uma imagem destino para a imagem origem.
//
function MudaImagem(IdImagemDestino, ImagemOrigem) {
    document.getElementById(IdImagemDestino).src = ImagemOrigem;
}

// 
// Ao fechar o popup devo inicializar a imagem Ampliada padr�o
// Para isso eu pego o ID da imagem atual e substituo pelo ID da imagem padr�o
//
function Fechar(Id) {
    ImgAtual = document.getElementById("Main_" + Id).src; // Pego o src da imagem ampliada atual
    pos = ImgAtual.indexOf("="); // Encontrar a posicao do ID do Arquivo
    ImgNova = ImgAtual.substring(0, pos + 1); // Monto o SRC com o ID padr�o
    ImgNova += Id;
    document.getElementById("Main_" + Id).src = ImgNova; // Substitituo a Imd Atual pela Padr�o
}

//
// Mostra a imagem do thumbnail em que o mouse est� passando por cima na janela de visualiza��o
// das imagens do produto na tela de produto.
//
function MostraImagePrincipal(thumbId, mainId, imgPrincipal) {
    var mainImg = document.getElementById(mainId).src;
    var thumbImg = document.getElementById(thumbId).src;
    if (imgPrincipal != "") { // MouseOut
        document.getElementById(thumbId).src = mainImg;
        document.getElementById(mainId).src = imgPrincipal;
    }
    else { // MouseOver
        document.getElementById(mainId).src = thumbImg; // Na �rea da Imagem Principal � mostrado o Thumb
    }
}

function MostraSku(idSkus, idSku) {
    aIdSku = idSkus.split(",");
    for (var i = 0; i < aIdSku.length; i++) {
        var Div = "Sku_" + aIdSku[i];
        if (aIdSku[i] == idSku)
            document.getElementById(Div).style.display = "block";
        else
            document.getElementById(Div).style.display = "none";
    }
}

function TamanhoMaximo(campo, tammax, teclapres) {
    var tecla = teclapres.keyCode;
    var Origem = document.getElementById(campo);
    // Desconsidera o [tab] e o [shift+tab]
    if ((tecla != 9) && (tecla != 16))
        if (Origem.value.length >= tammax) {
        // Trunca o conteudo para o tamanho máximo, no caso de CTRL+V
        Origem.value = Origem.value.substring(0, tammax);
    }
}



criaBuscaPaginaProduto = function() {
    $('#btnBuscaPagina').click(function() {
        //$('#pesquisa-palavra').realizaBusca();
        var str = $.trim($('#pesquisa-palavra').val());
        if (str != "") {
            $('body').each(function() {
                $('body').removeHighlight();
                $.highlight(this, str.toUpperCase());
            });
        } else {
            $('body').removeHighlight();
        }
    });
}


/*
highlight v2
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>
*/

$(function() {
    jQuery.highlight = document.body.createTextRange ?

    /*
    Version for IE using TextRanges.
    */
  function(node, te) {
      var r = document.body.createTextRange();
      r.moveToElementText(node);
      for (var i = 0; r.findText(te); i++) {
          r.pasteHTML('<font class="wrap">' + r.text + '<\/font>');
          r.collapse(false);
      }
  }

 :

    /*
    (Complicated) version for Mozilla and Opera using span tags.
    */
  function(node, te) {
      var pos, skip, spannode, middlebit, endbit, middleclone;
      skip = 0;
      if (node.nodeType == 3) {
          pos = node.data.toUpperCase().indexOf(te);
          if (pos >= 0) {
              spannode = document.createElement('font');
              spannode.className = 'wrap';
              middlebit = node.splitText(pos);
              endbit = middlebit.splitText(te.length);
              middleclone = middlebit.cloneNode(true);
              spannode.appendChild(middleclone);
              middlebit.parentNode.replaceChild(spannode, middlebit);
              skip = 1;
          }
      }
      else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
          for (var i = 0; i < node.childNodes.length; ++i) {
              i += $.highlight(node.childNodes[i], te);
          }
      }
      return skip;
  }

 ;
});

jQuery.fn.removeHighlight = function() {
    this.find("font.wrap").each(function() {
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    });
    return this;
};

/* end highlight */


/* Avaliacao produto usuario */
jQuery.resetaEstrelas = function(selecionadoId, avaliacaoProdutoStars) {
    $.each(avaliacaoProdutoStars, function(a, obj) {
        $(obj).removeClass('savedRatingStar').removeClass('filledRatingStar').addClass('emptyRatingStar');
    });
    $.each(avaliacaoProdutoStars, function(a, obj) {
        $(obj).removeClass('emptyRatingStar').addClass('filledRatingStar');
        if ($(obj).attr('id') == selecionadoId) {
            var notaProduto = selecionadoId.substring(selecionadoId.lastIndexOf('_') + 1);
            $(obj).parent().attr('title', notaProduto);
            $(obj).parent().parent().find('#rtAvaliacao_RatingExtender_ClientState').val(notaProduto);
            return false;
        }
    });
}
jQuery.selecionaNotaAvaliacao = function(obj) {
    var selNota = $(obj).parent().find('#rtAvaliacao_RatingExtender_ClientState').val();
    var urlNota = $(obj).parent().find('#hdnUrlResenha').val();
    var urlLogin = $(obj).parent().find('#hdnUrlLogin').val();

    urlNota += "&CurrentRating=" + selNota;

    if (document.getElementById('hdnClient') != null) {
        urlNota += "&User=" + document.getElementById('hdnClient').value;
    }
    else {
        window.location = urlLogin;
    }

    $('#ctl00_Conteudo_Resenha1_pnlAResenhaOpiniao').load(urlNota, function(a, b) {
        defineAvaliacaoProduto();
    });
};
jQuery.resetaNotaOriginal = function(obj, orig, todas) {
    $.each(todas, function(a, obj) {
        $(obj).removeClass('filledRatingStar');
    });
    $.each(orig, function(a, obj) {
        $(obj).addClass('savedRatingStar');
    });
};
jQuery.fn.criaAvaliacaoProduto = function() {
    return this.each(function() {
        var avaliacaoProdutoStars = $(this).find('span');
        var avaliacaoNotaOriginal = $(this).find('span.savedRatingStar');
        $(this).find('span').unbind().mouseover(function() {
            $.resetaEstrelas(this.id, avaliacaoProdutoStars);
        });
        $(this).find('a').unbind().click(function() {
            $.selecionaNotaAvaliacao(this);
            $(this).unbind('mouseout');
            return false;
        }).mouseout(function() {
            $.resetaNotaOriginal(this, avaliacaoNotaOriginal, avaliacaoProdutoStars);
        });
    });
};
defineAvaliacaoProduto = function() {
    if (typeof (Sys) == 'undefined')
        return;

    if (typeof (Sys.WebForms) == 'undefined')
        return;

    $('#rating-avalie-wrapper').criaAvaliacaoProduto();
};
/* fim Avaliacao produto usuario */

tb_remove_pt = function() {
    $("#TB_imageOff", window.parent.document).unbind("click");
    $("#TB_closeWindowButton", window.parent.document).unbind("click");
    $("#TB_window", window.parent.document).fadeOut("fast", function() { $('#TB_window,#TB_overlay,#TB_HideSelect', window.parent.document).trigger("unload").unbind().remove(); });
    $("#TB_load", window.parent.document).remove();

    if ($.browser.msie && $.browser.version < 7) {//if IE 6

        $('body,html', window.parent.document).css({ height: "auto", width: "auto" });
        $('html', window.parent.document).css("overflow", "");
    }
    window.parent.document.onkeydown = "";
    window.parent.document.onkeyup = "";
    return false;
}
abreLinkParent = function() {
    //window.parent.location.reload();
    window.parent.location.href = this.href;
    return false;
}
abreLinkParentRefresh = function() {
    window.parent.location.reload();
    return false;
}

abreLinkExterno = function() {
    var newWin = window.parent.open(this.href, "_blank");
    if (newWin) {
        if (newWin.focus) {
            newWin.focus();
        }
        return false;
    }
    return true;
};
/*  corrige links das janelas de fechar, apenas se NAO for telerik  */
corrigeLinksJanelas = function() {
    $('body.popup a.btn-thickbox, body.popup input.btn-thickbox, body.popup button.btn-thickbox').unbind().click(tb_remove_pt);
    $('body.popup a.lnkParent').unbind().click(abreLinkParent);
    $('body.popup a.lnkParentRefresh').unbind().click(abreLinkParentRefresh);
    $('body.popup a.lnkExterno').unbind().click(abreLinkExterno);
    corrigePosicao();
};

/*  iguala Alturas prateleiras */
igualaAlturaItensTodos = function() {

    if (typeof (Sys) == 'undefined')
        return;

    if (typeof (Sys.WebForms) == 'undefined' || typeof (Sys.WebForms) == undefined)
        return;

    $('body.todas-categorias div.listas-categorias > div').equalHeightColumn();
    $('body.sku div.lista-comprar li').equalHeightColumn({ 'other': '#conteudo-central-produto div.lista-comprar div.maisImagensInner , #conteudo-central-produto div.lista-comprar  div.maisImagensWrapper' });
    $('body.sku #qvct div.lista-percentual li').equalHeightColumn({ 'other': '#qvct div.maisImagensInner , #qvct div.maisImagensWrapper' });
    $('body.sku #qcct div.lista-percentual li').equalHeightColumn({ 'other': '#qcct div.maisImagensInner , #qcct div.maisImagensWrapper' });
    $('body.sku #qvvt div.lista-percentual li').equalHeightColumn({ 'other': '#qvvt .maisImagensInner , #qvvt div.maisImagensWrapper' });
    $('body.checkout div.lista-tageado li').equalHeightColumn({ 'other': 'div.lista-tageado div.maisImagensInner , div.lista-tageado div.maisImagensWrapper' });
};

/*  plugin para igualar Altura dos itens selecionados. pode-se enviar tags adicionais para que fiquem com a mesma altura máxima  */
$.fn.equalHeightColumn = function(options) {
    var settings = $.extend({ 'other': false }, options);
    var maxHeight = 0;
    $(this).each(function(a, b) {
        var sz = $(b).height();
        maxHeight = (maxHeight < sz) ? sz : maxHeight;
    });
    $(this).each(function() {
        $(this).height(maxHeight);
    });
    if (settings.other != false) {
        $(settings.other).height(maxHeight);
    }
};


// Timer criado quando o metodo VaiParaMensagemErro e chamado. Esse timer chama
// apos dois segundos durante dez vezes este metodo para que ele possa observar se aconteceu algum erro. 
var timeoutVaiParaMensagemErro = null;
// Quantidade maximas de vezes que o metodo VaiParaMensagemErro e chamado.
var chamadasRestantes = 60;
//
// Metodo usado para posicionar a janela no quadro de mensagem de erro de um formulario.
// Como nao existe um evento de onerror para o validador, e necessario que este metodo
// observe por um tempo para verificar se algum erro foi gerado.
// Para que se possa dar tempo da classe 'erro' seja inserido nos campos com erro, este
// metodo configura um timer para que seja chamado durante um numero de vezes. 
//
VaiParaMensagemErro = function(idElement) {

    if ($("#" + idElement).css("display") != "none") {
        // nao pode fazer o scroll de primeira senao o scroll para cima feita pelo asp.net atrapalha.
        if (timeoutVaiParaMensagemErro == null) {
            // cria um timer para que o metodo possa esperar para que as classes de erro sejam geradas
            timeoutVaiParaMensagemErro = setTimeout("VaiParaMensagemErro('" + idElement + "')", 2000);
        }
        else {
            // obtem o offset (posicao) do elemento informado (sumario de mensagens de erro).
            //var offset = $("#" + idElement).offset();

            // faz a janela posicionar-se no elemento informado.
            //window.scrollTo(offset.left, (offset.top - 60));

            window.location.hash = idElement;

            clearTimeout(timeoutVaiParaMensagemErro);
            timeoutVaiParaMensagemErro = null;
        }
    }
    else {
        // se ainda nao foi configurado um timer para chamar este metodo automaticamente,..
        if (timeoutVaiParaMensagemErro == null) {
            // cria um timer para que o metodo possa esperar para que as classes de erro sejam geradas
            timeoutVaiParaMensagemErro = setTimeout("VaiParaMensagemErro('" + idElement + "')", 2000);
        }
        else {
            if (chamadasRestantes == 0) {
                // ja chamou este metodo o maximo de vezes (5 vezes)
                clearTimeout(timeoutVaiParaMensagemErro);
                timeoutVaiParaMensagemErro = null;
            }
            else {
                // decrementa o numero de chamadas restantes
                chamadasRestantes = chamadasRestantes - 1;
            }
        }
    }
}

/*
thickboxInit = function(){
if((typeof tb_init == 'function') && ($('body.popup').size() == 0) ){
tb_init('a.thickbox, area.thickbox, input.thickbox');
if(typeof imgLoader == 'undefined' && tb_pathToImage != 'undefined'){
imgLoader = new Image();
imgLoader.src = tb_pathToImage;
}
}
}
*/

definePopups = function() {
    $('.popextra').click(redefineLinksPopups);
    $('body.popup').load(function() { $('#TB_load').hide(); $('#TB_load', window.top.document).hide(); });
}

redefineLinksPopups = function() {
    var options, arrayOptions, tempSettings, tempOption, settings, strSettings, hWnd;
    options = $(this).attr('rel');
    tempSettings = {};
    if (options.length > 0) {
        arrayOptions = options.split('_');
        tempSettings = {};
        tempOption = [];
        for (var i = 0; i < arrayOptions.length; i++) {
            tempOption = arrayOptions[i].split('-');
            tempSettings[tempOption[0]] = tempOption[1];
        }
    }
    settings = $.extend({ 'width': 560, 'height': 400, 'resizable': 1, 'toolbar': 1, 'location': 1, 'directories': 1, 'status': 1, 'menubar': 0, 'scrollbars': 0 }, tempSettings);
    strSettings = '';
    for (var i in settings) {
        strSettings += i + '=' + settings[i] + ',';
    }
    strSettings = strSettings.substring(0, (strSettings.length - 1));
    hWnd = window.open(this.href, "PopWindowX", strSettings);
    if (hWnd) {
        hWnd.focus();
        return false;
    }
    return true;
};



function MostraImagemPrincipal(img, imgId, imgPrincipal) {
    imgId.src = imgPrincipal;
}

corrigePosicao = function() {
    var val = $('#rblDebitoParceladoFieldSet').find('input:checked').attr('value');
    var idListParcelas = "#listParcelas-" + val;
    $(idListParcelas).append($('#radioParcel'));
    MudaImagem
}



/* Manter no topo  */
if ((document.domain.indexOf('localhost') != -1) || (document.domain.indexOf('sandbox') != -1)) {
    dDominioSite = '/Site/';
} else {
    dDominioSite = '/';
}
$(document).ready(function() {
    initFullPage();
});

$(document).ajaxStop(function() {
    arrumaPrateleiras();
    igualaAlturaItensTodos();
});

function ResenhaOpiniao() {
    if (document.getElementById('hdnClient') != null) {
        return tb_show('', document.getElementById('hdnUrlResenhaOpiniao').value + '&KeepThis=true&TB_iframe=true&height=450&width=612', false); return false;
    }
    else {
        return document.location = document.getElementById('hdnUrlLogin').value;
    }
}
// CarrinhoMVC
function MostraImagemPrincipal(img, imgId, imgPrincipal) {
    imgId.src = imgPrincipal;
}

$().ready(function() {
    $('#ctl00_Conteudo_RegularExpressionValidator1').hide();
    $('#ctl00_Conteudo_CalcFreteBtn').click(function() {
        if (mascaraInteiro($('#ctl00_Conteudo_txtCep1').val())) {
            if (mascaraInteiro($('#ctl00_Conteudo_txtCep2').val())) {
                window.location.href = document.location.href + '/Frete/' + $('#ctl00_Conteudo_txtCep1').val() + $('#ctl00_Conteudo_txtCep2').val();
            }
        }
    });
    $('#ctl00_Conteudo_btnGravarValeCupom').click(function() {
        if ($('#ctl00_Conteudo_txtCupom').val() == "") {
            window.location.href = document.location.href + '/CupomVale/' + $('#ctl00_Conteudo_txtCupom').val();
        }
    });
});

function mascaraInteiro(texto) {
    var numeros = "0123456789";
    cont = 0;
    for (i = 0; i < texto.length; i++) {
        if (numeros.indexOf(texto.charAt(i), 0) != -1) {
            cont++;
        }
    }
    if (cont == texto.length)
        return true;
    $('#ctl00_Conteudo_RegularExpressionValidator1').show();
    event.returnValue = false;
    return false;
}

function OverPaleta(end) {
    var img = FindImage();
    img.src = end
}

function OutPaleta(end) {
    var img = FindImage();
    img.src = end;
}

function FindImage() {
    var aPai = document.getElementById("ctl00_Conteudo_lnkMain");
    for (var cont = 0; cont < aPai.childNodes.length; cont++) {
        if (aPai.childNodes[cont].nodeName == "IMG") {
            return aPai.childNodes[cont];
        }
    }
}

function SetSkuSelected(btn) {
    document.getElementById("ctl00_Conteudo_PaletaCores_SkuSelected").value = btn.title;
}

function confirmarCompra(modeloSku, linkCarrinho) {
    if (confirm('O Produto escolhido é ' + modeloSku + '. Colocar no carrinho?')) {
        if (window.parent == null) {
            window.location.href = linkCarrinho;
        } else {
            window.parent.location.href = linkCarrinho;
        }
    }
}

// Memoria de Navegacao nas Paginacoes de Vitrine
function GetAnchor(anchor) {
    var regex = new RegExp(anchor + "([0-9\-]+)");
    var match = regex.exec(window.location);
    return (match != null) ? match[1] : 1;
}

function RedirectPage(pageclickednumber) {
    var host = new String(window.location);
    if (host.indexOf("#PG=") != -1) {
        host = host.replace(new RegExp("#PG=[0-9]+"), "");
        host += '#PG=' + pageclickednumber;
    }
    else {
        host = window.location + '#PG=' + pageclickednumber;
    }

    // No momento do .load na div ResultItems a referencia aos js usados pelo botao espiar estavam sendo perdidos
    $.getScript("/Scripts/jquery.livequery.min.js");
    $.getScript("/Scripts/prettyPhoto/js/jquery.prettyPhoto.js");
    $.getScript("/Scripts/prettyPhoto/js/lean-prettyPhoto.js"); 

    window.location = host;
}

function GoToTopPage() 
{
    $("html,body").animate({ scrollTop: $('.main').offset().top }, "slow");
}

