PageSourceSearch

https://www.bahroma1.ru/templates/bahroma1/js/minicart.js?1790245275

js bahroma1.ru collected 2026-09-24 10:49:01 UTC 83,240 bytes, 1,972 lines download raw bytes

1// function checkingCartItems() {
2//
3//     console.log('checkingCartItems');
4//     // проверка актуальности цен и исправление
5//
6//     //
7//     //simpleCart.items()[0].set('price', 1000); simpleCart.items()[0].set('price1', 1000); simpleCart.items()[0].set('baseprice', 1000); simpleCart.update();
8//
9//
10//     const items = $.map(simpleCart.items(), function (item, index) {
11//         return item.get('uid2') || item.get('uid');
12//     });
13//
14//     if (items.length) {
15//
16//         $.ajax({
17//             type: "POST",
18//             data: {
19//                 items: items
20//             },
21//             url: "/script/check_items.php",
22//             success: function (activeItems) {
23//                 let needUpdate = false;
24//                 simpleCart.each(function (item) {
25//                     uid = parseInt(item.get('uid2') || item.get('uid'));
26//
27//                     // проверка товара на актуальность
28//                     if (activeItems.indexOf(uid) == -1 && uid != 12064 && uid != 12112 && uid != 12065 && uid != 12066 && !item.get('deprecated') && item.get('category') != 3284) {
29//                         item.remove();
30//                         // item.set('deprecated', 1);
31//                         // item.set('uid', 10000000);
32//                         // item.set('uid2', 10000000);
33//                         // item.set('price', 0);
34//                         needUpdate = true;
35//                     }
36//                 });
37//                 if (needUpdate) {
38//                     simpleCart.update();
39//                 }
40//             }
41//         });
42//
43//         $.ajax({
44//             type: "POST",
45//             data: {
46//                 items: items
47//             },
48//             url: "/script/update_items.php",
49//             success: function (res) {
50//                 let needUpdate = false;
51//                 // справочник uid и цена
52//                 itemsWithPrice = JSON.parse(res);
53//
54//                 // проверка актуальности цены для товаров в корзине
55//                 $.each(itemsWithPrice, function (index, itemWithPrice) {
56//                     // товар в корзине
57//                     const cartItem = simpleCart.find({uid: itemWithPrice[0].toString()});
58//                     if (cartItem.length) {
59//                         if (cartItem[0].get('price_updated') == 1) console.log(cartItem[0].get('price_updated'));
60//                         // baseprice товара в корзине отличается от прайса справочника
61//                         if (parseInt(cartItem[0].get('baseprice')) != itemWithPrice[1]) {
62//                             cartItem[0].set('baseprice', itemWithPrice[1]);
63//                             cartItem[0].set('price1', itemWithPrice[1]);
64//                             cartItem[0].price(itemWithPrice[1]);
65//                             //cartItem[0].set('price_updated', 1);
66//                             needUpdate = true;
67//                         }
68//                     }
69//                 });
70//                 if (needUpdate) {
71//                     simpleCart.update();
72//                 }
73//             }
74//         });
75//
76//     }
77// }
78//
79
80const PaidDeliveryUid = '18022';
81const deliveryUid2 = 18022;
82
83
84function checkTotalSum() {
85    let totalSum = 0;
86    simpleCart.each(function (item) {
87        if (!item.get('mse')) totalSum += (item.get('price') * item.get('quantity'));
88    });
89
90    if (typeof minPrice !== 'undefined' && minPrice > 0) {
91        if (totalSum < minPrice && $("input#delivery:checked").length) {
92            $('#cartSubmit1btn').addClass('disabled');
93            const buttonText = 'Добавьте товаров на ' + String(minPrice - totalSum) + ' руб';
94            $('#cartSubmit1btn').val(buttonText);
95        } else {
96            const defaultText = 'Оформить заказ';
97            $('#cartSubmit1btn').val(defaultText);
98            $('#cartSubmit1btn').removeClass('disabled');
99        }
100    } else {
101        const defaultText = 'Оформить заказ';
102        $('#cartSubmit1btn').val(defaultText);
103    }
104}
105
106
107function checkingCartItems() {
108
109    console.log('checkingCartItems');
110    // проверка актуальности цен
111    // simpleCart.items()[0].set('price', 1000); simpleCart.items()[0].set('price1', 1000); simpleCart.items()[0].set('baseprice', 1000);
111 simpleCart.update();
112
113    const items = $.map(simpleCart.items(), function (item, index) {
114        return item.get('uid2') || item.get('uid');
115    });
116
117    if (items.length) {
118        $.ajax({
119            type: "POST",
120            data: {
121                items: items
122            },
123            url: "/script/cartitems/check_update.php",
124            success: function (activeItems) {
125                let needUpdate = false;
126                // справочник uid и цена
127                itemsWithPrice = JSON.parse(activeItems);
128                // товары в корзине
129                simpleCart.each(function (cart_item) {
130                    let foundCartItem = false
131
132                    $.each(itemsWithPrice, function (actual_index, item_) {
133                        if (item_[0] == cart_item.get('uid')) foundCartItem = item_
134                        if (item_[0] == cart_item.get('uid2')) foundCartItem = item_
135                    })
136
137                    if (foundCartItem) {
138                        let cartItem = simpleCart.find({uid: foundCartItem[0].toString()});
139                        if (cartItem.length) {
140                            if (parseInt(cartItem[0].get('baseprice')) != foundCartItem[1]) {
141                                cartItem[0].set('baseprice', foundCartItem[1]);
142                                cartItem[0].set('price1', foundCartItem[1]);
143                                cartItem[0].price(foundCartItem[1]);
144                                needUpdate = true;
145                            }
146                        }
147                    } else {
148                        uid = parseInt(cart_item.get('uid2') || cart_item.get('uid'));
149                        if (cart_item.get('category') != 3284 && uid != 18022) {
150                            console.log("removing item", cart_item);
151                            cart_item.remove();
152                            needUpdate = true;
153                        }
154
155                    }
156                });
157                if (needUpdate) {
158                    simpleCart.update();
159                }
160            }
161        });
162    }
163}
164
165
166$(function () {
167
168    window.cartLangVars = {
169        rus: {
170            cart_currency: ' Р',
171            cart_empty: 'Ваша корзина пока пуста, для выбора товаров перейдите в каталог товаров',
172            cart_empty_menu_button_label: 'Перейти в меню',
173            cart_empty_menu_button_link: '/menu.html',
174            cart_label_name: 'Наименование',
175            cart_label_calories: 'Калорийность',
176            cart_label_quantity: 'Количество',
177            cart_label_sum: 'Сумма',
178            cart_label_2nd_item: 'За второе блюдо',
179            cart_label_unit: 'шт',
180            cart_discount_title: 'Скидка',
181            cart_payment_courier_cash_label: 'Наличными курьеру',
182            cart_payment_courier_card_label: 'Оплата картой курьеру',
183            cart_payment_restaurant_cash_label: 'Наличными в ресторане',
184            cart_payment_restaurant_card_label: 'Оплата картой в ресторане'
185
186        },
187        lv_rus: {
188            cart_currency: ' €',
189            cart_empty: 'Ваша корзина пока пуста, для выбора товаров перейдите в каталог товаров',
190            cart_empty_menu_button_label: 'Перейти в меню',
191            cart_empty_menu_button_link: '/ru/menu.html',
192            cart_label_name: 'Наименование',
193            cart_label_calories: 'Калорийность',
194            cart_label_quantity: 'Количество',
195            cart_label_sum: 'Сумма',
196            cart_label_2nd_item: 'За второе блюдо',
197            cart_label_unit: 'шт',
198            cart_discount_title: 'Скидка',
199            cart_payment_courier_cash_label: 'Наличными курьеру',
200            cart_payment_courier_card_label: 'Оплата картой курьеру',
201            cart_payment_restaurant_cash_label: 'Наличными в ресторане',
202            cart_payment_restaurant_card_label: 'Оплата картой в ресторане'
203
204
205        },
206        lat: {
207            cart_currency: ' €',
208            cart_empty: 'Jūsu grozā nav ēdienu',
209            cart_empty_menu_button_label: 'Atveriet izvēlni',
210            cart_empty_menu_button_link: '/menu.html',
211            cart_label_name: 'Nosaukums',
212            cart_label_calories: 'Kaloriju daudzums',
213            cart_label_quantity: 'Daudzums',
214            cart_label_sum: 'Summa',
215            cart_label_2nd_item: 'Par Otro ēdienu',
216            cart_label_unit: 'gb',
217            cart_discount_title: 'Atlaide',
218            cart_payment_courier_cash_label: 'skaidrā naudā',
219            cart_payment_courier_card_label: 'ar karti',
220            cart_payment_restaurant_cash_label: 'skaidrā naudā restorānā',
221            cart_payment_restaurant_card_label: 'ar karti restorānā'
222
223
224        }
225    };
226
227    var lang = window.lang || 'rus';
228
229    var cart = simpleCart;
230
231    window.mobilesite = !!document.location.href.match(/spisok-product_mobile|cart_mobile.php/);
232
233    //if (!document.location.href.match(/eq5/)) $("label[for='radio578']").remove();
234
235
236    // $('#datepicker7kg').datepicker({
237    //     onSelect: function(dateText) {
238    //         // 31.12.2025
239    //         if (dateText === "31.12.2025") {
240    //             $('#7kgtime option[value="18"]').prop('disabled', true);
241    //             $('#7kgtime option[value="21"]').prop('disabled', true);
242    //         } else {
243    //             $('#7kgtime option[value="18"]').prop('disabled', false);
244    //             $('#7kgtime option[value="21"]').prop('disabled', false);
245    //         }
246    //     }
247    // });
248
249    $.fn.toggleClick = function () {
250        var methods = arguments, // store the passed arguments for future reference
251            count = methods.length; // cache the number of methods
252        //use return this to maintain jQuery chainability
253        return this.each(function (i, item) {
254            // for each element you bind to
255            var index = 0; // create a local counter for that element
256            $(item).click(function () { // bind a click handler to that element
257                return methods[index++ % count].apply(this, arguments); // that when called will apply the 'index'th method to that element
258                // the index % count means that we constrain our iterator between 0 and (count-1)
259            });
260        });
261    };
262
263    $.get("/js/jquery.mousewheel.js", function () {
264        $(window).mousewheel(function (event, delta) {
265            if (window.isOverP) {
266                $("div.simpleCart_items").scrollTop(parseFloat($("div.simpleCart_items").scrollTop()) - delta * 20);
267                return false;
268            }
269        });
270    });
271
272    $(".cartInfo").addClass('closed');
273    $(document).on("click", ".cartInfo", function () {
274        if (simpleCart.items().length) {
275            if ($(this).hasClass('closed')) {
276                $("#cartPopover").slideDown(200);
277                //                $("#cartPopover").fadeIn(500);
278                $(".cartInfo").removeClass('closed').addClass('open');
279            } else {
280                $("#cartPopover").slideUp(200);
281                $(".cartInfo").removeClass('open').addClass('closed');
282            }
283        }
284    });
285
286
287    /*
288
289    $(".cart2").bind({
290        'mouseenter': function () {
291            $("#cartPopover").slideDown(10);
292            $(".cartInfo").removeClass('closed').addClass('open');
293            window.isOverP = 1;
294            $("body").addClass("noscroll2");
295
296        },
297        'mouseleave': function () {
298            $("#cartPopover").slideUp(10);
299            $(".cartInfo").removeClass('open').addClass('closed');
300            window.isOverP = 0;
301            $("body").removeClass("noscroll2");
302
303        }
304    });
305
306    */
307
308
309    function updatePanel() {
310        if ($(".order__table-footer").length && $(".panel-fixed").length) {
311            o1 = $(".order__table-footer").eq(0).offset()['top'];
312            wt = $(window).scrollTop();
313            ////console.log('o1', o1, 'wt', wt);
314            visible = !isElementInViewport($(".order__table-footer")[0]);
315            if (wt > o1 - 50) visible = false;
316            $(".panel-fixed").toggleClass('panel-fixed--vis', visible);
317
318        }
319    }
320
321    $(window).scroll(function () {
322        ////console.log('elem in viewport', isElementInViewport($(".order__table-footer")[0]));
323
324        updatePanel();
325    });
326
327    function isElementInViewport(el) {
328        var rect = el.getBoundingClientRect();
329
330        return rect.bottom > 0 &&
331            rect.right > 0 &&
332            rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
333            rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
334    }
335
336    if (document.location.href.match(/order.php|cartNewPromocodes|cart.html|cart.php|order3|cart1489.html|cart1489.html|cart1490.html|cart_mobile.php|orde111r.php|page_1481656785_3105.html|page14773196594259.php/
336)) {
337        cart({
338            cartColumns: [{
339                attr: "image",
340                label: false,
341                view: function (item, column) {
342                    if (item.get('composite')) return false;
343                    if (!item.get('href')) item.set('href', '#');
344                    return document.location.href.match(/cart_mobile.php/) ? (item.get('image') ? '<span class="img-box"><span class="img-cont"><span><img src="' + item.get('image') + '" alt=""></span></span></span><span class="rubr"></span>' : '') : (item.get('image') ? '<a class="link-img cat-item cboxElement1" href="' + item.get('href').replace("popup", "product") + '"><span class="img-box"><span class="img-cont"><span><img src="' + item.get('image') + '" alt=""></span></span></span><span class="rubr"></span></a>' : '');
345                }
346            }, {
347                view: function (item, column) {
348
349                    toppings_text = '';
350                    if (item.get('toppings')) {
351                        toppings_text = item.get('toppings').map(function (e, index) {
352                            return e['quantity'] + ' ' + e['name'];
353                        }).join("<br>");
354                    }
355
356                    name = (item.get('name_html') || item.get('name'));
357
358                    // типы получения для товара (delivery pickup)
359                    const delivery_types = item.get('delivery_types')
360                    let delivery_types_html = ''
361                    // let delivery_types = ['delivery']
362                    if (delivery_types && Array.isArray(delivery_types) && delivery_types.length == 1) {
363                        if (delivery_types[0] == 'delivery') delivery_types_html = '<span class="item-status">Только доставка</span>'
364                        else delivery_types_html = '<span class="item-status">Только самовывоз</span>'
365                    }
366
367                    aHTML = '<a class="cat-item cboxElement1" href="' + item.get('href').replace("popup", "product") + '">' + name + '<div style="font-size: 14px">' + toppings_text + '</div> </a>' + delivery_types_html;
368                    cHTML = '<span class="cat-item cboxElement1">' + name + '</span>';
369
370                    return document.location.href.match(/cart_mobile.php/) ? '<div class="name">' + name + '</div><div class="subname">' + item.get('anons') + '</div>' : ('<div class="name">' + (item.get('composite') ? cHTML : aHTML) + '</div><div class="subname">' + item.get('anons') + '</div>');
371                },
372                attr: "name",
373                label: "Наименование/состав"
374            }, //            { attr: "quantity", label: "Количество", view: "input"},
375                /*                {
376                                    attr: "calories",
377                                    label: "Калорийность",
378                                    view: function (item, column) {
379                                        if (item.get('composite')) return false;
380                                        return item.get('calories') ? Math.floor(item.get('calories')) + ' kcal' : '';
381                                    }
382                                },
383                */
384
385                {
386                    view: function (item, column) {
387                        if (item.get('composite')) return false;
388                        if (item.get('uid')) {
389                            price = item.get('price');
390                            //console.log('price=', price);
391                        } else price = item.get('price1') ? item.get('price1') : item.get('price');
392                        if (item.get('price1') && item.get('price2') && item.quantity() >= 2) {
393                            //console.log('price2 exist');
394                            var p1 = parseFloat(item.get('price1')),
395
396                                p2 = parseFloat(item.get('price2'));
397                            //discount = p1 - p2;
398
399                            q = item.get('quantity');
400                            discount = ((q % 2 ? q - 1 : q) * (p1 - p2)).toFixed(2);
401
402                            //discountText = "<img src='/images/percent.png' title='Цена по акции - скидка " + discount + " руб. на второе блюдо' />";
403                            discountText = window.cartLangVars[lang]['cart_discount_title'] + ' ' + discount + " " + window.cartLangVars[lang]['cart_currency'];
404
405
406                        } else {
407                            discountText = '';
408                            discount = 0;
409                        }
410
411                        if (item.get('deprecated')) return "";
412
413                        cartprice2 = "<div class='cartprice2'>" + window.cartLangVars[lang]['cart_discount_title'] + ": <span> -" + discount + " " + window.cartLangVars[lang]['cart_currency'] + "</span></div>";
414
415                        if (item.get('uid') == PaidDeliveryUid) {
416                            console.log('PaidDeliveryUid')
417                        }
418
419                        html = '<div class="order__qty"><div class="order__price">' + (item.get('price1') ? item.get('price1') : item.get('price')) +
420                            "<span class='price-cur'>" + window.cartLangVars[lang]['cart_currency'] + "</span>" + "</div><input type='text' class='order__qty-value input-text simpleCart_input' value='" + item.get('quantity') + "' />" +
421                            '<div class="order__qty-toggles"><a href="javascript:;" class="order__qty-toggle  order__qty-toggle--more  simpleCart_increment">+</a><a href="javascript:;" class="order__qty-toggle  order__qty-toggle--less  simpleCart_decrement">&minus;</a></div></div>' +
422                            (item.get('price1') && item.get('price2') && item.quantity() >= 2 ? cartprice2 : '');
423
424
425                        return html;
426                    },
427                    attr: "quantity",
428                    label: "Количество"
429                },
430
431
432                {
433                    attr: "total",
434                    label: "Сумма",
435                    view: "currency"
436                },
437
438
439                {
440                    view: 'remove',
441                    text: "Remove",
442                    label: false
443                },
444
445
446            ],
447            cartStyle: document.location.href.match(/cart_mobile.php/) ? "div" : "div"
448        });
449        simpleCart.currency({
450            code: "RUR",
451            name: "RUR",
452            symbol: ""
453        });
454    } else {
455        cart({
456            cartColumns: [
457                //A custom cart column for putting the quantity and increment and decrement items in one div for easier styling.
458                {
459                    //                    view: function(item, column) {
460                    view: 'remove',
461                    text: "<img src='/images/minicart_remove.png' />",
462                    label: false
463                    //                    return item.get('composite') ? '' : "<img src='/images/minicart_remove.png' />";
464                    //                    },
465                    //                    attr: 'remove'
466                }, {
467                    attr: "image",
468                    label: false,
469                    view: function (item, column) {
470                        if (item.get('composite')) return false;
471                        return item.get('image') ? '<img src="' + item.get('image') + '">' : '';
472                    }
473                }, {
474                    attr: "name",
475                    label: false
476                }, {
477                    view: function (item, column) {
478                        if (item.get('composite')) return false;
479                        return "<span>" + item.get('quantity') + " шт.</span>"
480                        //                        "<div>" +
481                        //                            "<a href='javascript:;' class='simpleCart_increment'><img src='/image/increment.png' title='+1' alt='arrow up'/></a>" +
482                        //                            "<a href='javascript:;' class='simpleCart_decrement'><img src='/image/decrement.png' title='-1' alt='arrow down'/></a>" +
483                        //                        "</div>";
484                    },
485                    attr: 'custom'
486                }, //Name of the item //Subtotal of that row (quantity of that item * the price)
487                {
488                    view: 'currency',
489                    attr: "total",
490                    label: false
491                }
492                /*
493            {  view: function(item, column) {
494
495                if (item.get('composite')) return false;
496                if (item.get('uid')) {
497                    price = simpleCart.FIcfg[item.get('uid')]['price'] ? simpleCart.FIcfg[item.get('uid')]['price'] : item.get('price');
498                }
499                else     price = item.get('price');
500                //return    Math.ceil(price) + "руб.";
501                return    price + "руб.";
502
503
504               }, attr: "custom", label: false},
505*/
506            ],
507            cartStyle: 'div',
508            minicart: true
509        });
510        cart['minicart'] = 1;
511        simpleCart.currency({
512            code: "RUR",
513            name: "RUR",
514            symbol: ""
515        });
516    }
517    var itemType = ['susi', 'roll'];
518    simpleCart.extend({
519        /*
520    catFIcfg: {
521    "susi": {
522        "sous":10,
523        },
524
525
526    "roll":    {
527            "sous":10,
528        "palki":10
529        },
530
531
532    61:    {
533            "sous":10,
534        "palki":10
535        }
536    },
537
538/*
539
540    FIcfg: {
541         "sous": {
542            uid: 'sous',
543            name: "Соус",
544            price: "10",
545            anons: 'Соус',
546            uid: 200
547        },
548
549         "palki": {
550             uid: 'palki',
551             name: 'Палочки',
552             price: 0,
553             size: "Small" ,
554             quantity: 1,
555             anons: 'Приборы для еды',
556             category: 'FI',
557             sort_order: 3,
558             uid: 500
559        },
560
561
562    },
563
564*/
565        catFIcfg: {
566            10047: {
567                332: 10,
568                328: 10,
569                329: 10,
570                432: 10
571            },
572            10048: {
573                329: 2,
574                328: 2,
575                332: 3,
576                432: 3
577            }
578        },
579        FIcfg: {
580            /*
581                        329: {
582                            token: "Vasabi",
583                            name: "Васаби",
584                            price: "20",
585                            price1: "20",
586                            anons: "",
587                            uid: 329
588                        },
589                        328: {
590                            token: "Imbir-marinovannyj",
591                            name: "Имбирь маринованный",
592                            price: "20",
593                            price1: "20",
594                            anons: "",
595                            uid: 328
596                        },
597                        332: {
598                            token: "Sous-Soevyj",
599                            name: "Соус Соевый",
600                            price: "20",
601                            price1: "20",
602                            anons: "",
603                            uid: 332
604                        },
605                        432: {
606                            token: "Palki",
607                            name: "Палочки",
608                            price: "0.00",
609                            anons: "Палочки",
610                            uid: 432,
611                            image: '/images/palochki_dlia_edy.jpg'
612                        }
613            */
614        },
615
616        SETFIcfg: {
617            100164: {
618                328: 1,
619                329: 2
620
621            }
622        },
623
624        FIcrosscfg: {
625            3000: [100, 200, 300],
626            6000: [110, 220, 320],
627            9000: [120, 230, 330]
628        },
629
630        checkFIState: function () {
631            var itemCategoryCount = simpleCart.getItemCategoryCount(),
632                FIupdated = [];
633
634            for (category in itemCategoryCount) {
635                for (FIuid in simpleCart.catFIcfg[category]) {
636                    if (category && simpleCart.catFIcfg[category] && itemCategoryCount[category]) {
637                        var v = 0;
638                        simpleCart.each(function (item) {
639                            if (item.get('category') == category)
640                                v += Math.ceil(item.quantity() / simpleCart.catFIcfg[category][FIuid]);
640 // Math.ceil потому что 1 товар кладется сразу, так что инкремент фри товаров идет на N+1 материнких товаров
641                            if (simpleCart.SETFIcfg[item.get('uid')] && simpleCart.SETFIcfg[item.get('uid')][FIuid]) {
642                                v += simpleCart.SETFIcfg[item.get('uid')][FIuid]; // сеты
643                            }
644                        });
645                        FIupdated.push(FIuid);
646                        simpleCart.updateFIState(FIuid, v);
647                    }
648                }
649            }
650
651            for (FIuid in simpleCart.FIcfg) {
652                if ($.inArray(FIuid, FIupdated) == -1) {
653                    if (simpleCart.find({
654                        uid: FIuid
655                    }).length)
656                        simpleCart.find({
657                            uid: FIuid
658                        })[0].price(simpleCart.FIcfg[FIuid]['price']);
659                }
660            }
661
662            simpleCart.update();
663
664        },
665
666        updateFIState: function (uid, quantity) {
667            var FItems = simpleCart.find({
668                uid: uid
669            });
670            if (FItems.length) {
671                var FItem = FItems[0],
672                    FIquantity = FItem.quantity();
673                if ((iq = parseFloat(quantity) - parseFloat(FIquantity)) > -1) {
674                    var c = Math.abs(iq) >= 1 ? Math.abs(iq) : 0;
675                    FItem.price((c * simpleCart.FIcfg[uid]['price']) / FIquantity);
676                    FItem.quantity(Math.ceil(parseFloat(FIquantity + iq)));
677                } else {
678                    FItem.price((
679                        simpleCart.FIcfg[uid]['price'] * (FIquantity - Math.ceil(quantity))) / FIquantity);
680                }
681            } else if (quantity > 1 || !FItems.length) {
682                var tq = FItems.length ? Math.floor(quantity) + 1 : 1;
683                simpleCart.addFI(uid, tq, 0); // если нет фритоваров и добавили хоть 1 материнский товар, добавляем фри товар
684            }
685        },
686
687        getItemCategoryCount: function () {
688            var itemCategoryCount = {};
689            simpleCart.each(function (item) {
690                var itemCategory = item.get('category');
691                var itemQuantity = item.quantity();
692                if (itemCategoryCount[itemCategory]) {
693                    itemCategoryCount[itemCategory] += itemQuantity;
694                } else {
695                    itemCategoryCount[itemCategory] = itemQuantity;
696                }
697            });
698            return itemCategoryCount;
699        },
700        addFI: function (uid, quantity, price) {
701            p = parseFloat(price) || 0;
702            ////console.log ('addFI q=' + quantity + 'price=' + p + " uid=" + uid);
703            simpleCart.add({
704                uid: uid,
705                token: simpleCart.FIcfg[uid]['token'],
706                name: simpleCart.FIcfg[uid]['name'],
707                price: p,
708                price1: simpleCart.FIcfg[uid]['price1'],
709                size: "Small",
710                quantity: quantity,
711                anons: simpleCart.FIcfg[uid]['anons'],
712                //         category: 'sous',
713                sort_order: 2,
714                image: simpleCart.FIcfg[uid]['image']
715            });
716        }
717    });
718    simpleCart.ready(function () {
719        simpleCart.bind('load', function () {
720
721            checkingCartItems();
722            setInterval(checkingCartItems, 60000);
723
724            addPribory();
725            setSelectItemQuantity();
726            showAddedItemsOnTile();
727
728            if (simpleCart.find({
729                discounted: 1
730            }).length && !simpleCart.find({
731                discounted5: 1
732            }).length) {
733                console.log('ra dc');
734                removeDiscountCard();
735                applyDiscountCard();
736            }
737
738
739            //if (typeof (applyDiscountCard)!= 'undefined' && localStorage.getItem('discountCardNumber')) applyDiscountCard(localStorage.getItem('discountCardNumber'));
740            if (typeof (updateCartCSS) != 'undefined') updateCartCSS();
741
742            simpleCart.bind("beforeAdd", function (item, isNew) {
743                if (!item.get('uid')) item.set("category", "sushi");
744            });
745
746            //console.log('load');
747
748            simpleCart.bind("beforeRemove", function (item) {
749                //                    setSelectItemQuantity();
750            });
751
752            $(".in-cart").show(200);
753
754            simpleCart.bind("update", function () {
755
756                    const deliveryItem = simpleCart.find({uid: deliveryUid2});
757                    if (deliveryItem.length && simpleCart.items().length === 1) {
758                        deliveryItem[0].remove();
759                        console.log('remove deliveryItem')
760                    }
761
762                    // if (simpleCart.items()[0].get('uid') == '18022' && simpleCart.items().length === 1) simpleCart.items()[0].remove();
763
764                    $("input#rest").attr('disabled', false)
765                    $("input#delivery").attr('disabled', false)
766
767                    // проверка на товар с одним способом получения
768                    const singleObtainingMethodItems = simpleCart.items().filter((e) => {
769                        if (!!e.get('delivery_types') && e.get('delivery_types').length == 1) return true
770                    })
771
772                    let limitationObtainingMethod = false
773
774                    if (singleObtainingMethodItems.length) {
775                        if (singleObtainingMethodItems[0].get('delivery_types')[0] == 'delivery') limitationObtainingMethod = 'delivery'
776                        else if (singleObtainingMethodItems[0].get('delivery_types')[0] == 'pickup') limitationObtainingMethod = 'pickup'
777                    }
778
779                    removeOrphanItems();
780                    updatePanel();
781
782                    if (0 && simpleCart.total() > 1000 && !simpleCart.find({
783                        uid: '12557'
784                    }).length) {
785                        console.log("2500 in cart");
786                        $.ajax({
787                            url: '/alltovar-tech2.php?version=31&p_f_2_temp_id=20&p_f_2_id=' + 12557,
788                            type: "GET",
789                            dataType: "json",
790                            async: false,
791                            success: function (data) {
792                                itemInfo = data[0];
793                                itemInfo['sort_order'] = 100000000000;
794                                itemInfo['promo'] = 1;
795                                simpleCart.add(itemInfo);
796                                itemInfo['removeAllowed'] = 1;
797                            }
798                        });
799
800                    } else {
801                        if (simpleCart.find({
802                            uid: '12557'
803                        }).length && simpleCart.total() < 1000) {
804                            simpleCart.find({
805                                uid: '12557'
806                            })[0].remove();
807                        }
808                        console.log("NOT 2500");
809                    }
810
811                    if (simpleCart.find({
812                        uid: '10569'
813                    }).length && simpleCart.find({
814                        uid: '10569'
815                    })[0].quantity() > 5) {
816                        simpleCart.find({
817                            uid: '10569'
818                        })[0].quantity(5);
819                        simpleCart.update();
820                    }
821
822
823                    if (simpleCart.find({uid: '1264'}).length && document.location.href.match(/selfpickuptest/)) {
824                        console.log("1264");
825                        $("label[for='delivery']").remove();
826                        $("input#rest").click();
827                    }
828
829                    // в корзине кулинария
830                    const cooking = $.grep(simpleCart.items(), function (elem, i) {
831                        return $.inArray(elem.get('category'), [4623, 3042, 2920, 2849, 2880, 2881, 2882, 2883, 2884, 2885, 2886]) != -1 || elem.get('uid2') == '9065' || elem.get('uid2') == '9148' || elem.get('uid2') == '9065' || elem.get('uid2') == '12424' || elem.get('uid2') == '12425' || elem.get('uid2') == '12426' || elem.get('uid2') == '12427';
832                    });
833                    if (typeof (manageTime) !== 'undefined') {
834                        manageTime.cookingInCart = (cooking.length) ? true : false
835                    }
836
837                    //var n7 = simpleCart.find({uid2: '9065'});
838                    var n7 = $.grep(simpleCart.items(), function (elem, i) {
839                        return $.inArray(elem.get('category'), [4623, 3042, 2920, 2849, 2880, 2881, 2882, 2883, 2884, 2885, 2886]) != -1 || elem.get('uid2') == '9065' || elem.get('uid2') == '9148' || elem.get('uid2') == '9065' || elem.get('uid2') == '12424' || elem.get('uid2') == '12425' || elem.get('uid2') == '12426' || elem.get('uid2') == '12427';
840                    });
841                    var nb = simpleCart.find({
842                        category: 2918
843                    }).length;
844
845                    if (n7.length) {
846                        $("label[for='rest']").hide();
847                        $("#change_from_bill").hide();
848                        $("label[for='radio1625'], label[for='radio627'], label[for='radio577']").parent('div').hide()
849                        $("input#radio578").click();
850                        $("#no_need_callback").prop("checked", false)
851                        $("div:contains('действует скидка 30%.')").last().hide();
852                        $("label[for='no_need_callback']").hide();
853                        $("#discount_7kg_text").show();
854                        $("#selfpickup_discount").hide();
855                        $("#promocodeContainer, #callback_maybe").hide();
856                        $("#dateCommon").hide();
857                        $("#date7kg").show();
858
859
860                    } else {
861                        $("label[for='rest']").show();
862                        $("#change_from_bill").show();
863                        if (!nb) $("label[for='radio627'], label[for='radio577']").parent('div').show();
864                        $("div:contains('действует скидка 30%.')").last().show();
865                        $("label[for='no_need_callback']").show();
866                        $("#callback_maybe").show();
867                        //$("#selfpickup_discount").toggle($("input#rest").is(':checked'));
868                        $("#selfpickup_discount").toggle(1);
869                        $("#discount_7kg_text").hide();
870                        //$("#promocodeContainer").toggle(!!$("input#delivery:checked").length);
871                        $("#dateCommon").show();
872                        $("#date7kg").hide();
873
874
875                        if (window.location.pathname.match(/\/cart/)) {
876                            // обновляем ресторан при удалении кулинарии
877                            setRestaurantId();
878                        }
879
880
881                        // скрыть все методы оплаты кроме онлайн для самовывоза
882                        if ($('#rest').is(":checked")) {
883                            if (simpleCart.total() > 4000 && window.location.pathname.match(/\/cart/)) {
884                                console.log('total>3000')
885                                hideAllPaymentMethodsExceptOnline()
886                            } else {
887                                console.log('total<3000')
888                                showAllPaymentMethods()
889                            }
890                        }
891
892                        // **************** 01/09
893                        if (window.location.pathname.match(/\/cart/)) {
894                            let totalSum = 0;
895
896                            simpleCart.each(function (item) {
897                                if (!item.get('mse')) {
898                                    totalSum += (item.get('price') * item.get('quantity'));
899                                }
900                            });
901
902                            if (!isNaN(minPrice) && totalSum < minPrice) {
903                                $('.deliv-status').text(minPriceMsg);
904                                $('#street').addClass('ballon-w');
905                            } else {
906                                $('.deliv-status').text('');
907                                $('#street').removeClass('ballon-w');
908                            }
909                        }
910
911
912                        if (window.location.pathname.match(/\/cart/) && $('#delivery').is(':checked')) {
913
914                            if (simpleCart.total() > 5000) {
915                                console.log('delivery and total>5000')
916                                hideAllPaymentMethodsExceptOnline()
917                            } else {
918                                showAllPaymentMethods()
919                            }
920                        }
921
922
923                    }
924
925
926                    /*
927                if (simpleCart.find({category:2791}).length) {
928                    console.log('2791 FOUND');
929                    $("select#address-select option[value='119']").attr('disabled', 'disabled');
930                }
931                else $("select#address-select option[value='119']").removeAttr('disabled');
932                */
933
934
935                    if (simpleCart.find({
936                        category: 2791
937                    }).length && simpleCart.quantity() == simpleCart.find({
938                        category: 2791
939                    }).length) { // only 1+1 in cart
940                        $("label[for='delivery']").hide();
941                    }
942
943
944                    $("#delivery_paradox").toggle(!!(simpleCart.find({
945                        category: 2791
946                    }).length && simpleCart.quantity() != simpleCart.find({
947                        category: 2791
948                    }).length)); // we have 1+1 and another cat
949
950                    $("div#only4repino").toggleClass('warning-msg--active', !!simpleCart.find({
951                        category: 2787
952                    }).length);
953
954                    if (simpleCart.find({
955                        category: 2791
956                    }).length || simpleCart.find({
957                        category: 2764
958                    }).length || (simpleCart.find({
959                        uid: '8632'
960                    }).length || simpleCart.find({
961                        uid: '8631'
962                    }).length || simpleCart.find({
963                        uid: '8630'
964                    }).length || simpleCart.find({
965                        uid: '8629'
966                    }).length)) {
967                        if (!$("input#rest:checked").length) {
968                            $("label[for='delivery']").hide();
969                            $("input#rest").click();
970                        }
971                        deliveryForbidden = 1;
972                    } else {
973                        $("label[for='delivery']").show();
974                    }
975
976                    if (simpleCart.find({
977                        uid: '8847'
978                    }).length) {
979                        if (simpleCart.find({
980                            uid: '8847'
981                        })[0].get('promo') != 1) {
982                            simpleCart.find({
983                                uid: '8847'
984                            })[0].set('promo', 1);
985                            simpleCart.update();
986                        }
987                    }
988
989
990                    $("a[href*='/product']").each(function () {
991                        $(this).data('href', $(this).attr('href').replace('product', 'popup'));
992                    });
993
994                    if (lang == 'lat' || lang == 'lv_rus') {
995                        if (simpleCart.total() < 20) {
996                            $("div.msg-cart").show();
997                            $("input#rest").click();
998                            $("input#delivery").attr('disabled', 'disabled');
999                        } else {
1000                            $("div.msg-cart").hide();
1001                            $("input#delivery").removeAttr('disabled');
1002                        }
1003                    }
1004
1005                    if ($('#radio578').prop('checked') && simpleCart.grandTotal() < 1 && $("input#name").val() != 'TEST112233') {
1006                        $('.warning-msg--minsumm').addClass('warning-msg--active');
1007                        $('#cartSubmit1btn').addClass('disabled');
1008                    } else {
1009                        $('.warning-msg--minsumm').removeClass('warning-msg--active');
1010                        // $('#cartSubmit1btn').removeClass('disabled');
1011                    }
1012
1013
1014                    if (!simpleCart.items().length && document.location.href.match(/cart.html|cart.php|cart_mobile.php/)) {
1015                        $("div#tabs").replaceWith('<div class="message"><span>' + window.cartLangVars[lang]['cart_empty'] + '</span><a class="btn  btn--red  btn--big" href="' + window.cartLangVars[lang]['cart_empty_menu_button_link'] + '">' + window.cartLangVars[lang]['cart_empty_menu_button_label'] + '</a></div>');
1016                        $("a#cleanCartBtn1, [name='cart-no1'], [name='cart-no2']").remove();
1017                    } else {
1018                        if (typeof (updateCartCSS) != 'undefined') updateCartCSS();
1019                        var tKcal = 0;
1020                        simpleCart.each(function (item) {
1021                            tKcal += item.get('calories') ? parseFloat(item.get('calories')) : 0;
1022                        });
1023                        $("td.td-kcal").text(Math.floor(tKcal) + ' kcal');
1024                        $("td.td-sum").text(simpleCart.grandTotal().toFixed(2) + ' руб');
1025
1026                    }
1027                    var items = simpleCart.items();
1028                    $.each(items, function (i, e) {
1029                        temp = simpleCart.items();
1030                        var item = temp[i];
1031                        if (item.get('price2')) {
1032
1033                            //console.log('price old', item.get('price'));
1034
1035                            var oldPrice = item.get('price');
1036
1037                            q = parseFloat(item.quantity());
1038                            p1 = parseFloat(item.get('price1'));
1039                            p2 = parseFloat(item.get('price2'));
1040                            //                        price = q == 1 ? p1 : q % 2 ? ((p1 + p2) * (q - 1) / 2 + p1) / q : (p1 + p2) / 2;
1041                            price = q == 1 ? p1 : q % 2 ? (p2 * q - p2 + p1) / q : p2;
1042                            //console.log('p1 p2', p1, p2);
1043
1044
1045                            item.set('price', price);
1046                            //console.log('price, oldPrice', item.get('price'));
1047                            if (item.get('price') != oldPrice) simpleCart.update();
1048                        }
1049                    });
1050
1051                    setSelectItemQuantity();
1052
1053                    manageNB();
1054
1055
1056                    pribory = 0;
1057                    pribory_max = 0;
1058
1059                    fs_updated = 0;
1060                    simpleCart.each(function (item) {
1061                        if (item.get('uid') == 12112) return false;
1062                        if (item.get("priboryK") && item) pribory += item.quantity() * item.get("priboryK");
1063                        if (item.get("priboryK_max") && item.get) pribory_max += item.quantity() * item.get("priboryK_max");
1064                    });
1065
1066                    freePribory = simpleCart.find({
1067                        uid: 12112
1068                    });
1069                    fs_updated = 0;
1070                    if (freePribory.length) {
1071                        console.log("PRIBORY FOUND");
1072                        if (freePribory.length && freePribory[0].quantity() > pribory_max) {
1073                            fs_updated = 1;
1074                            freePribory[0].quantity(pribory_max);
1075                        }
1076                    }
1077
1078
1079                    if (fs_updated) simpleCart.update();
1080
1081
1082                    if (simpleCart.find({promo: 1}).length) {
1083                        promoItem = simpleCart.find({
1084                            promo: 1
1085                        })[0];
1086                        promoMinSum = promoItem.get('promoMinSum') || 2000;
1087                        total = simpleCart.total();
1088                        if (total < promoMinSum) {
1089                            needToAdd = promoMinSum - total;
1090                            $("#cartSubmit1btn").addClass("btn--disabled").val("Необходимо дозаказать на " + needToAdd + "₽");
1091                        } else {
1092                            $("#cartSubmit1btn").removeClass("btn--disabled").val("Оформить заказ");
1093                        }
1094                    } else {
1095                        $("#cartSubmit1btn").removeClass("btn--disabled").val("Оформить заказ");
1096                    }
1097
1098
1099                    if (document.location.href.match(/simpleCart.php/)) {
1100                        initColorBox();
1101                    }
1102                    if (document.location.href.match(/order.php|order_mobile.php|cart.html/)) {
1103                        orderFillTextArea();
1104                    }
1105
1106                    //                    if (typeof (processFils) != 'undefined') processFils(); // enable this to process
1107
1108                    $('#user_f_45').val(simpleCart.grandTotal());
1109
1110                    $("div.cart, .minicart").toggleClass('empty', !simpleCart.items().length);
1111
1112                    //if (typeof (applyDiscountCard)!= 'undefined' && localStorage.getItem('discountCardNumber')) applyDiscountCard(localStorage.getItem('discountCardNumber'));
1113
1114
1115                    var pcd1 = ['13159', '13160', '13161', '13162', '13163', '13164', '13178', '13226', '13227', '13228', '13108', '13103', '13105', '13106', '13104', '13097', '13098', '13099', '13100', '13101', '13086', '13067', '13068', '13016', '13015', '13014', '13013', '13012', '13001', '13002', '13003', '12975', '12976', '12977', '12978', '12979', '12980', '12960', '12959', '12926', '12924', '12925', '12641', '12642', '12585', '12586', '12588', '12587', '12584', '12169', '12168', '12170', '12166', '12167', '12150', '12151', '12153', '12152', '12148', '12146', '12149', '12145', '12143', '12142', '12120', '12119', '12118', '11663', '11664']; // delivery only promocodes
1116                    var sp = $.grep(simpleCart.items(), function (elem, i) {
1117                        return $.inArray(elem.get('uid'), pcd1) != -1;
1118                    });
1119                    if (sp.length) {
1120                        $("label[for='rest']").hide();
1121                        if (!$("input#delivery:checked").length) {
1122                            $("input#delivery").click();
1123                        }
1124                    }
1125
1126                    promoDeliveryVariant()
1127
1128                    if (limitationObtainingMethod) {
1129                        if (limitationObtainingMethod == 'delivery') {
1130                            console.log('### в корзине товар только для доставки')
1131                            if (!!$("input#rest")) {
1132
1133                                if ($("input#rest").is(':checked')) {
1134                                    $("input#delivery").click();
1135                                }
1136                                // $("label[for='rest']").hide();
1137                                $("input#rest").attr('disabled', true)
1138                            }
1139                        } else {
1140                            console.log('### в корзине товары только для самовывоза')
1141                            if (!!$("input#delivery")) {
1142
1143                                if ($("input#delivery").is(':checked')) {
1144                                    $("input#rest").click();
1145                                }
1146                                // $("label[for='delivery']").hide();
1147                                $("input#delivery").attr('disabled', true)
1148                                //
1149                                const deliveryItem = simpleCart.find({uid: deliveryUid2});
1150                                if (deliveryItem.length) {
1151                                    deliveryItem[0].remove();
1152                                }
1153
1154
1155                            }
1156                        }
1157                    }
1158
1159                    // debug
1160                    //if (document.location.href.match(/debug/) && document.location.href.match(/cart\.html/)) {
1161                    if (document.location.href.match(/cart\.html/)) {
1162
1163                        checkTotalSum();
1164
1165                        // let totalSum = 0;
1166                        // simpleCart.each(function (item) {
1167                        //     if (!item.get('mse')) totalSum += (item.get('price') * item.get('quantity'));
1168                        // });
1169                        //
1170                        // console.log('+===+ totalSum=', totalSum);
1171                        //
1172                        //
1173                        // if (typeof minPrice !== 'undefined' && minPrice > 0) {
1174                        //     console.log('+===+ minPrice=', minPrice);
1175                        //     if (totalSum < minPrice && $("input#delivery:checked").length) {
1176                        //         $('#cartSubmit1btn').addClass('disabled');
1177                        //         const buttonText = 'Добавьте товаров на ' + String(minPrice - totalSum) + ' руб';
1178                        //
1179                        //         // Проверяем, отличается ли новый текст от текущего
1180                        //         if ($('#cartSubmit1btn').val() !== buttonText) {
1181                        //             $('#cartSubmit1btn').val(buttonText);
1182                        //         }
1183                        //     } else {
1184                        //         const defaultText = 'Оформить заказ';
1185                        //
1186                        //         // Проверяем, отличается ли текст от стандартного
1187                        //         if ($('#cartSubmit1btn').val() !== defaultText) {
1188                        //             $('#cartSubmit1btn').val(defaultText);
1189                        //         }
1190                        //     }
1191                        // }
1192
1193                    } // debug
1194
1195
1196                }
1197            )
1198            ;
1199            simpleCart.bind("afterAdd", function (item, isNew) {
1200                ////console.log('afteradd');
1201                if (typeof (applyDiscountCard) != 'undefined' && localStorage.getItem('discountCardNumber')) applyDiscountCard(localStorage.getItem('discountCardNumber'));
1202                //                    if (typeof (processFils) != 'undefined') process
1202Fils();
1203            });
1204
1205            simpleCart.bind("afterSave", function (item, isNew) {
1206                if (!simpleCart.items().length) {
1207                    $("#cartPopover").hide();
1208                    $(".cart-trigger").hide();
1209                } else {
1210                    $(".cart-trigger").show();
1211                }
1212
1213                //    simpleCart.checkFIState();
1214            });
1215
1216            simpleCart.bind("beforeSave", function (item, isNew) {
1217                //                    if (typeof (processFils) != 'undefined') processFils();
1218
1219                ///                    //console.log('feforesave');
1220                //if (typeof (applyDiscountCard)!= 'undefined' && localStorage.getItem('discountCardNumber')) applyDiscountCard(localStorage.getItem('discountCardNumber'));
1221                //    simpleCart.checkFIState();
1222            });
1223        });
1224    });
1225
1226
1227    $("#add_magnit").click(function () {
1228        $.ajax({
1229            url: '/alltovar-tech2.php?version=31&p_f_2_temp_id=20&p_f_2_id=' + 10933,
1230            type: "GET",
1231            dataType: "json",
1232            async: false,
1233            success: function (data) {
1234                itemInfo = data[0];
1235                itemInfo['sort_order'] = 100000000000;
1236                simpleCart.add(itemInfo);
1237            }
1238        });
1239    });
1240
1241
1242});
1243
1244
1245function removeOrphanItems() {
1246
1247    var containers = [];
1248    var dt = new Date();
1249    $.each(simpleCart.items(), function (i, item) {
1250        if (item.get('composite') && !simpleCart.find({
1251            uid: item.get('parentuid')
1252        }).length) {
1253            item.remove();
1254        }
1255    });
1256
1257    if (simpleCart.find({
1258        uid: "1011"
1259    }).length) simpleCart.find({
1260        uid: "1011"
1261    })[0].remove();
1262    //if (simpleCart.find({uid:"12557"}).length) simpleCart.find({uid:"12557"})[0].remove();
1263    if (simpleCart.find({
1264        iiko_id: "bd1fddb6-0c6e-44a1-bc7f-a3d450efbdfe"
1265    }).length) simpleCart.find({
1266        iiko_id: "bd1fddb6-0c6e-44a1-bc7f-a3d450efbdfe"
1267    })[0].remove();
1268    if (simpleCart.find({
1269        iiko_id: "6dc0c5d8-7b5e-4ddb-8be6-0766da4b4882"
1270    }).length) simpleCart.find({
1271        iiko_id: "6dc0c5d8-7b5e-4ddb-8be6-0766da4b4882"
1272    })[0].remove();
1273    if (dt.getDate() != 23 && simpleCart.find({
1274        uid: "2161"
1275    }).length) simpleCart.find({
1276        uid: "2161"
1277    })[0].remove();
1278
1279}
1280
1281function setSelectItemQuantity() {
1282    $("li[name='select-item-li0']").text(0)
1283    simpleCart.each(function (item) {
1284        if (window.mobilesite) {
1285            $("select#select-item-" + item.get('uid')).val(item.quantity());
1286        } else {
1287            $("li[name='select-item-li0']", $("ul#select-item-" + (item.get('uid2') || item.get('uid')))).text(item.quantity());
1288        }
1289    });
1290}
1291
1292// переключаем варианты доставки, если в корзине промотовар
1293function promoDeliveryVariant() {
1294
1295    if (!!simpleCart.find({promo: 1}).length && document.location.href.match(/cart/)) {
1296
1297        if (localStorage.promodelivery == 'false') {
1298            $("label[for='delivery']").hide();
1299            if (!$("#rest").is(":checked")) $("input#rest").click();
1300        }
1301
1302        if (localStorage.promopickup == 'false') {
1303            $("label[for='rest']").hide();
1304            if (!$("#delivery").is(":checked")) $("input#delivery").click();
1305        }
1306    }
1307}
1308
1309function erasePromoInput() {
1310    $("input[name='user_f_54']").val('')
1311}
1312
1313function applyPromoCode(promocode) {
1314
1315    const promoStatus = {
1316        smallOrderAmount: 0,
1317        promoGoodsInBasket: 0,
1318        promocodeApplied: 0,
1319        promocodeCorrect: 0,
1320        customMessage: '',
1321        delivery: true,
1322        pickup: true
1323    }
1324
1325    const promoCode = promocode.toLowerCase().replace(/\s/g, '');
1326    ;
1327
1328
1329    if ((localStorage.getItem('promocode2') || simpleCart.find({
1330        'promo': 1
1331    }).length) && !(simpleCart.find({
1332        'promo': 1
1333    }).length == 1 && simpleCart.find({
1334        uid: '12557'
1335    }).length)) {
1336
1337        promoStatus.promoGoodsInBasket = 1
1338        promoStatus.customMessage = 'В корзине уже есть товары с примененным промо-кодом';
1339        erasePromoInput()
1340        return promoStatus
1341    }
1342
1343    /*  start insert ==================================================================== */
1344
1345    function totalWithoutSpecialItems() {
1346        var total21 = 0, totalNot21 = 0, totalNot21Price = 0;
1347        $.each(simpleCart.items(), function (i, item) {
1348            if (item.get('category') == 2776 && item.get('uid') != 6510) total21 += item.get('quantity');
1349        });
1350
1351        $.each(simpleCart.items(), function (i, item) {
1352            if (item.get('category') != 2776 && item.get('uid') != 6510) {
1353                totalNot21 += item.get('quantity');
1354                totalNot21Price += item.get('quantity') * item.get('price');
1355            }
1356        });
1357        return totalNot21Price;
1358
1359
1360        // Бахрома specialGoodsInBasket
1361        // if ((flags && $.inArray('offer', flags) != -1) || $.inArray(parseFloat(item.get('category')), [3260, 3238, 3042, 2920, 2918, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2862, 2790, 2787, 2764, 1499, 1527, 10000000000000]) != -1) {
1362        //     specialGoodsInBasket = 1;
1363        //     return true;
1364        // }
1365
1366
1367    }
1368
1369
1370    function addPromoItemsToCart(new_items, quantity = 1) {
1371        new_items.forEach((itemId) => {
1372            $.ajax({
1373                url: '/alltovar-tech2.php?p_f_2_158=' + itemId,
1374                type: "GET",
1375                dataType: "json",
1376                async: false,
1377                timeout: 5,
1378                success: function (item) {
1379                    console.log(item[0]);
1380                    /* проверка нет ли уже этого промотовара в корзине */
1381
1382                    if (simpleCart.find({uid: item[0].uid}).length) {
1383                        promoStatus.promocodeApplied = 0;
1384
1385                    } else { // если нет, то добавляем
1386                        item[0]['quantity'] = quantity;
1387                        item[0]['href'] = '#';
1388                        item[0]['promo'] = 1;
1389                        item[0]['remove-allowed'] = 1;
1390                        simpleCart.add(item[0]);
1391                        promoStatus.promocodeApplied = 1;
1392                        //addFreeSticks();
1393                    }
1394                    promoStatus.promoGoodsInBasket = 1
1395                }
1396            });
1397        });
1398    }
1399
1400    $.ajax({
1401        url: '/data/app_promocodes.php',
1402        type: "GET",
1403        dataType: "json",
1404        async: false,
1405        timeout: 5,
1406        success: function (data) {
1407            console.log(data)
1408            const promo_obj = data.find(promo => promo.promocode.toLowerCase() === promoCode);
1409
1410            if (promo_obj) {
1411
1412                let totalAmount = totalWithoutSpecialItems();
1413                promoStatus.promocodeCorrect = 1
1414                if (promo_obj.new_items.length > 0 && promo_obj.new_items != "") {
1415
1416                    if (totalAmount >= promo_obj.minsum) {
1417                        switch (promo_obj.action) {
1418                            case 'add_item':
1419                                addPromoItemsToCart(promo_obj.new_items)
1420                                simpleCart.update()
1421                                promoStatus.customMessage = 'Промокод успешно применен'
1422                                console.log('***Промокод add_item успешно применен!')
1423
1424                                // варианты доставки у промокода
1425                                promoStatus.delivery = promo_obj.delivery_types.includes('delivery')
1426                                promoStatus.pickup = promo_obj.delivery_types.includes('pickup')
1427                                localStorage.promodelivery = promoStatus.delivery
1428                                localStorage.promopickup = promoStatus.pickup
1429                                promoDeliveryVariant()
1430                                break
1431                            case 'replace_item':
1432                                replaceItem = simpleCart.find({iiko_id: promo_obj.base_item})[0];
1433                                if (replaceItem) {
1434                                    addPromoItemsToCart(promo_obj.new_items, replaceItem.quantity());
1435                                    replaceItem.remove();
1436                                    simpleCart.update();
1437                                    promoStatus.customMessage = 'Промокод успешно применен'
1438                                    console.log('***Промокод replace_item успешно применен!')
1439
1440                                    // варианты доставки у промокода
1441                                    promoStatus.delivery = promo_obj.delivery_types.includes('delivery')
1442                                    promoStatus.pickup = promo_obj.delivery_types.includes('pickup')
1443                                    localStorage.promodelivery = promoStatus.delivery
1444                                    localStorage.promopickup = promoStatus.pickup
1445                                    promoDeliveryVariant()
1446                                } else {
1447                                    // не найдено товара под замену в корзине
1448                                    promoStatus.promoGoodsInBasket = 0
1449                                    promoStatus.promocodeApplied = 0
1450                                    promoStatus.customMessage = 'В корзине не найден товар для замены по условию промокода.'
1451                                    console.log('***Промокод не применен, не найден товар для замены!')
1452                                    erasePromoInput()
1453                                }
1454                                break
1455                            case 'discount':
1456                                promoStatus.promocodeCorrect = 0
1457                                console.log('***Промокод не применен, не обслуживаемый тип!')
1458                                erasePromoInput()
1459                                break
1460                        }
1461
1462                    } else {
1463                        promoStatus.smallOrderAmount = 1
1464                        promoStatus.promocodeApplied = 0
1465                        promoStatus.customMessage = 'Суммы заказа без учёта акционного товара недостаточно для применения промо-кода.'
1466                        console.log('***Промокод не применен, недостаточная сумма заказа!')
1467                        erasePromoInput()
1468                    }
1469
1470                } else {
1471                    promoStatus.customMessage = 'Срок действия промо-кода истек';
1472                    console.log('***Промокод не применен, не найден new_items')
1473                    erasePromoInput()
1474                }
1475
1476            }
1477        }
1478    });
1479
1480    /*  end insert ==================================================================== */
1481
1482
1483    /*
1484            if (simpleCart.total() < 1500) {
1485                promocodeApplied = 0;
1486                promoGoodsInBasket = 0;
1487                promocodeCorrect = 1;
1488                customMessage = 'Минимальная сумма заказа после применения промокода 1200 руб.';
1489            } else if (simpleCart.find({
1490                    'promo': 1
1491                }).length) {
1492                promocodeApplied = 0;
1493                promoGoodsInBasket = 1;
1494                promocodeCorrect = 1;
1495                customMessage = 'Промокод уже применен.';
1496            } else {
1497                removeDiscountCard();
1498                applyDiscountCard('scd30');
1499                window.voaddr = 1;
1500                localStorage.setItem('promocode2', promocode);
1501                promocodeApplied = 1;
1502                promocodeCorrect = 1;
1503                promoGoodsInBasket = 1;
1504                $("[name='user_f_94']").val('апрель');
1505
1506            }
1507
1508    ///////////////////////////////
1509
1510
1511        } else {
1512            //console.log('not f99');
1513            $.each(simpleCart.items(), function(i, item) {
1514                if (item.get('promo')) {
1515                    return 1;
1516                }
1517
1518                $.ajax({
1519                    url: item.get('href').replace(/product|popup/, 'product-data-promo-multiple').replace(/.html/, '') + '/',
1520                    type: "GET",
1521                    dataType: "json",
1522                    async: false,
1523                    success: function(data) {
1524                        ////console.log('s0', data);
1525                        if (data['promo-ids']) {
1526                            $.each(data['promo-ids'], function(i, promoid) {
1527                                $.ajax({
1528                                    url: '/promo-check.php',
1529                                    data: {
1530                                        id: promoid,
1531                                        promocode: promocode
1532                                    },
1533                                    type: "GET",
1534                                    dataType: "json",
1535                                    async: false,
1536                                    success: function(promocheck) {
1537                                        //                        //console.log('pc0', promocheck, 'promocode' + promocode + ' id=' + item.get('uid'));
1538                                        if (promocheck['success'] == 1) {
1539                                            ////console.log('success verification promocode ' + promocode, promocheck['success']);
1540                                            $.ajax({
1541                                                url: '/alltovar-tech2.php?version=25&p_f_2_temp_id=20&p_f_2_id=' + promoid,
1542                                                type: "GET",
1543                                                dataType: "json",
1544                                                async: false,
1545                                                success: function(promodata) {
1546                                                    //                                //console.log('pgetpromodata', promodata);
1547                                                    promodata = promodata[0];
1548                                                    if (!item.get('promo')) {
1549                                                        item.set('uid', promodata['uid']);
1550                                                        item.set('iiko_id', promodata['iiko_id']);
1551                                                        item.set('price', promodata['price']);
1552                                                        item.set('price1', promodata['price']);
1553                                                        item.set('name', item.get('name') + ' PROMO');
1554                                                        item.set('promo', true);
1555                                                        simpleCart.update();
1556                                                        $('#user_f_45').val(simpleCart.grandTotal());
1557                                                    }
1558                                                    promocodeApplied = 1;
1559                                                    //console.log('pca0', promocodeApplied);
1560                                                    promocodeCorrect = 1;
1561                                                }
1562                                            });
1563                                        }
1564                                    }
1565                                });
1566                                promoGoodsInBasket = 1;
1567                            });
1568                        }
1569                    }
1570                });
1571            });
1572        }
1573    */
1574
1575    return promoStatus
1576}
1577
1578function applyDiscountCard(num) {
1579    console.log('adc');
1580    num = (num == 'scd' || num == 'scd30') ? num : 1000001;
1581    var specialGoodsInBasket = 0,
1582        discountApplied = 0,
1583        promises = [],
1584        dfd = $.Deferred();
1585    ////console.log ('dfd0', dfd);
1586    console.log('num', num);
1587    if (num == 'scd30' || num == 'scd' || (((num >= 1 && num < 904000) || (num >= 1000001 && num <= 1108000)) && num.toString().length == 7)) {
1588        var dk = num == 'scd' ? 1 : 1;
1589        if (num == 'scd30') dk = 1;
1590
1591
1592        console.log('num=', num, 'dk=', dk, 'card ok items = ', simpleCart.items());
1593        $.each(simpleCart.items(), function (i, e) {
1594            var item = simpleCart.items()[i];
1595            //        if (item.get('composite')) return true;
1596
1597            promise = getItemInfo(item.get('uid2') || item.get('uid'));
1598            promises.push(promise);
1599            promise.done(function (data) {
1600                itemInfo = data['itemInfo'];
1601                flags = itemInfo['flags'];
1602                item.set('flags', flags);
1603
1604                ////console.log("2512");
1605                console.log('item price', item.get('price'));
1606
1607                if (item.get('baseprice') != itemInfo['price'] && !item.get('composite') && !item.get('constructed')) { // old item, updating price
1608                    item.set('baseprice', itemInfo['price']);
1609                    item.set('price1', itemInfo['price']);
1610                    item.price(itemInfo['price']);
1611                    item.set('discounted', 0);
1612                }
1613
1614
1615                //console.log ('item price2', item.get('price'));
1616                //console.log('item0', item);
1617
1618
1619                //if ((flags && $.inArray('offer', flags) != -1) || $.inArray(parseFloat(item.get('category')), [3238, 3042, 2920, 2918, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2862, 2790, 2787, 2764, 1499, 1527, 10000000000000]) != -1) {
1620                if ((flags && $.inArray('offer', flags) != -1) || $.inArray(parseFloat(item.get('category')), [4623, 3284, 3042, 2920, 2918, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2862, 2790, 2787, 2764, 1499, 1527, 10000000000000]) != -1) {
1621                    //console.log (item, 'NGE', item.get('flags'), 'cat', $.inArray(item.get('category'), [1527, 10000000000000]));
1622                    specialGoodsInBasket = 1;
1623                    return true;
1624                }
1625
1626                if (item.get('uid')) {
1627                    ////console.log('item uid', item.get('uid'));
1628                    if (!item.get('discounted')) {
1629                        price = item.get('price1') ? item.get('price1') : item.get('price');
1630                        discountPrice = price * dk;
1631                        discountPrice = discountPrice.toFixed(2);
1632                        item.set('price1', discountPrice);
1633                        item.price(discountPrice);
1634                        item.set('discounted', 1);
1635                        item.set('discounted5', 1);
1636                        item.set('baseprice', price);
1637                        simpleCart.update();
1638                        discountApplied = 1;
1639                        //console.log("DISCOUNT_APPLIED");
1640                        //console.log ('item price3', item.get('price'));
1641                    } else {
1642                        discountApplied = 1;
1643                    }
1644                }
1645                ////console.log ('da', discountApplied);
1646            });
1647        });
1648
1649    }
1650
1651    $.when.apply($, promises).done(function () {
1652        ////console.log ('da0', discountApplied, num.toString().length, 'dfd', dfd);
1653        dfd.resolve({
1654            discountApplied: discountApplied,
1655            specialGoodsInBasket: specialGoodsInBasket
1656        });
1657        //        processFils();
1658    });
1659
1660    return dfd;
1661
1662}
1663
1664
1665function removeDiscountCard(num) {
1666    console.log("rdc");
1667    localStorage.removeItem('discountCardNumber');
1668    $.each(simpleCart.items(), function (i, e) {
1669        var item = simpleCart.items()[i];
1670        if (item.get('uid') && item.get('discounted')) {
1671            baseprice = item.get('baseprice');
1672            ////console.log (item, baseprice);
1673            item.set('price1', baseprice);
1674            item.price(baseprice);
1675            item.set('discounted', 0);
1676            simpleCart.update();
1677        }
1678    });
1679}
1680
1681function showAddedItemsOnTile() {
1682
1683    $.each(simpleCart.items(), function (index, item) {
1684        uid = item.get('uid');
1685        q1 = item.quantity();
1686        //$("div[data-pid='" + uid + "']").find(".item__add").eq(0).addClass("item__add--vis");
1687        $("div[data-pid='" + uid + "']").addClass("added");
1688        $("div[data-pid='" + uid + "']").find(".item__add-text").text("Добавлено " + q1 + " в корзину");
1689    });
1690}
1691
1692
1693function getItemInfo(id) {
1694    var def = $.Deferred();
1695    $.getJSON('/alltovar-tech2.php?p_f_2_temp_id=20&p_f_2_id=' + id).done(function (data) {
1696        if (data) {
1697            def.resolve({
1698                itemInfo: data[0]
1699            });
1700        }
1701    });
1702
1703    return def;
1704}
1705
1706function manageNB() {
1707
1708
1709    var n7 = $.grep(simpleCart.items(), function (elem, i) {
1710        return $.inArray(elem.get('category'), [2920, 2849, 2880, 2881, 2882, 2883, 2884, 2885, 2886]) != -1 || elem.get('uid2') == '9065' || elem.get('uid2') == '9148';
1711    });
1712    if (simpleCart.find({
1713        category: 2918
1714    }).length && document.location.href.match(/cart/)) {
1715
1716        manageTime.nb = true
1717
1718        $("label[for='radio-soon']").hide();
1719        setTimeout(function () {
1720            $("input#radio-delivery").click();
1721        }, 1000);
1722        total = simpleCart.total();
1723
1724        if (total >= 5000) {
1725            console.log('more 5000');
1726            $("label[for='radio627'], label[for='radio577']").parent('div').hide();
1727            $("label[for='radio578']").parent('div').show();
1728            $("input#radio578").click();
1729            if ($("input#rest").is(':checked')) {
1730                $("#datepicker2").datepicker("option", "minDate", 1); // 1
1731                $("#warning-time").removeClass("warning-msg--active");
1732            } else {
1733                $("#datepicker2").datepicker("option", "minDate", 1); // 1
1734                $("#warning-time").addClass("warning-msg--active").text("Доставка праздничных боксов осуществляется на следующий день с 13 часов");
1735
1736            }
1737
1738        } else if (!n7.length) {
1739            console.log('less 5000');
1740            if ($("input#rest").is(':checked')) {
1741                $("#datepicker2").datepicker("option", "minDate", 0); // 0
1742                $("label[for='radio627'], label[for='radio577']").parent('div').show();
1743                $("label[for='radio578']").parent('div').hide();
1744                $("input#radio627").click();
1745                $("#warning-time").addClass("warning-msg--active").text("Заказ можно будет забрать из ресторана не ранее чем через 3 часа");
1746
1747            } else {
1748                $("#datepicker2").datepicker("option", "minDate", 1); // 1
1749                $("label[for='radio627'], label[for='radio577']").parent('div').hide();
1750                $("label[for='radio578']").parent('div').show(); // mod1
1751                $("input#radio578").click(); // mod1
1752                $("#warning-time").addClass("warning-msg--active").text("Доставка праздничных боксов осуществляется на следующий день с 13 часов");
1753            }
1754
1755        }
1756
1757    } else {
1758        $("#warning-time").removeClass("warning-msg--active");
1759        $("label[for='radio-soon']").show();
1760    }
1761
1762    if (simpleCart.find({
1763        category: 2764
1764    }).length && document.location.href.match(/cart/)) { // alcohol
1765        $("label[for='radio627'], label[for='radio577']").parent('div').show();
1766        $("label[for='radio578']").parent('div').hide();
1767        $("input#radio627").click();
1768    }
1769
1770
1771}
1772
1773function addPribory() {
1774    freePribory = 0;
1775
1776    p1 = simpleCart.find({
1777        uid: "12112"
1778    });
1779
1780    console.log("p1", p1);
1781
1782
1783    simpleCart.each(function (item) {
1784        if (item.get("priboryK")) freePribory += item.quantity() * item.get("priboryK");
1785    });
1786
1787    if (freePribory) {
1788        console.log("ADDING FP");
1789        $.ajax({
1790            url: '/alltovar-tech2.php?version=33&p_f_2_temp_id=20&p_f_2_id=' + 12112,
1791            type: "GET",
1792            dataType: "json",
1793            async: false,
1794            success: function (data) {
1795
1796
1797                p1 = simpleCart.find({
1798                    uid: "12112"
1799                });
1800
1801                console.log("p1-2", p1);
1802
1803                itemInfo = data[0];
1804                itemInfo['sort_order'] = 100000000000;
1805                if (!p1.length) simpleCart.add(itemInfo);
1806
1807                p = simpleCart.find({
1808                    uid: "12112"
1809                });
1810                if (p.length) {
1811                    p[0].quantity(Math.round(freePribory));
1812                }
1813            }
1814
1815
1816        });
1817    }
1818
1819    // else {
1820    //     p = simpleCart.find({
1821    //         uid: "12112"
1822    //     });
1823    //     if(p.length) p[0].remove();
1824    //
1825    // }
1826}
1827
1828function addPaidSous() {
1829
1830    //console.log('add pribory');
1831    ps = 0;
1832
1833    simpleCart.each(function (item) {
1834        if (item.get('category') == 3544) ps += item.quantity();
1835    });
1836
1837    console.log("PS", ps);
1838
1839    if (ps) {
1840        $.ajax({
1841            url: '/alltovar-tech2.php?version=31&p_f_2_temp_id=25&p_f_2_id=' + 12064,
1842            type: "GET",
1843            dataType: "json",
1844            async: false,
1845            success: function (data) {
1846                itemInfo = data[0];
1847                itemInfo['sort_order'] = 100000000000;
1848                simpleCart.add(itemInfo);
1849                p = simpleCart.find({
1850                    uid: "12064"
1851                });
1852                if (p.length) {
1853                    p[0].quantity(Math.round(ps));
1854                }
1855            }
1856        });
1857
1858
1859        $.ajax({
1860            url: '/alltovar-tech2.php?version=31&p_f_2_temp_id=25&p_f_2_id=' + 12065,
1861            type: "GET",
1862            dataType: "json",
1863            async: false,
1864            success: function (data) {
1865                itemInfo = data[0];
1866                itemInfo['sort_order'] = 100000000000;
1867                simpleCart.add(itemInfo);
1868                p = simpleCart.find({
1869                    uid: "12065"
1870                });
1871                if (p.length) {
1872                    p[0].quantity(Math.round(ps));
1873                }
1874            }
1875        });
1876
1877
1878        $.ajax({
1879            url: '/alltovar-tech2.php?version=31&p_f_2_temp_id=25&p_f_2_id=' + 12066,
1880            type: "GET",
1881            dataType: "json",
1882            async: false,
1883            success: function (data) {
1884                itemInfo = data[0];
1885                itemInfo['sort_order'] = 100000000000;
1886                simpleCart.add(itemInfo);
1887                p = simpleCart.find({
1888                    uid: "12066"
1889                });
1890                if (p.length) {
1891                    console.log('setting 12012 to', ps);
1892                    p[0].quantity(ps);
1893                }
1894            }
1895        });
1896
1897
1898    }
1899}
1900
1901
1902function processFils() {
1903
1904    return 0;
1905
1906    //    //console.log('processfils');
1907    //    var fils = simpleCart.find({iiko_id: '3ed47998-14f1-483f-9745-84437e06533d'});
1908    var fils = simpleCart.find({
1909        uid: '245'
1910    });
1911
1912    if (!fils.length) return 0;
1913    //    //console.log('fils', fils);
1914
1915    var sum = 0,
1916        dfc = 0, // count of filadelfiyas to set the promo
1917        filprice = fils[0].get('price1'), // make me dynamic FIXME
1918        filpromoprice = 99, // make me dynamic FIXME;
1919        diff = filprice - filpromoprice;
1920
1921    //    //console.log('filprice', filprice);
1922    simpleCart.each(function (item) {
1923        sum += item.quantity() * (item.get('uid') == '245' ? filprice : item.get('price1'));
1924        //    sum += item.quantity() * (item.get('iiko_id') == '3ed47998-14f1-483f-9745-84437e06533d' ? filprice : item.get('price1'));
1925    });
1926
1927    ////console.log('fils quantuty', fils.quantity());
1928    var fc = fils[0].quantity();
1929
1930    //item.get('iiko_id') == '3ed47998-14f1-483f-9745-84437e06533d'
1931    //    //console.log('sum0', sum);
1932
1933    for (i = 0; i < fc; i++) {
1934        r = 700 * (dfc + 1);
1935        //    //console.log('r', r);
1936        //    //console.log('ok0 sum', sum, 'sum-diff', sum-diff);
1937
1938        if (sum - diff >= r) { // считаем нужное кол-во промо товаров, определяем по границе 700р
1939            //console.log('dfc increase');
1940            dfc++;
1941            sum = sum - diff;
1942        }
1943    }
1944    ;
1945
1946    //console.log('dfc', dfc);
1947
1948
1949    if (fils.length) {
1950        fq = fils[0].get('quantity');
1951        fqd = fq - dfc;
1952        promoprice = (fqd * filprice + dfc * filpromoprice) / fq;
1953        //console.log('fq', fq, 'promoprice', promoprice);
1954        if (dfc && fils[0].get('price') != promoprice) {
1955            fils[0].set('price', promoprice);
1956            fils[0].set('name', 'Маргарита + акция 99 руб.');
1957            fils[0].set('promo', 1);
1958            fils[0].set('dfc', dfc);
1959            simpleCart.update();
1960        }
1961
1962        if (!dfc && fils[0].get('price') != promoprice) {
1963            fils[0].set('price', promoprice);
1964            fils[0].set('name', 'Маргарита');
1965            fils[0].set('dfc', 0);
1966            fils[0].set('promo', 0);
1967            simpleCart.update();
1968        }
1969
1970    }
1971
1972}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.