Calculateur LPV

 avatar
unknown
javascript
4 months ago
28 kB
6
Indexable
var calculateurpgvg = [
        {base: 3361, booster: 6044, visuel: "70/30", dosage: 0.8},
        {base: 3216, booster: 4453, visuel: "50/50", dosage: 1},
        {base: 3360, booster: 5229, visuel: "30/70", dosage: 1.33333333333333},
        {base: 7681, booster: 3188, visuel: "20/80", dosage: 1.46666666666667},
        {base: 4336, booster: 6045, visuel: "0/100", dosage: 1.66666666666666}
    ],
    calculateurtauxpg,
    keypressed;

function getCSS(href){
    var el = document.createElement('link');
    el.rel = 'stylesheet'; el.type = 'text/css'; el.href = href;
    document.getElementsByTagName('head')[0].appendChild(el);
}

function CalculateurArome(el){
    var _ = this, app = _;
    _.el = $(el);
    var xhr, lastEdit, tm_resize,
        touchmove = false,
        $htmlLiquide = _.el.find('.liquide'),
        $htmlBase = _.el.find('.qtt-base input'),
        $htmlBooster = _.el.find('.qtt-booster label > span'),
        $htmlArome = _.el.find('.qtt-arome input'),
        $nicotines = _.el.find('.nicotine'),
        $formPGVG = $('#calc-arome-tx-pgvg'),
        $w = $(window),
        Marque = new function(){
            var _ = this;
            _.result = app.el.find('.result-marque');
            _.input = _.result.siblings('.label-custom').find('input');
            _.label = _.input.closest('label');
            _.hideChildren = function(){
                _.input.val('');
                return _.result.removeClass('active').children(':not(.element-selected)').hide();
            }
            _.showChildren = function(request){
                var filter = '';
                if(request){
                    var keys = Object.keys(request);
                    for(var i in keys){
                        var key = keys[i];
                        filter += '[data-'+key+'"'+stringalize(request[key])+'"]';
                    }
                    _.result.children().hide();
                }
                return _.result.addClass('active').children(filter).show();
            }
            _.isFull = function(){
                return _.result.children().length > 1;
            }
            _.reset = function(){
                _.result.removeClass('marque-select').find('.element-selected').removeClass('element-selected');
                _.hideChildren();
            }
            _.select = function($this){
                $this.addClass('element-selected').siblings().hide();
                _.result.addClass('marque-select').removeClass('active');
                _.input.val('');
                xhr && xhr.readyState != 4 && xhr.abort();
                xhr = Product.load({
                    type: "produit",
                    id_category: $this.data('id-marque')
                });
                xhr.done(function(){
                    Product.input.focus();
                });
            }
            _.isSelected = function(){
                return _.result.is('.marque-select');
            }
            _.getElement = function(row){
                return '<div class="element" data-name="'+stringalize(row.name)+'" data-id-marque="' + row.id + '"><span>' + row.name + '</span></div>';
            }
            _.load = function(request, cb){
                return $.post(CalculateurAromeUrl, request, function (data) {
                    var html = '';
                    if (data.success)
                        $.each(data.data, function (i, row) {
                            html += _.getElement(row);
                        });
                    else
                        html += "<div class='element no-result'><span>" + data.data + "</span></div>";
                    Marque.result.html(html).addClass('active');
                    typeof cb == 'function' && cb();
                },'json');
            }
        },
        Product = new function(){
            var _ = this;
            _.result = app.el.find('.searchResults');
            _.input = app.el.find('#calcInputSearch');
            _.label = _.input.closest('label');
            _.min_length =  _.input.data('minlength');
            _.grid;
            _.reset = function(){
                _.result.removeClass('produit-select').removeClass('active').html('');
                _.label.removeClass('selected');
                _.input.val('');
                if(!document.getElementById('pro-menu'))
                    Recommandations.recommandations.removeClass('display');
            }
            _.select = function($this){
                $this = $this instanceof jQuery ? $this : $($this);
                $this.addClass('element-selected').siblings().hide();
                _.result.addClass('produit-select').removeClass('active');
                _.label.addClass('selected');
                var vignette_data = ProductVignette.getDatas($this[0]);
                app.el.find('.temps-maturation .result').text(vignette_data.maturation);
                _.input.val($this.find('h2 a').text().trim());
                if (!Marque.isSelected()){
                    if (Marque.showChildren({'id-marque=': vignette_data.id_marque}).addClass('element-selected').length === 0){
                        xhr && xhr.readyState != 4 && xhr.abort();
                        xhr = Marque.load({
                            type: 'marque'
                        });
                        xhr.done(function(){
                            Marque.showChildren({'id-marque=': vignette_data.id_marque}).addClass('element-selected');
                            Marque.result.addClass('marque-select').removeClass('active');
                        });
                    } else {
                        Marque.result.addClass('marque-select').removeClass('active');
                    }
                }
                if(!document.getElementById('pro-menu')){
                    Recommandations.arome.products.html($this);
                    Recommandations.arome.unite = vignette_data.contenance;
                    Recommandations.recommandations.addClass('display');
                }
            }
            _.load = function(request, cb){
                function productListInition(){
                    var pl = _.result.find('.product-list-container'),
                        p = pl.length && window.productLists && productLists.set('calcSearchResult', pl[0]);
                    if(!p) return;
                    new ProductVignetteList_Filter(p);
                    p.filter.exec({searchText:document.getElementById('calcInputSearch').value});
                    p.clickable = false;
                    return p;
                }
                return $.post(CalculateurAromeUrl, request, function (data) {
                    _.result.addClass('active').html(data);
                    productListInition();
                });
            }
            _.toggleDescription = function(el){
                $(el).closest('div.item').find('p.description_suite').toggleClass('active');
                return false;
            };
        },
        Recommandations = new function(){
            var _ = this, reco = _;
            _.recommandations = app.el.find('.recommandations');
            _.achat_total = app.el.find('#buy_btn');

            function Composant(type, unite){
                if(!window.ProductVignetteActionsOBJ)
                    ProductVignetteActionsOBJ = new ProductVignetteActions({});
                var _ = this,
                    pv_act = ProductVignetteActionsOBJ,
                    origin = Object.assign(Object.create(Object.getPrototypeOf(pv_act)), pv_act);

                _.inRecommandations = function (vignette) {
                    return vignette.closest('.recommandations').length > 0;
                };
                pv_act.findCombination = function (vignette) {
                    if (!_.inRecommandations(vignette))
                        return origin.findCombination(vignette);
                    else
                        return vignette.data('id-product-attribute');
                };
                pv_act.findProductQtt = function (vignette) {
                    if (!_.inRecommandations(vignette))
                        return origin.findProductQtt(vignette);
                    else
                        return vignette.data('quantity');
                };
                pv_act.resetVignetteForm = function (vignette) {
                    if (!_.inRecommandations(vignette))
                        return origin.resetVignetteForm(vignette);
                };
                pv_act.displayAlert = function (vignette, message, is_error) {
                    if (!_.inRecommandations(vignette))
                        return origin.displayAlert(vignette, message, is_error);
                    else
                        sweetalert('<div class="error">'+ _.type + ' : ' + message + '</div>');
                };
                _.type = type;
                _.unite = unite;
                _.el =  reco.recommandations.find('.'+ _.type);
                _.products = _.el.find('.vignettes-produits');
                _.recap = _.el.find('.recap');
                _.nb = _.el.find('.nb');
                _.vignette = _.el.find('.vignette');
                _.utilise =  _.vignette.find('.utilise .volume');
                _.restant =  _.vignette.find('.restant .volume');
                _.prix = _.vignette.find('.prix');
                _.img =  _.vignette.find('img');
                _.buy_button =  _.vignette.find('.btn-buy');
                _.refresh = function(value){
                    if (_.type === 'booster'){
                        _.unite = (calculateurpgvg[calculateurtauxpg].booster === 3188)? 10 : 100;
                    }
                    var nb = Math.ceil(value / _.unite),
                        restant = keep1decimal(nb * _.unite - value);

                    if (nb == 0){
                        _.el.addClass('hidden');
                        _.vignette.data('quantity', nb);
                        return 0;
                    } else {
                        _.el.removeClass('hidden');
                        _.nb.html(nb * ((_.type === 'booster')? _.unite / 10 : 1) +  'X ');
                        if (_.type === 'arome'){
                            _.recap.html(_.recap.data('text').replace('%s', _.unite));
                            _.produit = _.products.find('.element-selected');
                            _.product_id = _.produit.data('id');
                        } else {
                            _.product_id = (_.type === 'base')? calculateurpgvg[calculateurtauxpg].base : calculateurpgvg[calculateurtauxpg].booster;
                            _.produit = _.products.find('.vignette-produit[data-id='+_.product_id+']');
                        }
                        if (_.product_id == undefined){
                            return 0;
                        }
                        var matchesControl = _.produit.is('.vignette-produit')? '.vignette-produit' : ProductVignette.itemClass,
                            v = new ProductVignette({element:_.produit[0], matchesControl}),
                            c = v.attribute && v.attribute.getCombination(),
                            produit_data = v.getDatas && v.getDatas(_.produit[0]),
                            price = _.produit.data('price') || produit_data.price,
                            img_large = _.produit.data('img-large') || produit_data.image_large,
                            id_product_attribute = _.produit.data('id-product-attribute') || (c && c.id_product_attribute);
                        _.utilise.html(value.toString().replace('.',',') + ' ML');
                        _.restant.html(restant.toString().replace('.',',') + ' ML');
                        _.prix.html(formatPrice(price * nb));
                        // _.img.attr('src', _.produit.find('img').attr('src'));
                        _.img.attr('src', img_large);
                        _.vignette.find('.text-unavailable').remove();
                        var unavailable = _.produit.find('.text-unavailable');
                        var isUnavailable = unavailable.text().length > 0;
                        if (isUnavailable) {
                            unavailable.clone().appendTo(_.vignette);
                            _.buy_button.removeClass('btn-orange').addClass('btn-gris');
                        } else {
                            _.buy_button.addClass('btn-orange');
                            _.buy_button.removeClass('btn-gris');
                            _.vignette.data('id', _.product_id)
                             .data('id-product-attribute', id_product_attribute || 0)
                             .data('quantity', nb);
                        }

                        return isUnavailable ? 0 : price * nb;
                    }
                }
                _.addToCart = function () {
                    if (_.vignette.data('quantity') > 0 && _.buy_button.hasClass('btn-orange')){
                        // pv_act.fetchProduct(_.vignette.data('id'), _.vignette);
                        // pv_act.buyProduct(_.vignette);
                        new Cart().add.product(_.vignette.data('id'), _.vignette.data('id-product-attribute'), _.vignette.data('quantity'))
                    }
                };

                (function init() {
                    _.el.on('click', '.btn-buy', _.addToCart);
                })();
            }
            _.refresh = function (base, booster, arome){
                var basePrice  = _.base.refresh(base),
                    boosterPrice = _.booster.refresh(booster),
                    aromePrice = _.arome.refresh(arome),
                    totalPrice = basePrice + boosterPrice + aromePrice;

                if (_.recommandations.find('.produit:not(.hidden) .vignette .btn-orange').length > 1){
                    _.achat_total.find('#prix_total').html(formatPrice(totalPrice));
                    _.achat_total.parent('.buy_btn_container').removeClass('hidden');
                } else {
                    _.achat_total.parent('.buy_btn_container').addClass('hidden');
                }

            };
            _.addProductsToCart = function () {
                _.base.addToCart();
                _.booster.addToCart();
                _.arome.addToCart();
            };
            function init(){
                _.base = new Composant('base', 1000);
                _.booster = new Composant('booster', 100);
                _.arome = new Composant('arome', 10);
                _.recommandations.on('click', '#buy_btn', _.addProductsToCart);
            };
            if(!document.getElementById('pro-menu'))
                init();
        };

    function stringalize(str){
        return str.toString().toLowerCase().replace(/[^0-9a-z]/g,'');
    }
    function getNicotine(nicoMax){

        var $sel = $nicotines.filter('.selected'), rs = 0;
        if($sel.is('.btn-input')){

            rs = parseFloat($sel.find('input').val().replace(',','.'));
            if (rs >= keep1decimal(nicoMax)){
                rs = nicoMax;
                $sel.find('input').val(keep1decimal(nicoMax));
            } else if ($sel.find('input').val() < 0){
                rs = 0;
                $sel.find('input').val(0);
            }
        }else{
            rs = parseFloat($sel.attr("data-taux-nicotine"));
        }
        return rs;
    }
    function keep1decimal(num){
        return Math.round(parseFloat(num) * 10) / 10;
    }
    function formatPrice(price) {
        return new Intl.NumberFormat('fr-FR', {
            style: 'currency',
            currency: 'EUR'
        }).format(price);
    }
    _.resize = function(){
        var w = _.el.width();
        if(w < 375) {
            _.el.addClass('md sm xs');
        }
        if(w < 560) {
            _.el.addClass('md sm').removeClass('xs');
        }
        else if(w < 800) {
            _.el.addClass('md').removeClass('sm xs');
        }
        else {
            _.el.removeClass('lg md sm xs');
        }
        return true;
    };
    _.exec = function(e) {
        // console.log(e.currentTarget.value, e.target.value);
        var $selection = Recommandations.arome && Recommandations.arome.products.find('.item.element-selected'),
            vignette_data = $selection && ProductVignette.getDatas($selection[0]),
            nicotineBooster = 20,
            booster = parseFloat($htmlBooster.text().replace(',','.')),
            base = parseFloat($htmlBase.val()),
            arome = parseFloat($htmlArome.val()),
            liquide = parseFloat($htmlLiquide.val()),
            pgvg = parseFloat(calculateurpgvg[calculateurtauxpg].dosage),
            concentration = pgvg * (!Recommandations.arome ? 12 : (parseFloat(vignette_data.concentration) || 12));

        if (concentration < 0)
            concentration = 0;

        var nicoMax = nicotineBooster * (1 - concentration / 100),
            nicotine = getNicotine(nicoMax);

        if(this.dataset && this.dataset.edit){
            lastEdit = this.dataset.edit;
        }
        else{
            lastEdit = lastEdit || 'liquide';
        }

        switch (lastEdit){
            case 'liquide':
                arome = liquide * (concentration / 100);
                booster = (liquide * nicotine) / nicotineBooster;
                base = liquide - (booster + arome);
                if(base<0){
                    base = 0;
                }

                break;
            case 'nicotine':
                arome = liquide * (concentration / 100);

                booster = (liquide * nicotine) / nicotineBooster;
                base = liquide - (booster + arome);
                if(base<0){
                    base = 0;
                }
                break;
            case 'base':
                var coefLiquide =( 1/(1-concentration/100))/
                    (1-(nicotine/nicotineBooster)-((nicotine*(concentration/100))/(nicotineBooster*(1-concentration/100))));

                if (coefLiquide < 0 || coefLiquide == Infinity || nicotine >= keep1decimal(nicoMax) || base <= 0){
                    base = 0;
                }
                // if (coefLiquide > 0 && coefLiquide != Infinity && nicotine < keep1decimal(nicoMax) && base > 0){
                if  (base > 0){
                    liquide = coefLiquide * base;
                }
                booster = (liquide * nicotine) / nicotineBooster;
                arome = liquide * (concentration / 100);
                // base = liquide - (booster + arome);


                break;
            case 'arome':
                liquide = arome / (concentration / 100);
                booster = (liquide * nicotine) / nicotineBooster;
                base = liquide - (booster + arome);

                if(base < 0){
                    base = 0;
                }

                break;
        }
        liquide = keep1decimal(liquide);
        $htmlLiquide.val(liquide);
        base = keep1decimal(base);
        $htmlBase.val(base);
        arome = keep1decimal(arome);
        $htmlArome.val(keep1decimal(arome));
        booster = keep1decimal(booster);
        $htmlBooster.html(booster.toString().replace('.',','));

        var tx_pg = calculateurpgvg[calculateurtauxpg].visuel;
        _.el.find('.recap[data-txt]').each(function(){
            var $this = $(this);
            $this.html($this.data('txt').replace('%s',tx_pg))
        });
        _.el.find('.bottle-base i').html(tx_pg);

        if(!document.getElementById('pro-menu'))
            Recommandations.refresh(base, booster, arome);

    };

    (function init(){
        //pour la popup
        var popup = $('#popup-calculateur-arome');
        if (popup.length > 0){
            popup_item = popup.find('.searchResults .item');
            if (popup_item.length > 0){
                Product.select(popup_item.first());
            }
        }

        $('#hide-calculateur-arome').on('click', function () {
            _.el.addClass('hidden');
            document.getElementsByTagName('body')[0].classList.remove('noscroll');
        });

        _.el
            .on('keydown', 'input', function(e){
                keypressed = e.keyCode == 188 || e.keyCode == 110 || e.keyCode == 190;
            })
            .on('input','input',function(e){
                var time = 0;
                if (this.type === 'number' && keypressed){
                    time = 1000;
                }
                setTimeout(() => {
                    _.exec.apply(this);
                }, time);
            })
            .on('touchmove', '.element, .item', function () {
                touchmove = true;
            });

        $formPGVG.on('change','input', function() {
            calculateurtauxpg = parseInt(this.value);
            $(this).closest('label').addClass('active').siblings('.active').removeClass('active');
            _.exec.apply(this);
        }).find('input:checked').trigger('change');

        $nicotines.on('click touchend', function () {
            var $this = $(this);
            $this.addClass("selected").siblings('.selected').removeClass("selected");
            if($this.is('.btn-input')){
                $this.find('input').val('').focus();
            }else{
                _.exec.apply(this);
            }
        });

        Marque.input
            .on('blur', function (e) {
                if(!$('.result-marque').is(e.relatedTarget)) {
                    setTimeout(function(){
                        Marque.hideChildren();
                        Product.input.focus();
                    },111);

                }
            })
            .on('focus input', function (e) {
                if (Product.label.hasClass('selected')){
                    Product.reset();
                }
                if(Marque.isFull()){
                    var rs = this.value ? {'name*=':this.value} : null
                    Marque.showChildren(rs);
                } else{
                    xhr && xhr.readyState != 4 && xhr.abort();
                    xhr = Marque.load({
                        type: 'marque',
                        search: this.value
                    });
                }
            });
        Marque.result
            .on('click touchend', '.element:not(.no-result, .element-selected)', function () {
                if (touchmove) {
                    touchmove = false;
                    return;
                }
                Marque.select($(this));
            })
            .on('click touchend', '.element-selected', function () {
                if (touchmove) {
                    touchmove = false;
                    return;
                }
                Marque.reset($(this));
                Marque.input.focus();
            });

        Product.input
            .on('focus input', function(e){
                if (!Product.label.hasClass('selected') &&
                    (e.target.value.length > Product.min_length || Marque.isSelected())) {
                    Marque.hideChildren();
                    if (Marque.isSelected()){
                        var p = productLists.get('calcSearchResult');
                        p && e.target.value && p.filter.exec({searchText:e.target.value});
                    } else {
                        xhr && xhr.readyState != 4 && xhr.abort();
                        xhr = Product.load({
                            type: "produit",
                            search: this.value,
                            min_length: Product.min_length,
                            id_category: Marque.result.find('.element-selected').data('id-marque')
                        });
                    }
                } else {
                    Product.result.removeClass('active');
                }
            });
        Product.result
            .on('click', '.btn-close',function(e){
                e && e.preventDefault();
                if (Marque.isSelected()){
                    Marque.reset();
                }
                Product.reset();
                Product.input.focus();
            })
            .on('click touchleave', '.item:not(.no-result, .element-selected)', function (e) {
                if (touchmove) {
                    touchmove = false;
                    return;
                }
                if(e.target.matches('.short-description-link') || e.target.closest('.short-description'))
                    Product.toggleDescription(e.target);
                else {
                    Product.select(ProductVignette.get(e.target));
                    _.exec();
                }
            });
        Product.label
               .on('click touchleave', function (){
                   if (Product.label.hasClass('selected')){
                       if (touchmove){
                           touchmove = false;
                           return;
                       }
                       if (Marque.isSelected()){
                           Marque.reset();
                       }
                       Product.reset();
                       Product.input.focus();
                   }
               });

        $w.on('resize',function(){
            tm_resize && clearTimeout(tm_resize);
            tm_resize = setTimeout(_.resize,11);
        })

        $.when(_.resize()).done(function(){
            var accessories = $('#popup-calculateur-arome .accessories_block ul.product-list-container');
            if (accessories.length > 0){
                accessories.slick({
                    slidesToShow: 4,
                    slidesToScroll: 4,
                    infinite: true,
                    responsive: [{
                        breakpoint: 1100,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 3
                        }
                    },{
                        breakpoint: 1025,
                        settings: {
                            slidesToShow: 4,
                            slidesToScroll: 4
                        }
                    }, {
                        breakpoint: 860,
                        settings: {
                            slidesToShow: 3,
                            slidesToScroll: 3
                        }
                    }, {
                        breakpoint: 650,
                        settings: {
                            slidesToShow: 2,
                            slidesToScroll: 2
                        }
                    }]
                });
            }
        });
    })();
}

function lunchCalculateurArome(){
    if(!window.ProductVignetteActions) {
        return setTimeout(lunchCalculateurArome, 11);
    }
    var el = document.getElementById('popup-calculateur-arome');
    window.calculateurArome = new CalculateurArome(el);
}

if(isDocReady()) lunchCalculateurArome();
else document.addEventListener("DOMContentLoaded", e => {
    lunchCalculateurArome();
});
Editor is loading...
Leave a Comment