$(document).ready(function(){
var csrf = $('meta[name="csrf-token"]').attr('content');

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': csrf,
}
});

banner_slider();
pay_var();
product_page();
burger_menu();
accordion();
setOrder();
catalog_list();
registration();

initMap();

supplements_modal();

checkCookies();


});

function number_format( number, decimals, dec_point, thousands_sep ){
var i, j, kw, kd, km;

// input sanitation & defaults
if( isNaN(decimals = Math.abs(decimals)) ){
decimals = 2;
};

if( dec_point == undefined ){
dec_point = ",";
};

if( thousands_sep == undefined ){
thousands_sep = ".";
};

i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

if( (j = i.length) > 3 ){
j = j % 3;
} else{
j = 0;
};

km = (j ? i.substr(0, j) + thousands_sep : "");
kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");

return km + kw + kd;
}

if(!String.prototype.trim){
(function(){
// Вырезаем BOM и неразрывный пробел
String.prototype.trim = function() {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
})();
};

function burger_menu(){
$('.burger__menu-icon__wrapper').click(function() {
$(this).toggleClass('act');
$('.header__links').toggleClass('act');
$('body').toggleClass('noScroll');
});
};

function banner_slider(){
$('.banner__slider').slick({
dots: true,
slidesToScroll: 1,
centerMode: true,
centerPadding: '0px',
        fade            : true,
        cssEase         : 'linear',
//adaptiveHeight: true,
        infinite        : true,
slidesToShow: 1,
autoplay: true,
autoplaySpeed: 5000,
arrows          : false,
        
});
    

};

function pay_var(){
$('.checkbox-option').children('input[type=radio][name=payment]').change(function () {
$('.checkbox-option').removeClass('act');
$(this).parent().toggleClass('act');
});
};

function product_page(){
var page = $('#product-page');

if(page.length < 1){
return false;
};

$('#product__slider').slick({
    dots: true,
slidesToScroll: 1,
centerMode: true,
centerPadding: '0px',
        fade            : true,
        cssEase         : 'linear',
//adaptiveHeight: true,
        infinite        : true,
slidesToShow: 1,
autoplay: false,
autoplaySpeed: 2000,
arrows          : false,
        
});

var selected= $('#supplements-selected');
var supplements_amount= $('#supplements-amount');

var additive= $('#additive');

var card__info= $('#card__info');

var order_amount= $('#order-amount');
var product_count= $('#product-count');
var product_price= parseFloat(card__info.attr('data-price'));

page.on('update', function(){
console.log('page on update');

additive_price = 0;

for (var i in additive_list) {
//if(additive_list[i] != null){
var item= additive.find('.additive__card[data-id="'+additive_list[i].id+'"]');
var selected_item= selected.find('.included__additive__item[data-id="'+additive_list[i].id+'"]');

if(!additive_list[i].remove){
var amount = additive_list[i].price > 0 ? (additive_list[i].price * additive_list[i].count) : 0;

additive_price += amount;

if(selected_item.length > 0){
selected_item.find('input.count-number').val(additive_list[i].count);
}else{
item.addClass('act');

var html = '';

html += '<div class="included__additive__item" data-price="'+additive_list[i].price+'" data-id="'+additive_list[i].id+'">';
html += '<button class="remove-item" type="button">';
html += '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M9.40984 9.40034L14.5904 14.5809" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path d="M14.5928 9.39777L9.40732 14.5832" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M16.6857 2H7.31429C4.04762 2 2 4.31208 2 7.58516V16.4148C2 19.6879 4.0381 22 7.31429 22H16.6857C19.9619 22 22 19.6879 22 16.4148V7.58516C22 4.31208 19.9619 2 16.6857 2Z" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</button>';
html += '<span class="additive__name" style="width:190px;">'+additive_list[i].name+'</span>';
html += '<div class="card__item-count">';
html += '<button class="count-minus" type="button">';
html += '<svg width="16" height="3" viewBox="0 0 16 3" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M14.8516 0.5C15.3904 0.5 15.8272 1.00368 15.8272 1.625C15.8272 2.19454 15.4602 2.66524 14.984 2.73973L14.8516 2.75H1.8433C1.30448 2.75 0.867676 2.24632 0.867676 1.625C0.867676 1.05546 1.23471 0.584764 1.71091 0.51027L1.8433 0.5H14.8516Z" fill="#8ABB3B"/>';
html += '</svg>';
html += '</button>';
html += '<input class="count-number" value="'+additive_list[i].count+'" name="additive['+additive_list[i].id+']" type="number">';
html += '<button class="count-plus" type="button">';
html += '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M7.86895 15.75C8.40777 15.75 8.84457 15.312 8.84457 14.7717V9.22826H14.3731L14.5055 9.21933C14.9817 9.15455 15.3487 8.74525 15.3487 8.25C15.3487 7.70972 14.9119 7.27174 14.3731 7.27174H8.84457V1.72826L8.83567 1.59552C8.77106 1.11803 8.36287 0.75 7.86895 0.75C7.33012 0.75 6.89332 1.18798 6.89332 1.72826V7.27174H1.36478L1.2324 7.28067C0.756195 7.34545 0.38916 7.75474 0.38916 8.25C0.38916 8.79028 0.825962 9.22826 1.36478 9.22826H6.89332V14.7717L6.90222 14.9045C6.96683 15.382 7.37502 15.75 7.86895 15.75Z" fill="#8ABB3B"/>';
html += '</svg>';
html += '</button>';
html += '</div>';
html += '</div>';

selected.append(html);
};
}else{
item.removeClass('act');

selected_item.remove();

if(selected_item.length > 0){
selected_item.remove();
}

delete additive_list[i];
};
//}
};

if(additive.length > 0){
supplements_amount.text(number_format(additive_price, 2, '.', '')+' грн');
};

order_amount.text(number_format((additive_price + (product_count.val() * product_price)), 2, '.', '')+' грн');
});

page.trigger('update');

// additive

additive.on('click', '.additive__card__body', function(){
var current = $(this),
li = current.parent();

var id= li.attr('data-id'),
price= parseFloat(li.attr('data-price')),
name= li.attr('data-name');

if(li.hasClass('act')){
additive_list[id].remove = true;
}else{
additive_list[id] = {
id: id,
name: name,
price: price,
count: 1,
remove: false
};
};

page.trigger('update');
});
    
    additive.on('click', '.close-btn'            , function(){
var current = $(this),
li = current.parent();

var id= li.attr('data-id'),
price= parseFloat(li.attr('data-price')),
name= li.attr('data-name');

if(li.hasClass('act')){
additive_list[id].remove = true;
            additive_list[id].count = 0;
            
            additive.find('form[data-id="'+id+'"] .count-number').val(additive_list[id].count);
}else{
additive_list[id] = {
id: id,
name: name,
price: price,
count: 1,
remove: false
};
};

page.trigger('update');
});
    
    additive.on('click', '.count-minus'        , function(){
var current = $(this),
li = current.parents('.additive__card');

var id= li.attr('data-id'),
price= parseFloat(li.attr('data-price')),
name= li.attr('data-name');

        var input   = li.find('.count-number');
        
        var value   = parseFloat(input.val());
        
        if(value == 0){
            return false;
        }
        
        value--;
        
        input.val(value);
        
if(value < 1){
additive_list[id] = {
id: id,
name: name,
price: price,
count: value,
remove: true
};
}else{
additive_list[id] = {
id: id,
name: name,
price: price,
count: value,
remove: false
};
};

page.trigger('update');
});
    
    additive.on('click', '.count-plus'            , function(){
var current = $(this),
li = current.parents('.additive__card');

var id= li.attr('data-id'),
price= parseFloat(li.attr('data-price')),
name= li.attr('data-name');

        var input   = li.find('.count-number');
        
        var value   = parseFloat(input.val());
        
        value++;
        
        if(value > 9){
return false;
};
        
        input.val(value);
        
additive_list[id] = {
            id: id,
            name: name,
            price: price,
            count: value,
            remove: false
        };

page.trigger('update');
});

selected.on('click', '.included__additive__item .count-minus', function(){
console.log('.included__additive__item .count-minus');

var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-id');

additive_list[id].count -= 1;

        if(additive_list[id].count < 1){
            additive_list[id].count = 0;
            additive_list[id].remove = true;
        }
        
        additive.find('form[data-id="'+id+'"] .count-number').val(additive_list[id].count);
        
page.trigger('update');
});

selected.on('click', '.included__additive__item .count-plus', function(){
console.log('.included__additive__item .count-plus');

var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-id');

if(additive_list[id].count > 9){
return false;
};

additive_list[id].count += 1;

        additive.find('form[data-id="'+id+'"] .count-number').val(additive_list[id].count);
        
page.trigger('update');
});

selected.on('click', '.included__additive__item .remove-item', function(){
var current = $(this),
parent= current.parents('.included__additive__item');

var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-id');

additive_list[id].remove = true;

page.trigger('update');
});

selected.on('keyup', '.included__additive__item input.count-number', function(){
console.log('.included__additive__item input.count-number');

var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-id');

var count= current.val();

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

current.val(count);

additive_list[id].count = count;

page.trigger('update');
});

// product

card__info.on('click', '.count-minus', function(){
console.log('.form__item .count-minus');

var current = $(this);

var id= card__info.attr('data-id');

var count= product_count.val();
count--;

if(count < 1){
return false;
};

product_count.val(count);

page.trigger('update');
});

card__info.on('click', '.count-plus', function(){
console.log('.form__item .count-plus');

var current = $(this);

var id= card__info.attr('data-id');

var count= product_count.val();
count++;

if(count < 1){
return false;
};

product_count.val(count);

page.trigger('update');
});

product_count.on('keyup', function(){
console.log('product_count keyup');

var current = $(this);

var id= card__info.attr('data-id');

var count= parseInt(current.val());

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

current.val(count);

page.trigger('update');
});

// product-form

var product_form = $('#product-form');
var btn_add = product_form.find('button[type="submit"]');

product_form.on('submit', function(){
if(btn_add.attr('data-type') == 'add'){
$.ajax({
type: "POST",
url: "/ajax/cart/add",
data: product_form.serialize(),
dataType: "json",
beforeSend: function(request){
btn_add.attr('disabled', true);
},
success: function(response){
btn_add.attr('disabled', false);

if(response.status){
$('.cart-counter').text(response.payload.count);

var html = '';

html += '<span>';
html += '<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M13.9443 7.75424V5.22757C13.9443 3.4909 12.5406 2.0834 10.8095 2.0834C9.0775 2.0759 7.66715 3.47674 7.65967 5.2134V5.22757V7.75424" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M14.7496 17.5003H6.8672C4.91241 17.5003 3.32861 15.9128 3.32861 13.9545V9.35784C3.32861 7.39951 4.91241 5.81201 6.8672 5.81201H14.7496C16.7044 5.81201 18.2882 7.39951 18.2882 9.35784V13.9545C18.2882 15.9128 16.7044 17.5003 14.7496 17.5003Z" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</span>';
html += 'Видалити з корзини';

btn_add.html(html);
btn_add.attr('data-type', 'remove');
}
},
error: function(){
btn_add.attr('disabled', false);
}
});
};

if(btn_add.attr('data-type') == 'remove'){
$.ajax({
type: "POST",
url: "/ajax/cart/remove",
data: product_form.serialize(),
dataType: "json",
beforeSend: function(request){
btn_add.attr('disabled', true);
},
success: function(response){
btn_add.attr('disabled', false);

if(response.status){
$('.cart-counter').text(response.payload.count);

var html = '';

html += '<span>';
html += '<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M13.9443 7.75424V5.22757C13.9443 3.4909 12.5406 2.0834 10.8095 2.0834C9.0775 2.0759 7.66715 3.47674 7.65967 5.2134V5.22757V7.75424" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M14.7496 17.5003H6.8672C4.91241 17.5003 3.32861 15.9128 3.32861 13.9545V9.35784C3.32861 7.39951 4.91241 5.81201 6.8672 5.81201H14.7496C16.7044 5.81201 18.2882 7.39951 18.2882 9.35784V13.9545C18.2882 15.9128 16.7044 17.5003 14.7496 17.5003Z" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</span>';
html += 'Додати в корзину';

btn_add.html(html);
btn_add.attr('data-type', 'add');
}
},
error: function(){
btn_add.attr('disabled', false);
}
});
};

return false;
});
};

function catalog_list(){
var page = $('#catalog_list,#catalog_list_associated');

if(page.length < 1){
return false;
};

page.on('click', '.count-minus', function(){
var current = $(this),
parent= current.parents('.catalog__item--cart');

var id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price')),
count_input= parent.find('input.count-number');

var count = parseInt(count_input.val());

if(count < 2){
return false;
};

count -= 1;

count_input.val(count);

if(price > 0){
parent.parents('.catalog__item--header').find('.card__info__price').text(number_format(price * count, 2, '.', '')+' грн');
}
});

page.on('click', '.count-plus', function(){
var current = $(this),
parent= current.parents('.catalog__item--cart');

var id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price')),
count_input= parent.find('input.count-number');

var count = parseInt(count_input.val());

if(count > 9){
return false;
};

count += 1;

count_input.val(count);

if(price > 0){
parent.parents('.catalog__item--header').find('.card__info__price').text(number_format(price * count, 2, '.', '')+' грн');
}
});

page.on('keyup', 'input.count-number', function(){
var count_input = $(this),
parent= count_input.parents('.catalog__item--cart');

var id= count_input.attr('data-id'),
price= parseFloat(count_input.attr('data-price'));

var count = parseInt(count_input.val());

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

count_input.val(count);

if(price > 0){
parent.parents('.catalog__item--header').find('.card__info__price').text(number_format(price * count, 2, '.', '')+' грн');
}
});

page.on('submit', '.catalog__item--cart', function(){
var product_form = $(this);
        
        var parent  = product_form.parents('.catalog__item--header'),
            product = parent.parent();
        
var id= product_form.parents('.catalog__item').attr('data-id');
var btn_add = product.find('button.card__info--btn');

if(btn_add.attr('data-type') == 'add'){
$.ajax({
type: "POST",
url: "/ajax/cart/add",
data: product_form.serialize(),
dataType: "json",
beforeSend: function(request){
btn_add.attr('disabled', true);
},
success: function(response){
btn_add.attr('disabled', false);

if(response.status){
$('.cart-counter').text(response.payload.count);

var html = '';

html += '<span>';
html += '<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M13.9443 7.75424V5.22757C13.9443 3.4909 12.5406 2.0834 10.8095 2.0834C9.0775 2.0759 7.66715 3.47674 7.65967 5.2134V5.22757V7.75424" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M14.7496 17.5003H6.8672C4.91241 17.5003 3.32861 15.9128 3.32861 13.9545V9.35784C3.32861 7.39951 4.91241 5.81201 6.8672 5.81201H14.7496C16.7044 5.81201 18.2882 7.39951 18.2882 9.35784V13.9545C18.2882 15.9128 16.7044 17.5003 14.7496 17.5003Z" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</span>';
html += 'Видалити з корзини';

btn_add.html(html);
btn_add.attr('data-type', 'remove');

if(response.payload.check_supplements){
var modal = $('#supplements-modal');

modal.attr('data-id', id);
modal.trigger('load');
}
}
},
error: function(){
btn_add.attr('disabled', false);
}
});
};

if(btn_add.attr('data-type') == 'remove'){
$.ajax({
type: "POST",
url: "/ajax/cart/remove",
data: product_form.serialize(),
dataType: "json",
beforeSend: function(request){
btn_add.attr('disabled', true);
},
success: function(response){
btn_add.attr('disabled', false);

if(response.status){
$('.cart-counter').text(response.payload.count);

var html = '';

html += '<span>';
html += '<svg width="21" height="20" viewBox="0 0 21 20" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M13.9443 7.75424V5.22757C13.9443 3.4909 12.5406 2.0834 10.8095 2.0834C9.0775 2.0759 7.66715 3.47674 7.65967 5.2134V5.22757V7.75424" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M14.7496 17.5003H6.8672C4.91241 17.5003 3.32861 15.9128 3.32861 13.9545V9.35784C3.32861 7.39951 4.91241 5.81201 6.8672 5.81201H14.7496C16.7044 5.81201 18.2882 7.39951 18.2882 9.35784V13.9545C18.2882 15.9128 16.7044 17.5003 14.7496 17.5003Z" stroke="#8ABB3B" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</span>';
html += 'Додати в корзину';

btn_add.html(html);
btn_add.attr('data-type', 'add');
}
},
error: function(){
btn_add.attr('disabled', false);
}
});
};

return false;
});
    
    page.on('click', 'button.card__info--btn', function(){
        var btn = $(this);
        
        var item = btn.parents('.catalog__item');
        
        var form = item.find('form.catalog__item--cart');
        
        form.trigger('submit');
    });
};

function accordion(){
var el = $('.accordion__container');

if (el.length < 1) {
return false;
};

// (Optional) Active an item if it has the class "is-active"
$(".accordion__container > .accordion-item.is-active").children(".accordion-panel").slideDown();

$(".accordion__container > .accordion-item").click(function () {
// Cancel the siblings
$(this).siblings(".accordion-item").removeClass("is-active").children(".accordion-panel").slideUp();
// Toggle the item
$(this).toggleClass("is-active").children(".accordion-panel").slideToggle("ease-out");
});
};

function leaflet_map_initialize(){
var container = $('#map');

if (!container.length) {
return false;
};

var el = document.getElementById("map");
var lat = container.data('lat');
var lng = container.data('lng');

var map = L.map("map", {
center: [
lat,
lng
],
zoom: 14,
});

L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 19
}).addTo(map);

var markersLayer = new L.LayerGroup();

map.addLayer(markersLayer);

var customIcon = L.icon({
iconUrl: '../img/svg/marker.svg',
iconSize: [39, 51],
iconAnchor: [39, 51],
});

var marker = L.marker(
[lat, lng],
{
icon: customIcon
}
);

marker.addTo(markersLayer);
};

function setOrder(){
var el = $('#order-wrp');

if(el.length < 1){
return false;
};

var order_form= $('#order_form');

var delivery_price_wrap = $('#delivery-price');
var delivery_type= $('#delivery_type');
var address= $('#address');
var address_wrap= $('#address-wrap');
var branches= $('#branches');
var branches_wrap= $('#branches-wrap');
var payment_type_wrap= $('#payment-type');

var cart_total= $('#cart-total');
var total= $('#total');

var order_btn= $('#order-btn'),
order_btn_mob= $('#order-btn-mob');

var wrap_right= $('#wrap-right'),
wrap_mob= $('#wrap-mob');

var amount= 0;

var min= parseFloat(order_form.attr('data-min-price'));

var delivery_to= parseFloat(order_form.attr('data-delivery-to'));
var delivery_to_price= parseFloat(order_form.attr('data-delivery-to-price'));

var delivery_from= parseFloat(order_form.attr('data-delivery-from'));
var delivery_from_price= parseFloat(order_form.attr('data-delivery-from-price'));

delivery_type.on('change', 'input', function(){
var current = $(this),
value= current.val();

delivery_type.find('label.act').removeClass('act');

var current_total= cart_total.text().replace(' грн').trim();
current_total= parseFloat(current_total);

delivery_type.attr('data-type', value);

if(value == 'pickup'){
current.parent().addClass('act');

delivery_price_wrap.find('.new-price').text('0 грн');

address_wrap.hide();
address.attr('required', false);
address.val('');

branches_wrap.show();

total.text(number_format(current_total, 2, '.', '')+' грн');
}

if(value != 'pickup'){
current.parent().addClass('act');

branches_wrap.hide();

address.attr('required', true);
address_wrap.show();

if(current_total > 0){
if(current_total < min && min > 0){
delivery_price_wrap.find('.new-price').text('0 грн');
}else{
var delivery_price = 0;

if(delivery_to > 0 && current_total <= delivery_to){
delivery_price= delivery_to_price;
}

if(delivery_from > 0 && current_total > delivery_from){
delivery_price= delivery_from_price;
}

if(delivery_price){
current_total += delivery_price;
}

delivery_price_wrap.find('.new-price').text(delivery_price+' грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}

total.text(number_format(current_total, 2, '.', '')+' грн');
}
});

payment_type_wrap.on('change', 'input', function(){
var current = $(this);

payment_type_wrap.find('label.act').removeClass('act');

current.parent().addClass('act');
});

branches.on('change', 'input', function(){
var current = $(this);

branches.find('label.act').removeClass('act');

current.parent().addClass('act');
});

//

order_form.on('click', '.included__additive__item .count-minus', function(){
var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-parent_id'),
child_id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count_inp= parent.find('.count-number');

var count= parseInt(count_inp.val());

if(count < 2){
return false;
};

count--;

count_inp.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartChild(id, count, child_id, parent);

return false;
});

order_form.on('click', '.included__additive__item .count-plus', function(){
var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-parent_id'),
child_id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count_inp= parent.find('.count-number');

var count= parseInt(count_inp.val());

if(count > 9){
return false;
};

count++;

count_inp.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartChild(id, count, child_id, parent);

return false;
});

order_form.on('keyup', '.included__additive__item .count-number', function(){
var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-parent_id'),
child_id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count= parseInt(current.val());

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

current.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartChild(id, count, child_id, parent);

return false;
});

order_form.on('click', '.included__additive__item .remove-item', function(){
var current = $(this),
parent= current.parents('.included__additive__item');

var id= parent.attr('data-parent_id'),
child_id= parent.attr('data-id');

parent.remove();

removeCartChild(id, child_id, parent);

return false;
});

//

order_form.on('click', '.order__body .count-minus', function(){
var current = $(this),
parent= current.parents('.order__item');

var id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count_inp= parent.find('.count-number');

var count= parseInt(count_inp.val());

if(count < 2){
return false;
};

count--;

count_inp.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartProduct(id, count, parent);

return false;
});

order_form.on('click', '.order__body .count-plus', function(){
var current = $(this),
parent= current.parents('.order__item');

var id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count_inp= parent.find('.count-number');

var count= parseInt(count_inp.val());

if(count > 9){
return false;
};

count++;

count_inp.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartProduct(id, count, parent);

return false;
});

order_form.on('keyup', '.order__body .count-number', function(){
var current = $(this),
parent= current.parents('.order__item');

var id= parent.attr('data-id'),
price= parseFloat(parent.attr('data-price'));

var count= parseInt(current.val());

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

current.val(count);

parent.find('.order__price').text(number_format((count * price), 2, '.', '')+' грн');

updateCartProduct(id, count, parent);

return false;
});

order_form.on('click', '.order__body .order__cancel', function(){
var current = $(this),
parent= current.parents('.order__item');

var id= parent.attr('data-id');

parent.remove();
$('.order__additive[data-id="'+id+'"]').remove();

removeCartProduct(id, parent);

return false;
});

//

var lock = false;

order_form.validate({
onkeyup: function(element){
var item = $(element);

if(item.hasClass('error')){
$(element).valid();
}
},
focusCleanup: false,
submitHandler: function(e){
console.log('submitHandler');

if(!lock){
//e.preventDefault();

$.ajax({
type: "POST",
url: '/ajax/cart/order',
data: order_form.serialize(),
dataType: "json",
beforeSend: function(request){
lock = true;

order_btn.attr('disabled', true);
order_btn_mob.attr('disabled', true);

$('.status-message').remove();
},
success: function(response){
if(response.status){
order_form.trigger('reset');

amount = 0;

$('#order__items').html('');

cart_total.text('0.00 грн');
total.text('0.00 грн');

cart_total.text('0.00 грн');
total.text('0.00 грн');

$('.header__cart .cart-counter').attr('data-cart-items', '0').text('0');
$('#cart_count').text('0');

console.log('payload:', response.payload);

if(response.payload.payment == "cashless_payment"){
location.href = response.payload.url;

return false;
}else{
var orderTotal = Number(response.payload.value);

console.log('orderTotal:', orderTotal);

console.log('fbq:', fbq);
console.log('typeof:', typeof fbq);

if(typeof fbq === 'function' && orderTotal > 0){
fbq('track', 'Purchase', {
value: orderTotal,
currency: 'UAH'
});
}

$('#order-modal').arcticmodal({
// Перед открытием окна
beforeOpen: function(data, el) {
console.log('beforeOpen');

$('#order-modal').show();
},
// После отображения окна
afterOpen: function(data, el) {
console.log('afterOpen');
},
// Перед закрытием окна
beforeClose: function(data, el) {
console.log('beforeClose');

$('#order-modal').hide();
},
// После закрытия окна
afterClose: function(data, el) {
console.log('afterClose');
}
});
}
}else{
if(wrap_mob.is(":visible")){
order_btn_mob.after(`<div class="status-message"> ${response.mesasge} </div>`);
}else{
order_btn.after(`<div class="status-message"> ${response.mesasge} </div>`);
}

lock = false;
    
    order_btn.attr('disabled', false);
    order_btn_mob.attr('disabled', false);
};

setTimeout(function(){
$('.status-message').remove();

lock = false;
    
    order_btn.attr('disabled', false);
    order_btn_mob.attr('disabled', false);
}, 5000)
},
error: function(){
lock = false;

order_btn.attr('disabled', false);
order_btn_mob.attr('disabled', false);

if(wrap_mob.is(":visible")){
order_btn_mob.after(`<div class="status-message">Сталась помилка</div>`);
}else{
order_btn.after(`<div class="status-message">Сталась помилка</div>`);
};

setTimeout(function(){
$('.status-message').remove();
}, 8000);
}
});
};

return false;
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 50,
},
tel: {
required: true,
minlength: 13,
maxlength: 13
},
number: {
required: false,
digits: true,
minlength: 10,
maxlength: 10,
},
comment: {
required: false,
maxlength: 500,
},
address: {
required: false,
minlength: 5,
maxlength: 150
},
},
messages: {
name: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
tel: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
number: {
required: "Поле обов'язкове для заповнення",
digits: "Тільки цифри",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
comment: {
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
address: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
}
});

order_form.on('blur keyup change', 'input', function(event){
validateForm(order_form);
});

var commentField = $('#comment-field');
var commentIcon = $('#comment-icon');

commentField.on('blur keyup change', function(event){
if(commentField.val().length > 0){
    commentIcon.hide();
}else{
    commentIcon.show();
}
});

getLocation();
};

function getLocation(){
var btn= $('#location-btn');
var input= $('#address');
var key= btn.attr('data-key');

var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};

btn.on('click', function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(pos) => {
var crd = pos.coords;

//console.log('Ваше текущее местоположение:');
//console.log(`Широта: ${crd.latitude}`);
//console.log(`Долгота: ${crd.longitude}`);
//console.log(`Плюс-минус ${crd.accuracy} метров.`);

var latlng = {
lat: parseFloat(crd.latitude),
lng: parseFloat(crd.longitude),
};

var geocoder = new google.maps.Geocoder();

geocoder.geocode({ location: latlng }, function(response, status) {
if(status == 'OK' && response.length > 0){
var street_number= "";
var address= "";
var components= [];

for(var i = 0; i < response[0].address_components.length; i++){
var item = response[0].address_components[i];

if(item.types[0] == "street_number"){
street_number = item.long_name;
};

if(item.types[0] == "route"){
address = item.long_name;
}
};

if(address){
components.push(address);
};

if(street_number){
components.push(street_number);
};

input.val(components.join(', '));
}else{
input.val('');
}
});
},
(err) => {
input.val('');

console.warn(`ERROR(${err.code}): ${err.message}`);
},
options
);
}
});
};

function updateCartProduct(id, count, parent){
console.log('updateCartProduct:');

var form = $('#order_form');

var min= parseFloat(form.attr('data-min-price'));

var delivery_to= parseFloat(form.attr('data-delivery-to'));
var delivery_to_price= parseFloat(form.attr('data-delivery-to-price'));

var delivery_from= parseFloat(form.attr('data-delivery-from'));
var delivery_from_price= parseFloat(form.attr('data-delivery-from-price'));

console.log('min:', min);

console.log('delivery_to:', delivery_to);
console.log('delivery_to_price:', delivery_to_price);

console.log('delivery_from:', delivery_from);
console.log('delivery_from_price:', delivery_from_price);

$.ajax({
type: "POST",
url: "/ajax/cart/update",
data: {
id: id,
count: count,
child_id: 0,
},
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
$('#cart-total').text(number_format(response.payload.amount, 2, '.', '')+' грн');
$('#cart_count').text(response.payload.count);

var cart_total= $('#cart-total');
var total= $('#total');

var delivery_type= $('#delivery_type');

var amount = response.payload.amount;

var delivery_price_wrap= $('#delivery-price');

if(delivery_type.attr('data-type') == 'delivery'){
if(amount > 0){
if(amount < min && min > 0){
delivery_price_wrap.find('.new-price').text('0 грн');
}else{
var delivery_price = 0;

if(delivery_to > 0 && amount <= delivery_to){
delivery_price= delivery_to_price;
}

if(delivery_from > 0 && amount > delivery_from){
delivery_price= delivery_from_price;
}

if(delivery_price){
amount += delivery_price;
}

delivery_price_wrap.find('.new-price').text(delivery_price+' грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}

total.text(number_format(amount, 2, '.', '')+' грн');
}
},
error: function(){
}
});
};

function updateCartChild(id, count, child_id, parent){
var form = $('#order_form');

var min= parseFloat(form.attr('data-min-price'));

var delivery_to= parseFloat(form.attr('data-delivery-to'));
var delivery_to_price= parseFloat(form.attr('data-delivery-to-price'));

var delivery_from= parseFloat(form.attr('data-delivery-from'));
var delivery_from_price= parseFloat(form.attr('data-delivery-from-price'));

$.ajax({
type: "POST",
url: "/ajax/cart/update",
data: {
id: id,
count: count,
child_id: child_id,
},
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
$('#cart-total').text(number_format(response.payload.amount, 2, '.', '')+' грн');
$('#cart_count').text(response.payload.count);

var cart_total= $('#cart-total');
var total= $('#total');

var delivery_type= $('#delivery_type');

var amount = response.payload.amount;

var delivery_price_wrap= $('#delivery-price');

if(delivery_type.attr('data-type') == 'delivery'){
if(amount > 0){
if(amount < min && min > 0){
delivery_price_wrap.find('.new-price').text('0 грн');
}else{
var delivery_price = 0;

if(delivery_to > 0 && amount <= delivery_to){
delivery_price= delivery_to_price;
}

if(delivery_from > 0 && amount > delivery_from){
delivery_price= delivery_from_price;
}

if(delivery_price){
amount += delivery_price;
}

delivery_price_wrap.find('.new-price').text(delivery_price+' грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}

total.text(number_format(amount, 2, '.', '')+' грн');
}
},
error: function(){
}
});
};

function removeCartProduct(id, parent){
var form = $('#order_form');

var min= parseFloat(form.attr('data-min-price'));

var delivery_to= parseFloat(form.attr('data-delivery-to'));
var delivery_to_price= parseFloat(form.attr('data-delivery-to-price'));

var delivery_from= parseFloat(form.attr('data-delivery-from'));
var delivery_from_price= parseFloat(form.attr('data-delivery-from-price'));

$.ajax({
type: "POST",
url: "/ajax/cart/remove",
data: {
id: id,
child_id: 0,
},
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
$('#cart-total').text(number_format(response.payload.amount, 2, '.', '')+' грн');
$('#cart_count').text(response.payload.count);

var cart_total= $('#cart-total');
var total= $('#total');

var delivery_type= $('#delivery_type');

var amount = response.payload.amount;

var delivery_price_wrap= $('#delivery-price');

if(delivery_type.attr('data-type') == 'delivery'){
if(amount > 0){
if(amount < min && min > 0){
delivery_price_wrap.find('.new-price').text('0 грн');
}else{
var delivery_price = 0;

if(delivery_to > 0 && amount <= delivery_to){
delivery_price= delivery_to_price;
}

if(delivery_from > 0 && amount > delivery_from){
delivery_price= delivery_from_price;
}

if(delivery_price){
amount += delivery_price;
}

delivery_price_wrap.find('.new-price').text(delivery_price+' грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}

total.text(number_format(amount, 2, '.', '')+' грн');
}
},
error: function(){
}
});
};

function removeCartChild(id, child_id, parent){
var form = $('#order_form');

var min= parseFloat(form.attr('data-min-price'));

var delivery_to= parseFloat(form.attr('data-delivery-to'));
var delivery_to_price= parseFloat(form.attr('data-delivery-to-price'));

var delivery_from= parseFloat(form.attr('data-delivery-from'));
var delivery_from_price= parseFloat(form.attr('data-delivery-from-price'));

$.ajax({
type: "POST",
url: "/ajax/cart/remove",
data: {
id: id,
child_id: child_id,
},
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
$('#cart-total').text(number_format(response.payload.amount, 2, '.', '')+' грн');
$('#cart_count').text(response.payload.count);

var cart_total= $('#cart-total');
var total= $('#total');

var delivery_type= $('#delivery_type');

var amount = response.payload.amount;

var delivery_price_wrap= $('#delivery-price');

if(delivery_type.attr('data-type') == 'delivery'){
if(amount > 0){
if(amount < min && min > 0){
delivery_price_wrap.find('.new-price').text('0 грн');
}else{
var delivery_price = 0;

if(delivery_to > 0 && amount <= delivery_to){
delivery_price= delivery_to_price;
}

if(delivery_from > 0 && amount > delivery_from){
delivery_price= delivery_from_price;
}

if(delivery_price){
amount += delivery_price;
}

delivery_price_wrap.find('.new-price').text(delivery_price+' грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}
}else{
delivery_price_wrap.find('.new-price').text('0 грн');
}

total.text(number_format(amount, 2, '.', '')+' грн');
}
},
error: function(){
}
});
};

//

function supplements_modal(){
var modal = $('#supplements-modal');

if(modal.length < 1){
return false;
};

var container= $('#modal-supplements-container');
var btn= modal.find('.card__info--btn');

var modal_total= $('#modal-total');

modal.on('load', function(){
$.ajax({
type: "GET",
url: "/ajax/cart/supplements?id="+modal.attr('data-id'),
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
modal.children('.modal__title').text('Додати добавки ('+response.payload.category.name+')');

modal_total.text('0.00');

container.html('');

var html = '';
var item;

var total = 0;

for(var i = 0; i < response.payload.supplements.length; i++){
item = response.payload.supplements[i];

html += '<div class="included__additive__item" data-status="0" data-price="'+item.price+'" data-parent_id="'+response.payload.product.id+'" data-id="'+item.id+'">';
html += '<span class="additive__name '+(item.cart ? "active-item":"")+'">'+item.name+'</span>';

html += '<div class="card__item-group">';
html += '<div class="card__item-count">';
html += '<button class="count-minus" type="button">';
html += '<svg width="16" height="3" viewBox="0 0 16 3" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M14.8516 0.5C15.3904 0.5 15.8272 1.00368 15.8272 1.625C15.8272 2.19454 15.4602 2.66524 14.984 2.73973L14.8516 2.75H1.8433C1.30448 2.75 0.867676 2.24632 0.867676 1.625C0.867676 1.05546 1.23471 0.584764 1.71091 0.51027L1.8433 0.5H14.8516Z" fill="#8ABB3B"/>';
html += '</svg>';
html += '</button>';

html += '<input class="count-number" value="'+item.count+'" name="additive['+response.payload.product.id+']['+item.id+']" type="number">';

html += '<button class="count-plus" type="button">';
html += '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M7.86895 15.75C8.40777 15.75 8.84457 15.312 8.84457 14.7717V9.22826H14.3731L14.5055 9.21933C14.9817 9.15455 15.3487 8.74525 15.3487 8.25C15.3487 7.70972 14.9119 7.27174 14.3731 7.27174H8.84457V1.72826L8.83567 1.59552C8.77106 1.11803 8.36287 0.75 7.86895 0.75C7.33012 0.75 6.89332 1.18798 6.89332 1.72826V7.27174H1.36478L1.2324 7.28067C0.756195 7.34545 0.38916 7.75474 0.38916 8.25C0.38916 8.79028 0.825962 9.22826 1.36478 9.22826H6.89332V14.7717L6.90222 14.9045C6.96683 15.382 7.37502 15.75 7.86895 15.75Z" fill="#8ABB3B"/>';
html += '</svg>';
html += '</button>';
html += '</div>';

html += '<div class="order__price order__price--mob" data-price="'+item.price+'">'+item.price+' грн</div>';

html += '<button class="add-item" type="button" '+(item.cart ? 'style="display:none;"' : '')+'>';
html += '<img src="/img/checked-21x22.png" width="21" height="22" alt="Додати" />';
html += '</button>';

html += '<button class="remove-item" type="button" '+(item.cart ? '' : 'style="display:none;"')+'>';
html += '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
html += '<path d="M9.40984 9.40034L14.5904 14.5809" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path d="M14.5928 9.39777L9.40732 14.5832" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '<path fill-rule="evenodd" clip-rule="evenodd" d="M16.6857 2H7.31429C4.04762 2 2 4.31208 2 7.58516V16.4148C2 19.6879 4.0381 22 7.31429 22H16.6857C19.9619 22 22 19.6879 22 16.4148V7.58516C22 4.31208 19.9619 2 16.6857 2Z" stroke="#E64047" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
html += '</svg>';
html += '</button>';

html += '</div>';
html += '</div>';

if(item.cart){
total += (item.price * item.count);
}
};

container.html(html);

modal_total.text(number_format(total, 2, '.', ''));

modal.arcticmodal({
beforeOpen: function(data, el) {
modal.show();
},
beforeClose: function(data, el) {
modal.hide();
},
});
}
},
error: function(){
}
});
});

container.on('click', '.add-item', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

var count= parseInt(parent.find('input.count-number').val());

if(count < 1){
count++;

parent.find('input.count-number').val(count);
};

$.ajax({
type: "POST",
url: "/ajax/cart/add",
data: 'id='+parent_id+'&child_id='+id+'&count='+count,
dataType: "json",
beforeSend: function(request){
current.attr('disabled', true);
},
success: function(response){
current.attr('disabled', false);

if(response.status){
current.hide();

parent.find('.additive__name').addClass('active-item');

parent.find('.remove-item').show();

parent.attr('data-status', 1);

modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
current.attr('disabled', false);
}
});
});

container.on('click', '.additive__name', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

var count= parseInt(parent.find('input.count-number').val());

if(count < 1){
count++;

parent.find('input.count-number').val(count);
};

$.ajax({
type: "POST",
url: "/ajax/cart/add",
data: 'id='+parent_id+'&child_id='+id+'&count='+count,
dataType: "json",
beforeSend: function(request){
},
success: function(response){
if(response.status){
parent.find('.add-item').hide();
parent.find('.remove-item').show();

current.addClass('active-item');

parent.attr('data-status', 1);

modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
}
});
});

container.on('click', '.remove-item', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

$.ajax({
type: "POST",
url: "/ajax/cart/remove",
data: 'id='+parent_id+'&child_id='+id,
dataType: "json",
beforeSend: function(request){
current.attr('disabled', true);
},
success: function(response){
current.attr('disabled', false);

if(response.status){
current.hide();

parent.find('.additive__name').removeClass('active-item');

parent.find('.add-item').show();

parent.find('input.count-number').val('0');

parent.attr('data-status', 0);

modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
current.attr('disabled', false);
}
});
});

container.on('click', '.count-minus', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

var count_inp= parent.find('input.count-number');

var count = count_inp.val();
count--;

if(count < 1){
return false;
};

count_inp.val(count);

if(parseInt(parent.attr('data-status')) != 1){
return false;
};

$.ajax({
type: "POST",
url: "/ajax/cart/update",
data: 'id='+parent_id+'&child_id='+id+'&count='+count,
dataType: "json",
beforeSend: function(request){
current.attr('disabled', true);
},
success: function(response){
current.attr('disabled', false);

if(response.status){
modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
current.attr('disabled', false);
}
});
});

container.on('click', '.count-plus', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

var count_inp= parent.find('input.count-number');

var count = count_inp.val();
count++;

if(count > 10){
return false;
};

count_inp.val(count);

if(parseInt(parent.attr('data-status')) != 1){
parent.find('.add-item').trigger('click');

return false;
};

$.ajax({
type: "POST",
url: "/ajax/cart/update",
data: 'id='+parent_id+'&child_id='+id+'&count='+count,
dataType: "json",
beforeSend: function(request){
current.attr('disabled', true);
},
success: function(response){
current.attr('disabled', false);

if(response.status){
modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
current.attr('disabled', false);
}
});
});

container.on('keyup', 'input.count-number', function(){
var current = $(this);
var parent = current.parents('.included__additive__item');

var parent_id= parent.attr('data-parent_id');
var id= parent.attr('data-id');

var count_inp= parent.find('input.count-number');

var count = count_inp.val();

if(count > 10){
count = 10;
}else if(count < 1){
count = 1;
};

count_inp.val(count);

if(parseInt(parent.attr('data-status')) != 1){
return false;
};

$.ajax({
type: "POST",
url: "/ajax/cart/update",
data: 'id='+parent_id+'&child_id='+id+'&count='+count,
dataType: "json",
beforeSend: function(request){
current.attr('disabled', true);
},
success: function(response){
current.attr('disabled', false);

if(response.status){
modal_total.text(number_format(response.payload.amount_supplements, 2, '.', ''));
}
},
error: function(){
current.attr('disabled', false);
}
});
});

modal.on('click', '.card__info--btn', function(){
window.location.href = '/cart';
});
};

//

function registration(){
var el = $('#reg-wrp');

if(el.length < 1){
return false;
};

var reg_form= $('#reg_form');
var save_btn= $('#save-btn');

var lock = false;

reg_form.validate({
onkeyup: function(element){
var item = $(element);

if(item.hasClass('error')){
$(element).valid();
}
},
focusCleanup: false,
submitHandler: function(e){
console.log('submitHandler');

if(!lock){
//e.preventDefault();

$.ajax({
type: "POST",
url: '/ajax/registration',
data: reg_form.serialize(),
dataType: "json",
beforeSend: function(request){
lock = true;

save_btn.attr('disabled', true);

$('.status-message').remove();
},
success: function(response){
lock = false;

save_btn.attr('disabled', false);

if(response.status){
reg_form.trigger('reset');

$('#reg-modal').arcticmodal({
// Перед открытием окна
beforeOpen: function(data, el) {
console.log('beforeOpen');

$('#reg-modal').show();
},
// После отображения окна
afterOpen: function(data, el) {
console.log('afterOpen');
},
// Перед закрытием окна
beforeClose: function(data, el) {
console.log('beforeClose');

$('#reg-modal').hide();
},
// После закрытия окна
afterClose: function(data, el) {
console.log('afterClose');
}
});
}else{
save_btn.after(`<div class="status-message"> ${response.mesasge} </div>`);
};

setTimeout(function(){
$('.status-message').remove();
}, 5000)
},
error: function(){
lock = false;

save_btn.attr('disabled', false);

save_btn.after(`<div class="status-message"> ${response.mesasge} </div>`);

setTimeout(function(){
$('.status-message').remove();
}, 8000);
}
});
};

return false;
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 30,
},
surname: {
required: false,
minlength: 2,
maxlength: 30,
},
patronymic: {
required: false,
minlength: 2,
maxlength: 30,
},
tel: {
required: true,
minlength: 13,
maxlength: 13
},
email: {
required: false,
email: true
},
number: {
required: false,
digits: true,
minlength: 10,
maxlength: 10,
},
code: {
required: false,
maxlength: 100,
},
},
messages: {
name: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
surname: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
patronymic: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
tel: {
required: "Поле обов'язкове для заповнення",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
email: {
required: "Поле обов'язкове для заповнення",
email: "Email вказано некоректно",
},
number: {
required: "Поле обов'язкове для заповнення",
digits: "Тільки цифри",
minlength: jQuery.validator.format("Мінімум {0} символів"),
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
code: {
maxlength: jQuery.validator.format("Максимум {0} символів"),
},
}
});

reg_form.on('blur keyup change', 'input', function(event){
validateForm(reg_form);
});
};

//

function saveOrderForm(){
localStorage.setItem('inputName', $('input[name="name"]').val());
localStorage.setItem('inputTel', $('input[name="tel"]').val());
localStorage.setItem('inputComment', $('input[name="comment"]').val());

localStorage.setItem('inputStreet', $('input[name="street"]').val());
localStorage.setItem('inputHouse', $('input[name="house"]').val());
localStorage.setItem('inputApartment', $('input[name="apartment"]').val());
};

function validateForm(form){
var valid = form.validate().checkForm();

if(!valid){
form.find('button[type="submit"]').prop('disabled', 'disabled');
};

form.find('button[type="submit"]').prop('disabled', false);
};

$(function maskPhone(){
var el = $('.tel-wrap input[type="tel"]');

if(!el.length){
return false;
};

el.mask('+389999999999');
});

$(function memuOpen(){
var menuBtn = $(".menu-btn");
var menu = $('.menu');

if(!menu.length){
return false
};

$(menuBtn).click(function(){
menu.show();

$('body').addClass('hidden');

menu.removeClass('menu-btn');
});

$(".is-active ").click(function(){
menu.addClass('menu-btn');
menu.hide();

$('body').removeClass('hidden');
});

$('.mob-nav a').click(function(){
menu.addClass('menu-btn');
menu.hide();

$('body').removeClass('hidden');
});
});

$(function showText(){
$('.info__link').click(function(){
$(this).closest('.info__wrap').find('.info__text p').removeClass('hide');

$(this).hide();
});
});

async function bindAutocompleteOld(){
var inputs = document.querySelector('#street');

var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(52.3718351926436, 20.812623315326388),
new google.maps.LatLng(52.09386026009501, 21.282288835254104)
);

var options = {
//input: inputs,
bounds: cityBounds,
types: ['address'],
componentRestrictions: { country: "ua" },
};



var autocomplete = new google.maps.places.Autocomplete(inputs, options);


};

function bindAutocomplete(){
if (!String.prototype.trim) {
// Вырезаем BOM и неразрывный пробел
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
};

var acService = new google.maps.places.AutocompleteService(),
placesService = new google.maps.places.PlacesService(document.createElement('div'));

var input = $('#street');

var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(52.3718351926436, 20.812623315326388),
new google.maps.LatLng(52.09386026009501, 21.282288835254104)
);

var options = {
input: "",
bounds: cityBounds,
types: ['geocode'],
fields: ["name", "address_component", "formatted_address", "geometry.location"],
componentRestrictions: { country: "ua" },
};

var location = new google.maps.LatLng(52.1716073, 21.1692158);

//placesService.setFields(options.fields);

input.autocomplete({
source: function (req, resp) {
//acService.getPlacePredictions(
acService.getQueryPredictions(
{
input: req.term,
radius: 18500,
location: location,
types: options.types,
fields: options.fields,
componentRestrictions: options.componentRestrictions,
},
function (places, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var _places = [];

for (var i = 0; i < places.length; ++i) {
var allowed = false;
var name = places[i].description.split(',');

for (var j = 0; j < name.length; ++j) {
name[j] = name[j].trim();

if (name[j] == "Warszawa") {
allowed = true;
}
};

if (allowed) {
_places.push({
id: places[i].place_id,
value: name[0],
label: name[0]
});
};
};

resp(_places);
}
}
);
},
select: function (e, o) {

}
});
};

function initializeAutocompleteService(){
var inputs = document.querySelector('#street');

var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(52.3718351926436, 20.812623315326388),
new google.maps.LatLng(52.09386026009501, 21.282288835254104)
);

var options = {
input: inputs,
bounds: cityBounds,
types: ['geocode'],
componentRestrictions: { country: "pl" },
};

const displaySuggestions = function (predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {
alert(status);
return;
};

predictions.forEach((prediction) => {
const li = document.createElement("li");

li.appendChild(document.createTextNode(prediction.description));

document.getElementById("results").appendChild(li);
});
};

const service = new google.maps.places.AutocompleteService();

service.getQueryPredictions(options, displaySuggestions);
};

function updateCount(count){
var items = $('a.header__cart');

$.each(items, function(i, el){
el = $(el);

var span = el.next();

if(count > 0){
span.text(count);
span.removeClass('hide-count');
}else{
span.addClass('hide-count');
span.text(count);
}
});
};

function initMap(){
var el = $('#map');

if(el.length < 1){
return false;
};

console.log(branches);

var map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 49.4363386,
lng: 26.9810086
},
zoom: 13,
});

for (let i = 0; i < branches.length; i++) {
var item = branches[i];

new google.maps.Marker({
position: {
lat: item.lat, 
lng: item.lng
},
map,
title: item.address,
icon: '/img/location-48.svg',
});
}
};

function checkCookies(){
return false;

let cookieDate = localStorage.getItem('cookieDate');
let cookieNotification = document.getElementById('cookie_notification');
let cookieBtn = cookieNotification.querySelector('.cookie_accept');

// Если записи про кукисы нет или она просрочена на 1 год, то показываем информацию про кукисы
if( !cookieDate || (+cookieDate + 31536000000) < Date.now() ){
cookieNotification.classList.add('show');
};

// При клике на кнопку, в локальное хранилище записывается текущая дата в системе UNIX
cookieBtn.addEventListener('click', function(){
localStorage.setItem( 'cookieDate', Date.now() );
cookieNotification.classList.remove('show');
});
}
