// source --> https://helixxfoods.ca/wp-content/plugins/bopo-woocommerce-product-bundle-builder/js/bopo-frontend.js?ver=1.1.9 
document.addEventListener('DOMContentLoaded', function () {
    bopobb_no_atc_ajax();
});

function bopobb_no_atc_ajax() {
    let is_bopobb = false;
    if (jQuery('.bopobb-single-wrap').length) is_bopobb = true;
    if (document.body.classList.contains('ajax-single-add-to-cart') && document.body.classList.contains('theme-zoa') && is_bopobb) {
        jQuery(document.body).removeClass('ajax-single-add-to-cart');
    }
    if (document.body.classList.contains('theme-xstore')) {
        jQuery('.product.type-product.product-type-bopobb .single_add_to_cart_button').removeClass('ajax_add_to_cart');
    }
}

jQuery(document).ready(function ($) {
    "use strict";
    let bopobb_load_init = false;
    let bopobb_timeout = null;
    let bopobbSearchTimer = 0;

    $('.bopobb-single-wrap').each(function () {
        bopobb_load_init = true;
        bopobbInit($(this));
    });

    $(window).on('load', function () {
        if (!bopobb_load_init) {
            $('.bopobb-single-wrap').each(function () {
                bopobb_load_init = true;
                bopobbInit($(this));
            });
        }
    });

    $(document.body).on('bopobb-initial-bundle', function () {
        if (!bopobb_load_init) {
            $('.bopobb-single-wrap').each(function () {
                bopobb_load_init = true;
                bopobbInit($(this));
            });
        }
    });

    if ($('.type-product.product-type-bopobb .bopobb-single-wrap').length && bopobbVars.wc_custom_atc === '1') {
        $(document).on('click', 'button.single_add_to_cart_button:not(.disabled)', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            let button = $(this),
                data = {},
                form = $(this).closest('form.cart');
            form.find('select, input').each(function () {
                let name = $(this).attr('name');
                if (name) {
                    data[name] = $(this).val();
                }
            });
            if (!data['product_id']) {
                data['product_id'] = parseInt(button.attr('value'));
            }
            if (!data['add-to-cart']) {
                data['add-to-cart'] = parseInt(button.attr('value'));
            }
            $(document.body).trigger('adding_to_cart', [button, data]);
            $.ajax({
                type: 'post',
                url: bopobbVars.wc_ajax_url.toString().replace('%%endpoint%%', 'bopobb_add_to_cart_ajax'),
                data: data,
                beforeSend: function (response) {
                    button.removeClass('added').addClass('loading');
                },
                success: function (response) {
                    if (response.error) {
                        location.href = window.location.href;
                        return false;
                    }
                    jQuery(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, button]);
                },
                complete: function (response) {
                },
            });
        });
    }

    $(document).on('input blur', '.bopobb-single-note-input', function () {
        let single_wrap = $(this).closest('.bopobb-single-wrap'),
            value = $(this).find('textarea.input-text').val();
        if ($(single_wrap).hasClass('bopobb-shortcode-wrap')) {
            $(single_wrap).closest('.bopobb-shortcode-form').find('form.cart #bopobb_product_note').val(value);
        } else {
            let wrap_id = single_wrap.attr('data-id'),
                $container = bopobb_wrap_container(single_wrap, wrap_id);
            $($container).find('form.cart #bopobb_product_note').val(value);
        }
    });

    $(document).on('click touch', '.bopobb-item-change', function () {
        let btn_index = $(this).attr('data-item'),
            prd_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list'),
            current_single_wrap = $(this).closest('.bopobb-single-wrap'),
            popup_wrap = $('.bopobb-area .bopobb-inner .bopobb-popup'),
            p_item_wrap = $(this).closest('.bopobb-item-product');
        if (current_single_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + btn_index).attr('data-change') == 1) {
            bopobbDisableScroll();
            current_single_wrap.addClass('bopobb-swap-active');
            if ($(this).closest('.bopobb-item-top').length) {
                current_single_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + btn_index).addClass('bopobb-swap-active');
                p_item_wrap = current_single_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + btn_index);
            } else {
                $(this).closest('.bopobb-item-product').addClass('bopobb-swap-active');
            }
            $('.bopobb-area .bopobb-inner .bopobb-overlay').addClass('bopobb-open');
            popup_wrap.addClass('bopobb-open');
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
            prd_list.css({
                'visibility': 'visible',
                'opacity': 1
            });
            // $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').hide(100);
            let popup_id_product = prd_list.attr('data-product'),
                popup_btn_back = $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back'),
                popup_index = prd_list.attr('data-item'),
                variable_title = p_item_wrap.attr('data-title'),
                custom_title = p_item_wrap.attr('data-custom-title'),
                item_id_product = $(this).attr('data-product'),
                item_index = $(this).attr('data-item'),
                var_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list'),
                is_variation = 'variation' === p_item_wrap.attr('data-type'),
                variation_id_current = p_item_wrap.attr('data-id');
            $(popup_btn_back).hide(100);
            if ('product' !== bopobbVars.popup_load_init && is_variation && variation_id_current) {
                let left_slide = popup_wrap.width();
                $(popup_wrap).find('.bopobb-popup-title').html(variable_title).attr('title', variable_title).data('title', custom_title);
                $(popup_btn_back).show(100);
                prd_list.bopobbSlideLeft(1, 0, left_slide);
                var_list.bopobbSlideLeft(1, 1, left_slide);
            } else {
                $(popup_wrap).find('.bopobb-popup-title').html(custom_title).attr('title', custom_title).data('title', custom_title);
                $(popup_btn_back).hide(100);
                prd_list.bopobbSlideRight(1, 1, 0);
            }

            if (popup_index === '' || popup_index !== item_index || popup_id_product != item_id_product) {
                // if ('' !== $(popup_wrap).find('.bopobb-popup-title').data('title')) {
                //     $(popup_wrap).find('.bopobb-popup-title').html(bopobbVars.bopobb_popup_title);
                // }
                popup_wrap.attr('data-caller', 'single');

                if ('product' !== bopobbVars.popup_load_init && is_variation && variation_id_current) {
                    prd_list.attr('data-item', btn_index);
                    var_list.attr('data-item', btn_index);
                    prd_list.html('');
                    var_list.html('').addClass('bopobb-loading');
                    let data_v = {
                        action: 'bopobb_cart_popup_data',
                        item: btn_index,
                        product: $(this).attr('data-product'),
                        variation: variation_id_current,
                        discount_type: p_item_wrap.attr('data-discount-type'),
                        discount_number: p_item_wrap.attr('data-discount-number'),
                        dataType: 'JSON',
                        lang: bopobbVars.language,
                        nonce: bopobbVars.nonce,
                    };
                    $.post(bopobbVars.ajaxurl, data_v, function (response) {
                        let _res = response;
                        prd_list.html(_res[0]).attr('data-product', p_item_wrap.closest('.bopobb-single-wrap').attr('data-id'))
                            .attr('data-item', btn_index)
                            .attr('data-var-in', _res[4])
                            .attr('data-var-ex', _res[5]);
                        var_list.html(_res[1]).attr('data-product', _res[2]).removeClass('bopobb-loading');
                        if (_res[6] && '' !== _res[6] && 'undefined' !== typeof _res[6]) {
                            $(popup_wrap).find('.bopobb-popup-title').data('title', response['item_title']);
                        }

                        let bottom_filter_height = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list .bopobb-product-filter').outerHeight();
                        var_list.css('padding-bottom', bottom_filter_height);
                        if (var_list.hasClass('bopobb-option-product-wrap')) {
                            bopobb_option_check(var_list.find('.bopobb-option-add'), var_list.find('.bopobb-option-variations'));
                            var_list.find('.bopobb-option-select').trigger('change');
                        }
                    });
                } else {
                    prd_list.html('').addClass('bopobb-loading');
                    let data = {
                        action: 'bopobb_product_list',
                        item: $(this).attr('data-item'),
                        product: $(this).attr('data-product'),
                        lang: bopobbVars.language,
                        nonce: bopobbVars.nonce,
                    };
                    $.post(bopobbVars.ajaxurl, data, function (response) {
                        if ('object' !== typeof response) {
                            prd_list.removeClass('bopobb-loading');
                            return;
                        }
                        if ('' !== response['item_title'] && 'undefined' !== typeof response['item_title']) {
                            $(popup_wrap).find('.bopobb-popup-title').html(response['item_title']).attr('title', response['item_title']).data('title', response['item_title']);
                        }
                        let products_html = response['products'],
                            variation_include = response['variation'],
                            variation_exclude = response['variation_ex'];
                        prd_list
                            .html(products_html)
                            .attr('data-product', item_id_product)
                            .attr('data-item', item_index)
                            .attr('data-var-in', variation_include)
                            .attr('data-var-ex', variation_exclude)
                            .removeClass('bopobb-loading');
                    });
                }
            }
        } else {
            if (current_single_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + btn_index).attr('data-change') == '') {
                alert(bopobbVars.alert_no_item);
            }
        }
    });

    $(document).on('click touch', '.bopobb-cart-change', function (e) {
        e.preventDefault();
        let btn_index = $(this).attr('data-index'),
            btn_bundle_id = $(this).attr('data-bundle'),
            bopo_popup = $('.bopobb-area .bopobb-inner .bopobb-popup'),
            active_cart_info = $(this).closest('.bopobb-cart-item.bopobb-cart-child').find('.bopobb-cart-info'),
            variation_id = active_cart_info.attr('data-product-id'),
            is_variation = active_cart_info.attr('data-variation') !== '',
            variable_id = active_cart_info.attr('data-variable'),
            variable_title = active_cart_info.attr('data-title'),
            var_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list'),
            prd_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list');
        bopobbDisableScroll();
        $(this).closest('.bopobb-cart-item.bopobb-cart-child').addClass('bopobb-swap-active');
        $('.bopobb-area .bopobb-inner .bopobb-overlay').addClass('bopobb-open');

        bopo_popup.addClass('bopobb-open');
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
        if (is_variation) {
            let left_slide = bopo_popup.width();
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title').html(variable_title).attr('title', variable_title);
            $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').show(100);
            prd_list.bopobbSlideLeft(1, 0, left_slide);
            var_list.bopobbSlideLeft(1, 1, left_slide);
        } else {
            $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').hide(100);
            prd_list.bopobbSlideRight(1, 1, 0);
        }
        let popup_id_product = prd_list.attr('data-product');
        let popup_index = prd_list.attr('data-item');
        let popup_variable = var_list.attr('data-product');
        if (popup_index === '' || popup_index !== btn_index || popup_id_product !== btn_bundle_id) {
            let discount_type = active_cart_info.data('discount-type'),
                discount_number = active_cart_info.data('discount-number');
            prd_list.attr('data-item', btn_index);
            var_list.attr('data-item', btn_index);
            bopo_popup.attr('data-caller', 'cart');
            if (is_variation) {
                prd_list.html('');
                var_list.html('').addClass('bopobb-loading');
                let data = {
                    action: 'bopobb_cart_popup_data',
                    item: btn_index,
                    product: btn_bundle_id,
                    variation: variation_id,
                    discount_type: discount_type,
                    discount_number: discount_number,
                    dataType: 'JSON',
                    lang: bopobbVars.language,
                    nonce: bopobbVars.nonce,
                };
                $.post(bopobbVars.ajaxurl, data, function (response) {
                    let _res = response;
                    prd_list.html(_res[0]).attr('data-product', btn_bundle_id)
                        .attr('data-item', btn_index)
                        .attr('data-var-in', _res[4])
                        .attr('data-var-ex', _res[5]);
                    var_list.html(_res[1]).attr('data-product', _res[2]).removeClass('bopobb-loading');

                    let bottom_filter_height = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list .bopobb-product-filter').outerHeight();
                    var_list.css('padding-bottom', bottom_filter_height);
                    if (var_list.hasClass('bopobb-option-product-wrap')) {
                        bopobb_option_check(var_list.find('.bopobb-option-add'), var_list.find('.bopobb-option-variations'));
                        var_list.find('.bopobb-option-select').trigger('change');
                    }
                });
            } else {
                prd_list.html('').addClass('bopobb-loading');
                let data = {
                    action: 'bopobb_product_list',
                    item: btn_index,
                    product: btn_bundle_id,
                    lang: bopobbVars.language,
                    nonce: bopobbVars.nonce,
                };
                $.post(bopobbVars.ajaxurl, data, function (response) {
                    if ('object' !== typeof response) {
                        prd_list.removeClass('bopobb-loading');
                        return;
                    }
                    let products_html = response['products'],
                        variation_include = response['variation'],
                        variation_exclude = response['variation_ex'];
                    prd_list.html(products_html)
                        .attr('data-product', btn_bundle_id)
                        .attr('data-item', btn_index)
                        .attr('data-var-in', variation_include)
                        .attr('data-var-ex', variation_exclude)
                        .removeClass('bopobb-loading');
                });
            }
        }
    });

    $(document).on('click touch', '.bopobb-order-change', function (e) {
        e.preventDefault();
        let btn_index = $(this).attr('data-index'),
            btn_bundle_id = $(this).attr('data-bundle'),
            bopo_popup = $('.bopobb-area .bopobb-inner .bopobb-popup'),
            active_order_info = $(this).closest('.bopobb-cart-item.bopobb-cart-child').find('.bopobb-cart-info'),
            variation_id = active_order_info.attr('data-product-id'),
            is_variation = active_order_info.attr('data-variation') !== '',
            variable_id = active_order_info.attr('data-variable'),
            variable_title = active_order_info.attr('data-title'),
            prd_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list'),
            var_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list');
        if (!active_order_info.length) {
            return;
        }

        bopobbDisableScroll();
        $(this).closest('.bopobb-cart-item.bopobb-cart-child').addClass('bopobb-swap-active');
        $('.bopobb-area .bopobb-inner .bopobb-overlay').addClass('bopobb-open');

        bopo_popup.addClass('bopobb-open');
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
        if (is_variation) {
            let left_slide = bopo_popup.width();
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title')
                .html(variable_title).attr('title', variable_title);
            $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').show(100);
            prd_list.bopobbSlideLeft(1, 0, left_slide);
            var_list.bopobbSlideLeft(1, 1, left_slide);
        } else {
            $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').hide(100);
            prd_list.bopobbSlideRight(1, 1, 0);
        }
        let popup_id_product = prd_list.attr('data-product'),
            popup_index = prd_list.attr('data-item'),
            popup_variable = var_list.attr('data-product'),
            item_index = btn_index;
        if (popup_index === '' || popup_index !== item_index || popup_id_product !== btn_bundle_id) {
            let discount_type = active_order_info.data('discount-type'),
                discount_number = active_order_info.data('discount-number');
            prd_list.attr('data-item', btn_index);
            var_list.attr('data-item', btn_index);
            bopo_popup.attr('data-caller', 'order');
            if (is_variation) {
                prd_list.html('');
                var_list.html('').addClass('bopobb-loading');
                let data = {
                    action: 'bopobb_cart_popup_data',
                    item: btn_index,
                    product: btn_bundle_id,
                    variation: variation_id,
                    discount_type: discount_type,
                    discount_number: discount_number,
                    dataType: 'JSON',
                    lang: bopobbVars.language,
                    nonce: bopobbVars.nonce,
                };
                $.post(bopobbVars.ajaxurl, data, function (response) {
                    let _res = response;
                    prd_list.html(_res[0]).attr('data-product', btn_bundle_id).attr('data-item', item_index);
                    var_list.html(_res[1]).attr('data-product', _res[2]).removeClass('bopobb-loading');

                    let bottom_filter_height = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list .bopobb-product-filter').outerHeight();
                    var_list.css('padding-bottom', bottom_filter_height);
                    if (var_list.hasClass('bopobb-option-product-wrap')) {
                        bopobb_option_check(var_list.find('.bopobb-option-add'), var_list.find('.bopobb-option-variations'));
                        $('.bopobb-option-select').trigger('change');
                    }
                });
            } else {
                prd_list.html('').addClass('bopobb-loading');
                let data = {
                    action: 'bopobb_product_list',
                    item: btn_index,
                    product: btn_bundle_id,
                    lang: bopobbVars.language,
                    nonce: bopobbVars.nonce,
                };
                $.post(bopobbVars.ajaxurl, data, function (response) {
                    if ('object' !== typeof response) {
                        prd_list.removeClass('bopobb-loading');
                        return;
                    }
                    let products_html = response['products'],
                        variation_include = response['variation'],
                        variation_exclude = response['variation_ex'];
                    prd_list.html(products_html)
                        .attr('data-product', btn_bundle_id)
                        .attr('data-item', item_index)
                        .attr('data-var-in', variation_include)
                        .attr('data-var-ex', variation_exclude)
                        .removeClass('bopobb-loading');
                });
            }
        }
    });

    $(document).on('click touch', '.bopobb-product-pages:not(.bopobb-product-page-active)', function () {
        bopobbDisableScroll();
        let item_id_product = $(this).closest('.bopobb-product-list').attr('data-product'),
            item_index = $(this).closest('.bopobb-product-list').attr('data-item'),
            item_filter = $(this).closest('.bopobb-product-paging-wrap').find('.bopobb-category-filter'),
            filter_cat = '', enable_filter = item_filter.length,
            digit = $(this).closest('.bopobb-product-paging-wrap').find('.bopobb-search-filter-input').val();
        if (enable_filter) filter_cat = $(item_filter).val();
        // $('.bopobb-area .bopobb-inner .bopobb-popup').attr('data-caller', 'single');
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html('').addClass('bopobb-loading');
        let data = {
            action: 'bopobb_product_list',
            item: item_index,
            product: item_id_product,
            category: filter_cat,
            key: digit,
            page: $(this).attr('data-page'),
            lang: bopobbVars.language,
            nonce: bopobbVars.nonce,
        };
        $.post(bopobbVars.ajaxurl, data, function (response) {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html(response['products']);
            setTimeout(function () {
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').removeClass('bopobb-loading');
                if (enable_filter) $('.bopobb-area .bopobb-popup .bopobb-product-list .bopobb-product-paging-wrap .bopobb-category-filter option[value="' + filter_cat + '"]').attr("selected", true);
            }, 100)
        });
    });

    $(document).on('change', '.bopobb-category-filter', function () {
        bopobbDisableScroll();
        let item_id_product = $(this).closest('.bopobb-product-list').attr('data-product'),
            item_index = $(this).closest('.bopobb-product-list').attr('data-item'),
            filter_cat = $(this).val(),
            digit = $(this).closest('.bopobb-product-paging-wrap').find('.bopobb-search-filter-input').val();
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html('').addClass('bopobb-loading');
        let data = {
            action: 'bopobb_product_list',
            item: item_index,
            product: item_id_product,
            category: filter_cat,
            key: digit,
            page: 1,
            lang: bopobbVars.language,
            nonce: bopobbVars.nonce,
        };
        $.post(bopobbVars.ajaxurl, data, function (response) {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html(response['products']);
            setTimeout(function () {
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').removeClass('bopobb-loading');
                $('.bopobb-area .bopobb-popup .bopobb-product-list .bopobb-product-paging-wrap .bopobb-category-filter option[value="' + filter_cat + '"]').attr("selected", true);
            }, 100)
        });
    });

    $(document).on('change', '.bopobb-search-filter-input', function () {
        bopobbDisableScroll();

        let _digit = $(this).val();
        // if (_digit === '' || _digit.length >= 3) {
        // $(this).attr('title', '');
        if (bopobbSearchTimer != null) {
            clearTimeout(bopobbSearchTimer);
        }
        bopobbSearchTimer = setTimeout(bopobbAjaxSearchFilter, 300, _digit, $(this).closest('.bopobb-product-paging-wrap'));
        return false;
        // } else {
        // $(this).attr('title', 'Input atleast 3 charactor to search');
        // }
    });

    $(document).on('click touch', '.bopobb-product-img-wrap', function (e) {
        e.preventDefault();
        bopobbProductSelect($(this));
    });

    $(document).on('click touch', '.bopobb-option-add:not(.bopobb-disable)', function (e) {
        e.preventDefault();
        let caller = $(this).closest('.bopobb-popup').attr('data-caller');
        bopobbApplyProduct($(this).closest('.bopobb-variation-list').attr('data-item'), $(this), caller);
    });

    $(document).on('click touch', '.bopobb-gallery-add-wrap', function (e) {
        let $product_select = $('.bopobb-area .bopobb-products-wrap .bopobb-product.bopobb-product-id-' + $(this).attr('data-product'));
        if ($product_select.length) {
            bopobbProductSelect($product_select.find('.bopobb-product-img-wrap'));
        }
    });

    $(document).on('click touch', '.bopobb-product-zoom', function (e) {
        e.stopPropagation();
        let $gallery = $('.bopobb-area .bopobb-popup .bopobb-product-gallery');
        $gallery.hide();
        $gallery.closest('.bopobb-product-gallery-wrap').bopobbLeftReset(400, 1, 960);
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').bopobbSlideRight(400, 0, 960);

        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-btn-back').attr('data-current', 'gallery').show();
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title').html($(this).closest('.bopobb-product').find('.bopobb-product-title').html());
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap .bopobb-product-gallery-overlay').addClass('bopobb-active');
        let product_id = $(this).closest('.bopobb-product').attr('data-product');
        let gallery_id = $gallery.attr('data-product');

        if (product_id !== gallery_id) {
            let data = {
                action: 'bopobb_product_gallery',
                product: product_id,
                lang: bopobbVars.language,
                nonce: bopobbVars.nonce,
            };
            $.post(bopobbVars.ajaxurl, data, function (response) {
                if (response != '') {
                    $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap .bopobb-product-gallery-overlay').removeClass('bopobb-active');
                    $gallery.show();
                    $gallery.html(response);
                    $gallery.attr('data-product', product_id);
                    $gallery.closest('.bopobb-product-gallery-wrap').find(('.bopobb-gallery-add-wrap')).attr('data-product', product_id);
                    $gallery.show();
                }
            });
        } else {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap .bopobb-product-gallery-overlay').removeClass('bopobb-active');
            $gallery.show();
        }
    });

    $(document).on('click change', '.bopobb-attr-select', function () {
        let variation_array = [];
        $('.bopobb-filter-variation .bopobb-attr-select').each(function () {
            let attr_name = $(this).attr('name');
            variation_array[attr_name] = $(this).val();
        });
        $('.bopobb-variation-list .bopobb-product').each(function () {
            let product_display = true;
            for (let key in variation_array) {
                if (variation_array.hasOwnProperty(key) && variation_array[key] != '') {
                    if (variation_array[key] != $(this).data(key.toLowerCase())) {
                        product_display = false;
                    }
                }
            }
            if (product_display) {
                $(this).show(400);
            } else {
                $(this).hide(400);
            }
        })
    });

    $(document).on('change', '.bopobb-option-select', function () {
        let variationData = $(this).closest('.bopobb-option-variations').data('product_variations'),
            useAjax = false === variationData,
            attributes = bopobb_getChosenAttributes($(this).closest('.bopobb-option-variations'));
        if (attributes.count && attributes.count === attributes.chosenCount) {
            let matching_variations = '', variation = '';
            let prd_wrap = $(this).closest('.bopobb-option-product'),
                prd_title_html = prd_wrap.find('.bopobb-product-title'),
                prd_title = prd_title_html.attr('data-title'),
                prd_options = prd_wrap.find('.bopobb-option-variation'),
                prd_description = prd_wrap.find('.bopobb-variation-description'),
                variation_att = '';

            prd_options.each(function () {
                prd_title += ' - ' + $(this).find('option:selected').text();
                if (variation_att) {
                    variation_att += '&' + $(this).find('.bopobb-option-select').attr('name') + '=' + $(this).find('option:selected').val();
                } else {
                    variation_att = $(this).find('.bopobb-option-select').attr('name') + '=' + $(this).find('option:selected').val();
                }
            });
            if (useAjax) {
                let variable_wrap = $(this).closest('.bopobb-variation-list.bopobb-option-product-wrap'),
                    product_list_wrap = $(this).closest('.bopobb-products-wrap').find('.bopobb-product-list'),
                    variable_include = product_list_wrap.attr('data-var-in'),
                    variable_exclude = product_list_wrap.attr('data-var-ex'),
                    variable_id = variable_wrap.attr('data-product'),
                    ajax_attr = [],
                    caller = $(this).closest('.bopobb-popup').attr('data-caller'),
                    discount_type = 0,
                    discount_number = 0,
                    active_product_wrap = $('.bopobb-single-wrap.bopobb-swap-active .bopobb-item-product.bopobb-swap-active');
                variable_wrap.addClass('bopobb-loading');
                switch (caller) {
                    case 'cart':
                    case 'order':
                        let active_cart_info = $('.bopobb-cart-item.bopobb-cart-child.bopobb-swap-active .bopobb-cart-info');
                        discount_type = active_cart_info.attr('data-discount-type');
                        discount_number = active_cart_info.attr('data-discount-number');
                        break;
                    default:
                        discount_type = active_product_wrap.attr('data-discount-type');
                        discount_number = active_product_wrap.attr('data-discount-number');
                        break;
                }
                ajax_attr = attributes.data;
                ajax_attr['product_id'] = variable_id;
                ajax_attr['type'] = discount_type;
                ajax_attr['number'] = discount_number;
                let data = {
                    action: 'bopobb_search_many_variation',
                    data: ajax_attr,
                    lang: bopobbVars.language,
                    nonce: bopobbVars.nonce,
                };
                $.post(bopobbVars.ajaxurl, data, function (response) {
                    if (response != '' && response != false) {
                        variation = response;
                        prd_wrap.attr('data-price', variation.display_price).attr('data-product', variation.variation_id);
                        prd_wrap.find('.bopobb-product-variations').val(variation_att);
                        prd_wrap.find('.bopobb-option-image-wrap img').attr('src', variation.image.src).attr('srcset', '');
                        prd_wrap.find('.bopobb-option-price-wrap').html(variation.price_html).attr('data-price', variation.display_price);
                        prd_title_html.html(prd_title);
                        prd_wrap.find('.bopobb-product-stock').html(variation.availability_html).attr('data-stock', variation.max_qty).attr('data-backorder', variation.backorders_allowed);
                        if (variation.variation_description) {
                            prd_description.html(variation.variation_description);
                        } else {
                            prd_description.html('');
                        }
                        if (variable_include.length || variable_exclude.length) {
                            let is_variation_purchased = true;
                            if (variable_include.length) {
                                let include_arr = variable_include.split(",");
                                is_variation_purchased = false;
                                $.each(include_arr, function (key, val) {
                                    if (variation.variation_id == val) is_variation_purchased = true;
                                });
                            }
                            if (variable_exclude.length) {
                                let exclude_arr = variable_exclude.split(",");
                                $.each(exclude_arr, function (key, val) {
                                    if (variation.variation_id == val) is_variation_purchased = false;
                                });
                            }
                            if (is_variation_purchased) {
                                if (variation.is_in_stock && variation.is_purchasable) {
                                    prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').removeClass('bopobb-disable');
                                } else {
                                    prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                                }
                            } else {
                                prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                                prd_description.html(bopobbVars.variation_notice)
                            }
                        } else {
                            if (variation.is_in_stock && variation.is_purchasable) {
                                prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').removeClass('bopobb-disable');
                            } else {
                                prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                            }
                        }
                        variable_wrap.removeClass('bopobb-loading');
                    } else {
                        prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                        variable_wrap.removeClass('bopobb-loading');
                    }
                });
            } else {
                matching_variations = bopobb_findMatchingVariations(variationData, attributes.data);
                variation = matching_variations.shift();
                if (variation) {
                    prd_wrap.attr('data-price', variation.display_price).attr('data-product', variation.variation_id);
                    prd_wrap.find('.bopobb-product-variations').val(variation_att);
                    prd_wrap.find('.bopobb-option-image-wrap img').attr('src', variation.image.src).attr('srcset', '');
                    prd_wrap.find('.bopobb-option-price-wrap').html(variation.price_html).attr('data-price', variation.display_price);
                    prd_title_html.html(prd_title);
                    prd_wrap.find('.bopobb-product-stock').html(variation.availability_html).attr('data-stock', variation.max_qty).attr('data-backorder', variation.backorders_allowed);
                    if (variation.variation_description) {
                        prd_description.html(variation.variation_description);
                    } else {
                        prd_description.html('');
                    }
                    if (variation.is_in_stock && variation.is_purchasable) {
                        prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').removeClass('bopobb-disable');
                    } else {
                        prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                    }
                } else {
                    prd_wrap.attr('data-price', '').attr('data-product', '');
                    prd_wrap.find('.bopobb-product-variations').val('');
                    // prd_wrap.find('.bopobb-option-image-wrap img').attr('src', variation.image.src);
                    prd_wrap.find('.bopobb-option-price-wrap').html('').attr('data-price', '');
                    // prd_title_html.html(prd_title);
                    prd_wrap.find('.bopobb-product-stock').html('').attr('data-stock', 0).attr('data-backorder', 0);
                    prd_description.html(bopobbVars.variation_notice);
                    prd_wrap.find('.bopobb-option-add-wrap .bopobb-option-add').addClass('bopobb-disable');
                }
            }
        }
    });

    $(document).on('click touch', '.bopobb-overlay', function (e) {
        e.preventDefault();
        bopobbClosePopup();
    });

    $(document).on('click touch', '.bopobb-btn-close', function (e) {
        e.preventDefault();
        bopobbClosePopup();
    });

    $(document).on('click touch', '.bopobb-option-remove-wrap .bopobb-option-remove', function (e) {
        e.preventDefault();
        e.stopPropagation();
        let index = $(this).closest('.bopobb-item-img-wrap').data('item'),
            custom_title = $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index).data('custom-title');
        $(this).closest('.bopobb-option-remove-wrap').addClass('bopobb-hidden');

        if (bopobbVars.bopobb_link_individual == 1) {
            $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-title').attr('href', '');
        }
        if ($(this).closest('.bopobb-single-wrap').find('.bopobb-items-bottom-wrap.bopobb-template-1').length) {
            $(this).closest('.bopobb-item-img-wrap').addClass('bopobb-icon-plus2').attr('title', '');
            $(this).closest('.bopobb-item-img-wrap').find('.bopobb-item-img').html('').attr('title', '');
        } else {
            $(this).closest('.bopobb-item-img-wrap').attr('title', '');
            $(this).closest('.bopobb-item-img-wrap').find('.bopobb-item-img').html('<p class="bopobb-icon-plus2"></p>').attr('title', '');
        }
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index).attr('data-id', '').attr('data-price', '').attr('data-max', '');
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-title').html(custom_title).attr('title', '');
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-right .bopobb-item-price').html('......');
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-detail .stock').remove();
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-detail .star-rating').remove();
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-detail .bopobb-item-variations').val('');
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-detail .bopobb-item-detail-short-description').html('');
        $(this).closest('.bopobb-single-wrap').find('.bopobb-item-product.bopobb-item-' + index + ' .bopobb-item-detail .bopobb-item-detail-description').html('');

        $(this).closest('.bopobb-single-wrap').addClass('bopobb-initial-process');
        bopobbInit($('.bopobb-single-wrap.bopobb-initial-process'), 'init');
    });

    $(document).on('click touch', '.bopobb-btn-back', function (e) {
        e.preventDefault();
        $(this).hide(100);
        let popup_title = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title');
        if ('' != $(popup_title).data('title') && 'undefined' !== typeof $(popup_title).data('title')) {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title').html($(popup_title).data('title'));
        } else {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title').html(bopobbVars.bopobb_popup_title);
        }
        switch ($(this).attr('data-current')) {
            case 'gallery':
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').bopobbLeftReset(400, 1);
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list').bopobbLeftReset(400, 0);
                break;
            default:
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').bopobbLeftReset(400, 1);
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list').bopobbLeftReset(400, 0);
        }
    });

    $(document).on('change', '.bopobb-item-quantity .bopobb-item-qty', function () {
        let $this = $(this);

        bopobb_check_qty($this);
    });

    $(document).on('keyup', '.bopobb-item-quantity .bopobb-item-qty', function () {
        let $this = $(this);

        if (bopobb_timeout != null) clearTimeout(bopobb_timeout);
        bopobb_timeout = setTimeout(bopobb_check_qty, 1000, $this);
    });

    $(document).on('change', '.bopobb-cart-item.bopobb-cart-child .bopobb-cart-item-qty', function () {
        let $this = $(this);

        if (bopobb_timeout != null) return;
        if (!$this.hasClass('bopobb-cart_updating')) bopobb_cart_qty($this, 'cart');
    });

    $(document).on('keyup', '.bopobb-cart-item.bopobb-cart-child .bopobb-cart-item-qty', function () {
        let $this = $(this);
        $this.addClass('bopobb-cart_updating');

        if (bopobb_timeout != null) clearTimeout(bopobb_timeout);
        bopobb_timeout = setTimeout(bopobb_cart_qty, 1000, $this, 'cart');
    });

    $(document).on('change', '.bopobb-cart-item.bopobb-cart-child .bopobb-order-item-qty', function () {
        let $this = $(this);

        if (bopobb_timeout != null) return;
        if (!$this.hasClass('bopobb-cart_updating')) bopobb_cart_qty($this, 'order');
    });

    $(document).on('keyup', '.bopobb-cart-item.bopobb-cart-child .bopobb-order-item-qty', function () {
        let $this = $(this);
        $this.addClass('bopobb-cart_updating');

        if (bopobb_timeout != null) clearTimeout(bopobb_timeout);
        bopobb_timeout = setTimeout(bopobb_cart_qty, 1000, $this, 'order');
    });

    $(document).on('click touch', '.bopobb-sticky-atc-wrap .vi-wcaio-product-bt-atc.bopobb-disabled', function (e) {
        e.stopImmediatePropagation();
        e.preventDefault();
        let sticky_wrap = $(this).closest('.bopobb-sticky-atc-wrap'),
            sticky_items = sticky_wrap.find('.bopobb-sticky-item .bopobb-sticky-item-img-wrap'),
            unselected_index = '',
            single_bopo_wrap = $('.bopobb-single-wrap.bopobb-single-wrap-' + sticky_wrap.data('product-id'));
        sticky_items.each(function () {
            if ($(this).data('id') !== '' && $(this).data('id') !== null) {
                unselected_index = $(this).data('item');
                return false;
            }
        });
        if (unselected_index !== '' && single_bopo_wrap.length) {
            if (bopobbVars.bundle_scroll_animation === '1') {
                $('html, body').animate({
                    scrollTop: single_bopo_wrap.offset().top
                }, 500, function () {
                    single_bopo_wrap.first().find('.bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + unselected_index).focus();
                });
            }
        }
    });

    $(document).on('click', '.test-bopobb-export-pdf-button:not(.bopobb-loading)', function () {
        let thisBtn = $(this);
        let items_data = {},
            bundle_wrap = thisBtn.closest('.bopobb-single-wrap'),
            item_block = bundle_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product'),
            tax_include = bundle_wrap.find('.bopobb-detail-table').data('tax-include'),
            tax_rate = parseFloat(bundle_wrap.find('.bopobb-detail-table').data('tax-rate')),
            tax_exempt = bundle_wrap.find('.bopobb-detail-table').data('tax-exempt'),
            tax_view = bundle_wrap.find('.bopobb-detail-table').data('tax-view');
        $.each(item_block, function (i_key, i_val) {
            let item_detail = {};
            item_detail['id'] = $(i_val).data('id');
            item_detail['image'] = $(i_val).find('.bopobb-item-img-wrap .bopobb-item-img img').attr('src');
            item_detail['qty'] = $(i_val).find('.bopobb-item-quantity .bopobb-item-qty').val();
            item_detail['title'] = $(i_val).find('.bopobb-item-detail .bopobb-item-title').html().trim();
            if (tax_view === 1 && tax_exempt === 0) {
                item_detail['price'] = parseFloat($(i_val).data('price')) + (parseFloat($(i_val).data('price')) * (tax_rate / 100));
            } else {
                item_detail['price'] = parseFloat($(i_val).data('price'));
            }
            items_data[i_key] = item_detail;
        });
        $.ajax({
            type: 'post',
            url: bopobbVars.ajaxurl,
            data: {
                action: 'bopobb_export_pdf',
                lang: bopobbVars.language,
                nonce: bopobbVars.nonce,
                bundle_id: '',
                bundle_item: items_data,
            },
            xhr: function () {
                let xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 2) {
                        if (xhr.status === 200) {
                            xhr.responseType = "blob";
                        } else {
                            xhr.responseType = "text";
                        }
                    }
                };
                return xhr;
            },
            beforeSend: () => $(thisBtn).addClass('bopobb-loading'),
            success(data) {
                let fileName = 'BopoBundle.pdf';
                //Convert the Byte Data to BLOB object.
                let blob = new Blob([data], {type: "application/octetstream"});
                //Check the Browser type and download the File.
                let isIE = !!document.documentMode;
                if (isIE) {
                    window.navigator.msSaveBlob(blob, fileName);
                } else {
                    let url = window.URL || window.webkitURL,
                        link = url.createObjectURL(blob),
                        a = $(`<a download="${fileName}" href="${link}"/>`),
                        body = $('body');

                    body.append(a);
                    a[0].click();
                    body.remove(a);
                }
                $(thisBtn).removeClass('bopobb-loading');
            },
            error(res) {
                // console.log(res)
            },
        });
    });

    $(document).on('click', '.bopobb-print-button:not(.bopobb-loading)', function () {
        let printIframe = $(`<iframe id="bopobb-print-frame" name="bopobb_print_frame" style="display:none;"></iframe>`),
            thisBtn = $(this),
            bundle_title = $(thisBtn).data('title'),
            items_data = {},
            bundle_wrap = thisBtn.closest('.bopobb-single-wrap'),
            item_block = bundle_wrap.find('.bopobb-items-bottom-wrap .bopobb-item-product'),
            tax_include = bundle_wrap.find('.bopobb-detail-table').data('tax-include'),
            tax_rate = parseFloat(bundle_wrap.find('.bopobb-detail-table').data('tax-rate')),
            tax_exempt = bundle_wrap.find('.bopobb-detail-table').data('tax-exempt'),
            tax_view = bundle_wrap.find('.bopobb-detail-table').data('tax-view'),
            fix = Math.pow(10, Number(bopobbVars.price_decimals) + 1);
        let style = bopobbVars.printStyle,
            printDesc = '',
            total_price = 0,
            total_discount = 0,
            totalQty = 0,
            temp = $('<div></div>'),
            temp_subtotal = '',
            print_html = '';
        $(thisBtn).addClass('bopobb-loading');

        $.each(item_block, function (i_key, i_val) {
            let i_image = '';
            if (bundle_wrap.find('.bopobb-items-bottom-wrap').hasClass('bopobb-template-1')) {
                let i_index = $(i_val).data('item');
                i_image = $(bundle_wrap).find('.bopobb-item-top.bopobb-item-' + i_index + ' .bopobb-item-img img').attr('src');
            } else {
                i_image = $(i_val).find('.bopobb-item-img-wrap .bopobb-item-img img').attr('src');
            }
            if (undefined === i_image) return;
            let item_detail = {},
                i_dc_type = $(i_val).data('discount-type'),
                i_dc_number = parseFloat($(i_val).data('discount-number'));
            item_detail['id'] = $(i_val).attr('data-id');
            item_detail['image'] = i_image;
            item_detail['quantity'] = $(i_val).find('.bopobb-item-quantity .bopobb-item-qty').val();
            item_detail['title'] = $(i_val).find('.bopobb-item-detail .bopobb-item-title').html().trim();
            let i_price = parseFloat($(i_val).attr('data-price')) * parseInt(item_detail['quantity']),
                i_dc_price = i_price;

            switch (i_dc_type) {
                case 0:
                    i_dc_price *= (100 - i_dc_number) / 100;
                    i_dc_price = Math.round(i_dc_price * fix) / fix;
                    break;
                case 1:
                    i_dc_price = i_dc_number >= i_dc_price ? 0 : i_dc_price - i_dc_number;
                    i_dc_price = Math.round(i_dc_price * fix) / fix;
                    break;
                case 2:
                    i_dc_price = i_dc_number;
                    i_dc_price = Math.round(i_dc_price * fix) / fix;
                    break;
            }
            if (tax_view === 1 && tax_exempt === 0) {
                item_detail['price'] = parseFloat(i_price) + (parseFloat(i_price) * (tax_rate / 100));
                item_detail['bundle_price'] = parseFloat(i_dc_price) + (parseFloat(i_dc_price) * (tax_rate / 100));
            } else {
                item_detail['price'] = parseFloat(i_price);
                item_detail['bundle_price'] = parseFloat(i_dc_price);
            }
            items_data[i_key] = item_detail;
        });

        printIframe.remove();
        $('body').append(printIframe);
        let printSection = frames['bopobb_print_frame'];

        $.each(items_data, function (p_key, p_val) {
            let format_price = bopobb_format_price(p_val.price),
                format_b_price = bopobb_format_price(p_val.bundle_price);
            total_price += parseFloat(p_val.price);
            total_discount += parseFloat(p_val.bundle_price);
            totalQty += parseInt(p_val.quantity);
            print_html += `<tr>
                    <td class="bopobb-print-img">
                        <img src="${p_val.image}" width="100%">
                    </td>
                    <td class='bopobb-print-title'>
                        <div>${p_val.title}</div>
                    </td>
                    <td class="bopobb-print-quantity-col">${p_val.quantity}</td>
                    <td class="bopobb-print-price-col">${format_price}</td>
                    <td class="bopobb-print-subtotal-col">${format_b_price}</td>
                </tr>`;
        });
        total_price = bopobb_format_price(total_price);
        total_discount = bopobb_format_price(total_discount);

        temp.append($('head meta').clone());
        temp.append($('head title').clone());

        let html = `<div id="bopobb-print-frame">
                            ${bopobbVars.printHeader}
                            <h1 class="bopobb-print-bundle-title">${bundle_title}</h1>
                            <table>
                                <thead >
                                <tr>
                                    <th colspan="2" class="bopobb-print-product-col">Product</th>
                                    <th class="bopobb-print-quantity-col">Quantity</th>
                                    <th class="bopobb-print-price-col">Item Price</th>
                                    <th class="bopobb-print-subtotal-col">Bundle Price</th>
                                </tr>
                                </thead>
                                <tbody>
                                ${print_html}
                                </tbody>
                                 <tfoot style="display: table-row-group; ">
                                    <tr>
                                        <th colspan="2">Total</th>
                                        <th>${totalQty}</th>
                                        <th class="bopobb-print-footer-total">${total_price}</th>
                                        <th class="bopobb-print-footer-bundle-total">${total_discount}</th>
                                    </tr>
                                </tfoot>
                            </table>
                            ${bopobbVars.printFooter}
                        </div>`;

        html = `<!DOCTYPE html>
                        <html>
                            <head>
                                ${temp.html()}
                                ${style}
                            </head>
                            <body>${html}</body>
                        </html>`;

        printSection.document.write(html);

        let images = $(html).find('img');
        let totalImages = images.length;
        let imagesLoaded = 0;

        images.on('load', function (e) {
            imagesLoaded++;
            if (imagesLoaded === totalImages) {
                printSection.print();
            }
        });
        $(thisBtn).removeClass('bopobb-loading');

        printSection.document.close();
    });

    $(document).on('click', '.bopobb-social-share.bopobb-share-url', function () {
        let $this = $(this),
            this_copied_text = $this.parent().find('.bopobb-copy-tooltip');
        /*Copy event*/
        $this.select();
        document.execCommand('copy');
        /*Show tooltip and auto hide it */
        this_copied_text.css('visibility', 'visible');
        setTimeout(function () {
            this_copied_text.css('visibility', 'hidden');
        }, 1000);
    });

    function bopobbProductSelect(product_element) {
        let caller = product_element.closest('.bopobb-popup').attr('data-caller');
        switch (product_element.closest('.bopobb-product').attr('data-type')) {
            case 'simple':
                bopobbApplyProduct(product_element.closest('.bopobb-product-list').attr('data-item'), product_element, caller);
                break;
            case 'variation':
                bopobbApplyProduct(product_element.closest('.bopobb-variation-list').attr('data-item'), product_element, caller);
                break;
            case 'variable':
                let variable_title = product_element.closest('.bopobb-product').find('.bopobb-product-title-wrap .bopobb-product-title').html(),
                    left_slide = $('.bopobb-area .bopobb-inner .bopobb-popup').width(),
                    prd_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list'),
                    var_list = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list'),
                    active_product_wrap = $('.bopobb-single-wrap.bopobb-swap-active .bopobb-item-product.bopobb-swap-active');
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
                prd_list.bopobbSlideLeft(400, 0, left_slide);
                var_list.bopobbSlideLeft(400, 1, left_slide);
                $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').attr('data-current', 'variation').show(100);

                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-popup-header .bopobb-popup-title').html(variable_title).attr('title', variable_title);
                if (product_element.closest('.bopobb-product').attr('data-product') !== var_list.attr('data-product') ||
                    prd_list.attr('data-item') !== var_list.attr('data-item')) {
                    var_list.html('').addClass('bopobb-loading');
                    let variable_id = product_element.closest('.bopobb-product').attr('data-product'),
                        discount_type = 0,
                        discount_number = 0;
                    switch (caller) {
                        case 'cart':
                        case 'order':
                            let active_cart_info = $('.bopobb-cart-item.bopobb-cart-child.bopobb-swap-active .bopobb-cart-info');
                            discount_type = active_cart_info.attr('data-discount-type');
                            discount_number = active_cart_info.attr('data-discount-number');
                            break;
                        default:
                            discount_type = active_product_wrap.attr('data-discount-type');
                            discount_number = active_product_wrap.attr('data-discount-number');
                            break;
                    }
                    let data = {
                        action: 'bopobb_product_variations',
                        product: variable_id,
                        variation_in: prd_list.attr('data-var-in'),
                        variation_ex: prd_list.attr('data-var-ex'),
                        discount_type: discount_type,
                        discount_number: discount_number,
                        lang: bopobbVars.language,
                        nonce: bopobbVars.nonce,
                    };
                    $.post(bopobbVars.ajaxurl, data, function (response) {
                        var_list.html(response).attr('data-product', variable_id).removeClass('bopobb-loading');
                        let bottom_filter_height = $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list .bopobb-product-filter').outerHeight();
                        var_list.css('padding-bottom', bottom_filter_height);
                        if (var_list.hasClass('bopobb-option-product-wrap')) {
                            bopobb_option_check(var_list.find('.bopobb-option-add'), var_list.find('.bopobb-option-variations'));
                            $('.bopobb-option-select').trigger('change');
                            if ('1' === bopobbVars.vi_swatches) {
                                $('.bopobb-option-variations').each(function () {
                                    jQuery(this).addClass('vi_wpvs_variation_form vi_wpvs_variation_form_init').viwpvs_woo_product_variation_swatches();
                                });
                            }
                        }
                    });
                }
                var_list.attr('data-item', prd_list.attr('data-item'));
                break;
            default:
                break;
        }
    }

    function bopobbInit($wrap, stage = 'init') {
        let wrap_id = $wrap.attr('data-id');
        let $container = bopobb_wrap_container($wrap, wrap_id);

        bopobb_check_ready($container, stage);
        bopobb_calc_price($container);
        bopobb_save_ids($container);

        $wrap.removeClass('bopobb-initial-process');
        $(document).trigger('bopobbInit', [$wrap, $container]);
    }

    function bopobbCartInit($wrap, stage = 'init') {

    }

    function bopobb_wrap_container($wrap, id) {
        if ($wrap.closest('.bopobb-shortcode-form').length) {
            return $wrap.closest('.bopobb-shortcode-form');
        }

        if ($wrap.closest('.bopobb-container').length) {
            return $wrap.closest('.bopobb-container');

        }
        if ($wrap.closest('#product-' + id).length) {
            let summary_wrap = $wrap.closest('#product-' + id + ' .summary.entry-summary');
            let short_summary_wrap = $wrap.closest('#product-' + id + ' .summary');
            let information_wrap = $wrap.closest('#product-' + id + ' .product-information');
            if ($wrap.closest('body.theme-cranebaby').length && short_summary_wrap.length) return short_summary_wrap;
            if (summary_wrap.length) return summary_wrap;
            if (information_wrap.length) return information_wrap;

        }
        if ($wrap.closest('.et_pb_column').length) {
            return $wrap.closest('.et_pb_column');
        }
        if ($wrap.closest('.product.post-' + id).length) {
            return $wrap.closest('.product.post-' + id);

        }
        if ($wrap.closest('div.product-type-bopobb').length) {
            return $wrap.closest('div.product-type-bopobb');

        }
        if ($wrap.closest('.elementor-product-bopobb').length) {
            return $wrap.closest('.elementor-product-bopobb');

        }
        if ($wrap.closest('body.theme-Divi').length && $wrap.closest('.et_pb_column').length) {

            return $wrap.closest('.et_pb_column');
        }

        return $wrap;
    }

    function bopobb_container(id, stage) {
        let aditional_class = stage == 'change' ? '.bopobb-initial-process' : '';

        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('.bopobb-shortcode-form').length) {
            return $('.bopobb-single-wrap-' + id + aditional_class).closest('.bopobb-shortcode-form').attr('class');
        }

        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('.bopobb-container').length) {
            return '.bopobb-container';

        }

        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('#product-' + id).length) {
            return '#product-' + id + ' .summary.entry-summary';

        }
        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('.product.post-' + id).length) {
            return '.product.post-' + id;

        }
        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('div.product-type-bopobb').length) {
            return 'div.product-type-bopobb';

        }
        if ($('.bopobb-single-wrap-' + id + aditional_class).closest('.elementor-product-bopobb').length) {
            return '.elementor-product-bopobb';

        }

        return 'body.single-product';
    }

    // Disable add to cart button
    function bopobb_check_ready($container, stage = 'init') {
        let is_empty = false,
            is_selected_one = false,
            is_max = false,
            is_enough_qty = true,
            empty_item_count = 0,
            // total_qty = 0,
            // detail_table = $container.find('.bopobb-detail-table'),
            // b_quantity_min = parseInt( $(detail_table).data('min-quantity') ),
            // b_quantity_max = parseInt( $(detail_table).data('max-quantity') ),
            // $i_quantity = $container.find('.bopobb-items-bottom-wrap .bopobb-item-quantity .bopobb-item-qty'),
            $price = $container.find('.price'),
            $products = $container.find('.bopobb-items-bottom-wrap .bopobb-item-product'),
            $alert = $container.find('.bopobb-alert'),
            $print = $container.find('.bopobb-print-wrap'),
            $btn = $container.find('.single_add_to_cart_button').length ? $container.find('.single_add_to_cart_button') : $container.find('.et_pb_wc_add_to_cart'),
            count_item = $container.find('.bopobb-single-wrap .bopobb-items-bottom-wrap .bopobb-item-product').length,
            $sticky_wrap = $('.vi-wcaio-sb-wrap .bopobb-sticky-atc-wrap');
        $btn.removeClass('ajax_add_to_cart');

        if ($container.find('.bopobb-items-bottom-wrap.bopobb-template-2').length) {
            $container.find('.bopobb-single-wrap .bopobb-detail-table .bopobb-item-product').each(function () {
                if ($(this).attr('data-id') == '') {
                    $(this).find('th .bopobb-item-detail').addClass('bopobb-item-detail-null');
                    // $(this).find('th .bopobb-item-detail .bopobb-item-title').html(bopobbVars.bopobb_popup_title).addClass('bopobb-item-title-placeholder');
                    $(this).find('th .bopobb-item-detail .bopobb-item-title').addClass('bopobb-item-title-placeholder');
                } else {
                    $(this).find('th .bopobb-item-detail').removeClass('bopobb-item-detail-null');
                    $(this).find('th .bopobb-item-detail .bopobb-item-title').removeClass('bopobb-item-title-placeholder');
                }
            })
        }

        if (stage === 'init') {
            setTimeout(function () {
                let item_width = parseInt($container.find('.bopobb-single-wrap .bopobb-item-top:first-child').width() * bopobbVars.image_rate);
                if ($container.find('.bopobb-items-bottom-wrap.bopobb-template-1').length) {
                    for (let i = 0; i < count_item; i++) {
                        let img_item_set = $container.find('.bopobb-single-wrap .bopobb-item-top.bopobb-item-' + i + ' .bopobb-item-img img');
                        if (0 === img_item_set.length) {
                            if (item_width) {
                                $container.find('.bopobb-single-wrap .bopobb-item-top.bopobb-item-' + i + ' .bopobb-item-img-wrap.bopobb-item-change')
                                    .addClass('bopobb-icon-plus2').css('min-height', item_width);
                            } else {
                                $container.find('.bopobb-single-wrap .bopobb-item-top.bopobb-item-' + i + ' .bopobb-item-img-wrap.bopobb-item-change')
                                    .addClass('bopobb-icon-plus2');
                            }
                        }
                    }
                } else {
                    for (let i = 0; i < count_item; i++) {
                        if (!$container.find('.bopobb-single-wrap .bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + i).attr('data-id')) {
                            $container.find('.bopobb-single-wrap .bopobb-items-bottom-wrap .bopobb-item-product.bopobb-item-' + i + ' .bopobb-item-img')
                                .css('min-height', bopobbVars.image_height + 'px');
                        }
                    }
                }
                if ($container.find('.bopobb-items-bottom-wrap.bopobb-template-3').length) {
                    let image_element = $container.find('.bopobb-items-bottom-wrap.bopobb-template-3 .bopobb-item-block-wrap .bopobb-item-img-wrap');
                    $container.find('.bopobb-items-bottom-wrap.bopobb-template-3 .bopobb-item-img-separate-wrap').css('height', image_element.height() + 'px');
                }
            }, 1)
        }

        $products.each(function () {
            if ($(this).attr('data-id') === '') {
                empty_item_count += 1;
                if ('1' !== $(this).attr('data-optional')) {
                    is_empty = true;
                }
            } else {
                is_selected_one = true;
            }
            if ((parseInt($(this).attr('data-max')) >= 0) && (parseInt($(this).attr('data-max')) < parseInt($(this).attr('data-qty')))) {
                if ('0' !== $(this).attr('data-max') && '1' !== $(this).attr('data-optional')) is_max = true;
            }

            if ($(this).attr('data-change') != 1) {
                if ($container.find('.bopobb-items-bottom-wrap').hasClass('bopobb-template-1')) {
                    $container.find('.bopobb-item-change-wrap .bopobb-item-change.bopobb-item-' + $(this).attr('data-item')).css({
                        'opacity': 0,
                        'visibility': 'hidden'
                    });
                }
                if ($container.find('.bopobb-items-bottom-wrap').hasClass('bopobb-template-2') ||
                    $container.find('.bopobb-items-bottom-wrap').hasClass('bopobb-template-3')) {
                    $(this).find('.bopobb-item-change-wrap .bopobb-item-change').hide()
                }
            }
        });

        // $.each($i_quantity, function (i_key, i_element) {
        //     total_qty += parseInt( $(i_element).val() );
        // });
        //
        // if ('' !== b_quantity_min) {
        //     if ( total_qty < b_quantity_min ) {
        //         is_enough_qty = false;
        //     }
        // }
        // if ('' !== b_quantity_max) {
        //     if ( total_qty > b_quantity_max ) {
        //         is_enough_qty = false;
        //     }
        // }

        if ($sticky_wrap.length) {
            bopobb_sticky_check_ready($sticky_wrap, stage);
        }

        if (count_item === empty_item_count) {
            is_empty = true;
        }

        if (is_empty || is_max || !is_enough_qty) {
            if ('1' === bopobbVars.hide_price) {
                $price.hide();
            } else if ('2' === bopobbVars.hide_price) {
                if (is_selected_one) {
                    $price.show();
                } else {
                    $price.hide();
                }
            }
            $print.addClass('bopobb-hidden');
            $btn.addClass('bopobb-disabled');
            if (is_empty) {
                $alert.html(bopobbVars.alert_empty).slideDown();
                return;
            }
            if (is_max) {
                $alert.html(bopobbVars.alert_stock).slideDown();
                return;
            }
            // if (! is_enough_qty) {
            //     if ( total_qty < b_quantity_min ) {
            //         $alert.html(bopobbVars.alert_min_quantity.replace('[d]', b_quantity_min)).slideDown();
            //     } else {
            //         $alert.html(bopobbVars.alert_max_quantity.replace('[d]', b_quantity_max)).slideDown();
            //     }
            // }
        } else {
            if ('2' === bopobbVars.hide_price) {
                if (is_selected_one) {
                    $price.show();
                } else {
                    $price.hide();
                }
            } else {
                $price.show();
            }
            $alert.html('').slideUp();
            $print.removeClass('bopobb-hidden');
            $btn.removeClass('bopobb-disabled');
        }
    }

    function bopobb_sticky_check_ready($container, stage = 'init') {
        let is_empty = false,
            is_max = false,
            $sticky_wrap = $container.closest('.vi-wcaio-sb-wrap'),
            $price = $sticky_wrap.find('.vi-wcaio-sb-product-price-wrap .price'),
            $products = $container.find('.bopobb-sticky-items-wrap .bopobb-sticky-item'),
            $btn = $container.find('#bopobb-add-to-cart');
        $btn.removeClass('ajax_add_to_cart');

        $products.each(function () {
            if ($(this).attr('data-id') == '') is_empty = true;
            if ((parseInt($(this).attr('data-max')) >= 0) && (parseInt($(this).attr('data-max')) < parseInt($(this).attr('data-qty')))) is_max = true;
        });
        if (is_empty || is_max) {
            $price.hide();
            $btn.addClass('bopobb-disabled');
            if (is_empty) {
                $btn.attr('title', bopobbVars.alert_empty);
                return;
            }
            if (is_max) {
                $btn.attr('title', bopobbVars.alert_stock);
                return;
            }
        } else {
            $price.show();
            $btn.attr('title', '');
            $btn.removeClass('bopobb-disabled');
        }
    }

    function bopobb_save_ids($wrap) {
        let ids = Array(),
            $ids = $wrap.find('.bopobb-ids'),
            $sticky_vapier_ids = $('body.theme-vapier .main-single-product .sticky-product form.cart .bopobb-ids'),
            $atc_btn = $wrap.find('.single_add_to_cart_button').length ? $wrap.find('.single_add_to_cart_button') : $wrap.find('.et_pb_wc_add_to_cart'),
            $products = $wrap.find('.bopobb-detail-table'),
            $sticky_bopo_wrap = $('.vi-wcaio-sb-wrap .bopobb-sticky-atc-wrap');

        $products.find('.bopobb-item-product').each(function () {
            let $this = $(this);

            if ((
                parseInt($this.attr('data-id')) > 0
            ) && (
                parseFloat($this.attr('data-qty')) > 0
            )) {
                if ($this.find('.bopobb-item-detail .bopobb-item-variations').val()) {
                    ids.push($this.attr('data-id') + '%/' + $this.attr('data-qty') + '%/' + $this.find('.bopobb-item-detail .bopobb-item-variations').val());

                } else {
                    ids.push($this.attr('data-id') + '%/' + $this.attr('data-qty'));
                }
            } else {
                if (1 === $this.data('optional')) {
                    ids.push(null);
                }
            }
        });
        let atc_ids = ids.join('%&'), social_wrap = $wrap.find('.bopobb-social-share-wrap');
        $ids.val(atc_ids);
        if (social_wrap.length) {
            let link_wrap = social_wrap.find('.bopobb-social-share'),
                link_ids = ids.join('b0p0it'),
                link_id_attr = link_ids.replace('&', 'b0p0at'),
                link_id_detail = link_id_attr.replace(/%\//g, 'b0p0dt');

            $.each(link_wrap, function (s_key, s_val) {
                let data_link = $(s_val).data('link'), data_url = $(s_val).data('url'), data_edit = '';
                data_url += '?bopobbshare=' + link_id_detail;
                data_edit = data_link.replace("{bopobb_share}", data_url);
                if ($(s_val).hasClass('bopobb-share-url')) {
                    $(s_val).attr('data-url', data_edit);
                } else {
                    $(s_val).attr('href', data_edit);
                }
            })
        }
        $ids.val(atc_ids);
        $sticky_vapier_ids.val(atc_ids);
        $atc_btn.data('bopobb-ids', atc_ids);
        if ($sticky_bopo_wrap.length) {
            $sticky_bopo_wrap.find('.bopobb-ids').val(atc_ids);
            $sticky_bopo_wrap.find('.vi-wcaio-product-bt-atc').data('bopobb-ids', atc_ids);
        }

        $(document).trigger('bopobb_save_ids', [ids]);
    }

    function bopobbClosePopup(mode = 'all') {
        bopobbEnableScroll();
        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-item-product.bopobb-swap-active').removeClass('bopobb-swap-active');
        $('.bopobb-single-wrap').removeClass('bopobb-swap-active');
        $('.bopobb-area .bopobb-inner .bopobb-overlay').removeClass('bopobb-open');
        $('.bopobb-area .bopobb-inner .bopobb-popup').removeClass('bopobb-open');
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-gallery-wrap').bopobbSlideLeft(1, 0, 960);
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').bopobbLeftReset(0, 0);
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-variation-list').bopobbLeftReset(0, 0);
        $('.bopobb-area .bopobb-inner .bopobb-popup-header .bopobb-btn-back').hide();
        //$('.bopobb-area .bopobb-inner .bopobb-popup-title').html(bopobbVars.bopobb_popup_title).attr('title', '');
        let popup_title = $('.bopobb-area .bopobb-inner .bopobb-popup-title');
        if ('' != $(popup_title).data('title') && 'undefined' !== typeof $(popup_title).data('title')) {
            $(popup_title).html($(popup_title).data('title')).attr('title', '');
        } else {
            $(popup_title).html(bopobbVars.bopobb_popup_title).attr('title', '');
        }
        if (mode == 'all') {
            $('.bopobb-cart-item.bopobb-cart-child').removeClass('bopobb-swap-active');
        }
    }

    function bopobbApplyProduct(index = 0, item = '', mode = 'single') {
        let in_stock = true,
            stock_block = $(item).closest('.bopobb-product').find('.bopobb-product-stock');
        if (stock_block.length) {
            if (0 == $(stock_block).data('stock') && 1 != $(stock_block).data('backorder')) {
                in_stock = false;
            }
        }
        if (item && in_stock) {
            switch (mode) {
                case "cart":
                    let cart_prd = item.closest('.bopobb-product');
                    if (item.closest('.bopobb-option-add-wrap').length) {
                        cart_prd = item.closest('.bopobb-option-product');
                    }
                    let item_id = cart_prd.length ? cart_prd.attr('data-product') : '',
                        item_variation_val = cart_prd.find('.bopobb-product-variations'),
                        item_variation = item_variation_val.length ?
                            '%/' + item_variation_val.val() : '',
                        item_variation_string = item_variation_val.length ?
                            item_variation_val.val() : '',
                        cart_active = $('.bopobb-cart-child.bopobb-swap-active'),
                        cart_info = cart_active.find('.bopobb-cart-info'),
                        parent_key = cart_active.find('.product-name .bopobb-cart-info').attr('data-parent'),
                        cart_key = cart_active.find('.product-name .bopobb-cart-info').attr('data-id'),
                        variation_string = bopobbCartItems(parent_key, item_id, item_variation);

                    if (cart_info.attr('data-product-id') == item_id &&
                        cart_info.attr('data-variation') == item_variation_string) {
                        bopobbClosePopup();
                    } else {
                        if (is_duplicate_item(item_id, 'cart')) {
                            alert(bopobbVars.alert_duplicate);
                            return;
                        }
                        bopobbCartUpdate(cart_key, parent_key, variation_string);
                    }
                    break;
                case "order":
                    let order_prd = item.closest('.bopobb-product');
                    if (item.closest('.bopobb-option-add-wrap').length) {
                        order_prd = item.closest('.bopobb-option-product');
                    }
                    let order_item_id = order_prd.length ? order_prd.attr('data-product') : '',
                        order_variations = order_prd.find('.bopobb-product-variations'),
                        order_item_variation = order_variations.length ?
                            '%/' + order_variations.attr('value') : '',
                        order_item_variation_string = order_variations.length ?
                            order_variations.attr('value') : '',
                        order_active = $('.bopobb-cart-child.bopobb-swap-active'),
                        order_info = order_active.find('.bopobb-cart-info'),
                        order_parent_key = order_active.find('.product-name .bopobb-cart-info').attr('data-parent'),
                        order_key = order_active.find('.product-name .bopobb-cart-info').attr('data-id'),
                        order_variation_string = bopobbCartItems(order_parent_key, order_item_id, order_item_variation);

                    if (order_info.attr('data-product-id') == order_item_id &&
                        order_info.attr('data-variation') == order_item_variation_string) {
                        bopobbClosePopup();
                    } else {
                        if (is_duplicate_item(order_item_id, 'order')) {
                            alert(bopobbVars.alert_duplicate);
                            return;
                        }
                        bopobbOrderUpdate(order_key, order_parent_key, order_variation_string);
                    }
                    break;
                default:
                    let $prd_data = '', prod_img = '', prod_price_html = '', prod_price = '', prod_description = '',
                        sticky_wrap = $('.vi-wcaio-sb-wrap .bopobb-sticky-atc-wrap'), prod_type = '';
                    if (item.closest('.bopobb-option-add-wrap').length) {
                        $prd_data = item.closest('.bopobb-option-product');
                        prod_type = 'variation';
                        prod_img = $prd_data.find('.bopobb-option-image-wrap').html();
                        prod_price_html = $prd_data.find('.bopobb-option-price-wrap .price').html();
                        prod_price = $prd_data.attr('data-price');
                        if ($prd_data.find('.bopobb-variation-description').html() !== '') {
                            prod_description = $prd_data.find('.bopobb-variation-description').html();
                        } else {
                            prod_description = $prd_data.find('.bopobb-product-full-description').html();
                        }
                    } else {
                        $prd_data = item.closest('.bopobb-product');
                        prod_type = $prd_data.attr('data-type');
                        prod_img = item.html();
                        prod_price_html = $prd_data.find('.bopobb-product-price').html();
                        prod_price = $prd_data.attr('data-price');
                        prod_description = $prd_data.find('.bopobb-product-full-description').html();
                    }
                    let prod_regular_title = $prd_data.find('.bopobb-product-title-wrap .bopobb-product-title').html(),
                        prod_title = $prd_data.find('.bopobb-product-title-wrap .bopobb-product-title').html(),
                        prod_id = $prd_data.attr('data-product'),
                        prod_stock_html = $prd_data.find('.bopobb-product-stock').html(),
                        prod_stock = $prd_data.find('.bopobb-product-stock').attr('data-stock'),
                        prod_backorder = $prd_data.find('.bopobb-product-stock').attr('data-backorder'),
                        prod_variable_title = $('.bopobb-popup-header .bopobb-popup-title').html(),
                        prod_ratting = $prd_data.find('.bopobb-product-ratting').html(),
                        prod_short_description = $prd_data.find('.bopobb-product-description').html(),
                        prod_title_des = '',
                        prod_variations = $prd_data.find('.bopobb-product-variations').val() ? $prd_data.find('.bopobb-product-variations').val() : '';
                    if (is_duplicate_item(prod_id)) {
                        alert(bopobbVars.alert_duplicate);
                        return;
                    }
                    if ('1' !== bopobbVars.view_description) {
                        prod_short_description = '';
                    }
                    if ('1' !== bopobbVars.view_full_description) {
                        prod_description = '';
                    }
                    if ('0' === bopobbVars.short_des_position && '0' === bopobbVars.des_position) {
                        if ('' != prod_short_description && '' != prod_description) {
                            prod_title_des = prod_short_description.trim() + '\n' + prod_description.trim();
                        } else {
                            prod_title_des = prod_short_description.trim() + prod_description.trim();
                        }
                    } else {
                        if ('0' === bopobbVars.short_des_position) {
                            prod_title_des = prod_short_description.trim();
                        } else {
                            if ('0' === bopobbVars.des_position) {
                                prod_title_des = prod_description.trim();
                            }
                        }
                    }
                    if (bopobbVars.bopobb_link_individual === '1') {
                        let prod_link = $prd_data.find('.bopobb-product-title-wrap .bopobb-variation-title').length ?
                            $prd_data.find('.bopobb-product-title-wrap .bopobb-variation-title').attr('data-link') :
                            $prd_data.find('.bopobb-product-title-wrap .bopobb-product-title').attr('data-link');
                        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-title').attr('href', prod_link);
                    }
                    if ($('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap.bopobb-template-1').length) {
                        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-top-wrap .bopobb-item-' + index + ' .bopobb-item-img-wrap')
                            .removeClass('bopobb-icon-plus2').css('min-height', 'unset').attr('title', '');
                        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-top-wrap .bopobb-item-' + index + ' .bopobb-item-img')
                            .html(prod_img).attr('title', prod_regular_title.trim());
                    } else {
                        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-img-wrap')
                            .attr('title', '');
                        $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-img')
                            .html(prod_img).attr('title', prod_regular_title.trim()).css('min-height', 'unset');
                    }
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-item-' + index).attr('data-title', prod_variable_title).attr('data-type', prod_type);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-item-' + index + ' .bopobb-item-img-wrap .bopobb-option-remove-wrap').removeClass('bopobb-hidden');
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail .bopobb-item-title')
                        .html(prod_title).attr('title', prod_title_des);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index)
                        .attr('data-id', prod_id).attr('data-price', prod_price).attr('data-max', prod_stock);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail-short-description').html(prod_short_description);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail-description').html(prod_description);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-right .bopobb-item-price').html(prod_price_html);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail .star-rating').remove();
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail .stock').remove();
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail').append(prod_ratting).append(prod_stock_html);
                    $('.bopobb-single-wrap.bopobb-swap-active .bopobb-items-bottom-wrap .bopobb-item-' + index + ' .bopobb-item-detail .bopobb-item-variations').val(prod_variations);
                    if (sticky_wrap.length) {
                        let sticky_item = sticky_wrap.find('.bopobb-sticky-items-wrap .bopobb-sticky-item.bopobb-sticky-item-' + index),
                            sticky_img = sticky_item.find('.bopobb-sticky-item-img');
                        sticky_item.find('.bopobb-sticky-item-img-wrap')
                            .removeClass('bopobb-icon-plus2');
                        sticky_img.html(prod_img).attr('title', prod_regular_title.trim());
                        sticky_img.find('.bopobb-product-zoom').replaceWith('');
                        sticky_item.attr('data-id', prod_id).attr('data-price', prod_price).attr('data-max', prod_stock).attr('data-variations', prod_variations);
                    }
                    $('.bopobb-single-wrap.bopobb-swap-active').addClass('bopobb-initial-process');
                    bopobbClosePopup();
                    bopobbInit($('.bopobb-single-wrap.bopobb-initial-process'), 'change');
            }
        } else {
            if (item && !in_stock) {
                if ('1' !== bopobbVars.out_stock_watermark) {
                    alert(bopobbVars.bopobb_alert_stock);
                }
            }
        }
    }

    function is_duplicate_item(prod_id, caller = '') {
        if (bopobbVars.allow_duplicate_select === '1') {
            return false;
        }
        let is_dup = false;
        switch (caller) {
            case 'cart':
            case 'order':
                let cart_products = $('.bopobb-cart-item.bopobb-cart-child .bopobb-cart-info');
                cart_products.each(function () {
                    let $this = $(this);
                    if (parseInt($this.attr('data-product-id')) > 0) {
                        if ($this.attr('data-product-id') == prod_id) {
                            is_dup = true;
                        }
                    }
                });
                break;
            default:
                let products = $('.bopobb-single-wrap.bopobb-swap-active .bopobb-detail-table');
                products.find('.bopobb-item-product').each(function () {
                    let $this = $(this);
                    if (parseInt($this.attr('data-id')) > 0) {
                        if ($this.attr('data-id') == prod_id) {
                            is_dup = true;
                        }
                    }
                });
        }

        return is_dup;
    }

    function bopobbCartItems(parent_key, item_id, item_variation) {
        let variation_string = '', cart_wrap = '';
        if ($('form.woocommerce-cart-form').length) {
            cart_wrap = 'form.woocommerce-cart-form ';
        }
        let index_count = 0, nulable_variation = true;
        $(cart_wrap + '.bopobb-cart-item.bopobb-cart-child:not(.mini_cart_item) .bopobb-cart-info').each(function () {
            if ('undefined' !== typeof $(this).data('index')) {
                if ($(this).attr('data-parent') == parent_key) {
                    if (index_count < parseInt($(this).data('index'))) {
                        let option_count = parseInt($(this).data('index')) - index_count;
                        for (let i = 0; i < option_count; i++) {
                            index_count++;
                            if (variation_string == '' && nulable_variation) {
                                variation_string = '';
                            } else {
                                variation_string += '%&' + '';
                            }
                            nulable_variation = false;
                        }
                    }

                    if (index_count == parseInt($(this).data('index'))) {
                        let prd_id = $(this).attr('data-product-id');
                        let prd_qty = '%/' + $(this).attr('data-quantity');
                        let prd_variation = $(this).attr('data-variation') ? '%/' + $(this).attr('data-variation') : '';
                        if ($(this).closest('.bopobb-cart-child').hasClass('bopobb-swap-active')) {
                            if (variation_string == '' && nulable_variation) {
                                variation_string = item_id + prd_qty + item_variation;
                            } else {
                                variation_string += '%&' + item_id + prd_qty + item_variation;
                            }
                        } else {
                            if (variation_string == '' && nulable_variation) {
                                variation_string = prd_id + prd_qty + prd_variation;
                            } else {
                                variation_string += '%&' + prd_id + prd_qty + prd_variation;
                            }
                        }
                        index_count++;
                        nulable_variation = false;
                    }
                }
            }
        });
        return variation_string;
    }

    function bopobbCartUpdate(cart_key, parent_key, variation_string, caller = 'item') {
        $("a.checkout-button.wc-forward").addClass('disabled');
        $('.bopobb-cart-child.bopobb-swap-active').find('.bopobb-cart-info').addClass('bopobb-swap-active');
        let cartLoopOverlay = setInterval(function () {
            if (!$("a.checkout-button.wc-forward").hasClass('disabled')) {
                $('.bopobb-cart-child.bopobb-swap-active').find('.bopobb-cart-info').addClass('bopobb-swap-active');
                $('.bopobb-cart-item.bopobb-cart-child').removeClass('bopobb-swap-active');
                clearInterval(cartLoopOverlay);
            }
        }, 500);
        if (caller === 'item') {
            bopobbClosePopup('cart');
        }
        let data = {
            action: 'bopobb_cart_update',
            bopobb_cart_key: cart_key,
            bopobb_cart_parent: parent_key,
            bopobb_cart_item_data: variation_string,
            lang: bopobbVars.language,
            nonce: bopobbVars.nonce,
        };
        $.post(bopobbVars.ajaxurl, data, function (response) {
            bopobbCartRefresh();
        });
    }

    function bopobbCartRefresh() {
        // some themes creates multiple cart forms so it will try to find the correct update button
        let mainSelector = $(document);
        if ($('.bopobb-cart-child.bopobb-swap-active').closest('.woocommerce-cart-form').length) {
            mainSelector = $('.bopobb-cart-child.bopobb-swap-active').closest('.woocommerce-cart-form');
        }

        // deal with update cart button
        let updateButton = mainSelector.find("button[name='update_cart']:not(.dgfw-add-gift-button),input[name='update_cart']:not(.dgfw-add-gift-button)");

        updateButton.removeAttr('disabled').trigger('click').prop('disabled', true);

    }

    function bopobbOrderUpdate(oder_key, oder_parent_key, oder_variation_string, caller = 'item') {
        $('.bopobb-cart-child.bopobb-swap-active').find('.bopobb-cart-info').addClass('bopobb-swap-active');
        let cartLoopOverlay = setInterval(function () {
            if ($(".bopobb-cart-child.bopobb-swap-active").find('.product-name .bopobb-cart-info').attr('data-id') != oder_key) {
                $('.bopobb-cart-child.bopobb-swap-active').find('.bopobb-cart-info').removeClass('bopobb-swap-active');
                $('.bopobb-cart-item.bopobb-cart-child').removeClass('bopobb-swap-active');
                clearInterval(cartLoopOverlay);
            }
        }, 500);

        if (caller === 'item') {
            bopobbClosePopup('order');
        }
        let data = {
            action: 'bopobb_cart_update',
            bopobb_cart_key: oder_key,
            bopobb_cart_parent: oder_parent_key,
            bopobb_cart_item_data: oder_variation_string,
            lang: bopobbVars.language,
            nonce: bopobbVars.nonce,
        };
        $.post(bopobbVars.ajaxurl, data, function (response) {
            $(document.body).trigger('update_checkout');
        });
    }

    function bopobbDisableScroll() {
        if (bopobbVars.bundle_scroll_animation === '1') {
            if ($(document).height() > $(window).height()) {
                let scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop();
                if (!document.body.classList.contains('theme-Divi') || document.body.classList.contains('et_divi_theme')) {
                    $('html').addClass('bopobb-html-scroll').css('top', -scrollTop);
                } else {
                    $('html').addClass('bopobb-html-scroll');
                }
            }
        }
    }

    function bopobbEnableScroll() {
        if (bopobbVars.bundle_scroll_animation === '1') {
            let scrollTop = parseInt($('html').css('top'));
            $('html').removeClass('bopobb-html-scroll');
            if (!document.body.classList.contains('theme-Divi') || document.body.classList.contains('et_divi_theme')) {
                $('html,body').scrollTop(-scrollTop);
            }
        }
    }

    function bopobb_calc_price($container) {
        let total = 0,
            total_sale = 0,
            $wrap = $container.find('.bopobb-single-wrap'),
            wrap_id = $wrap.attr('data-id'),
            $products = $container.find('.bopobb-detail-table'),
            price_suffix = $products.attr('data-price-suffix'),
            $total = $container.find('.bopobb-total'),
            $woobt = $('.woobt-wrap-' + wrap_id),
            total_woobt = parseFloat($woobt.length ? $woobt.attr('data-total') : 0),
            discount = 0,
            discount_amount = 0,
            fixed_price = $products.attr('data-fixed-price'),
            fixed_sale = $products.attr('data-fixed-sale'),
            flex_no_discount = true,
            saved = '',
            fix = Math.pow(10, Number(bopobbVars.price_decimals) + 1),
            tax_include = $container.find('.bopobb-detail-table').attr('data-tax-include'),
            tax_view = $container.find('.bopobb-detail-table').attr('data-tax-view'),
            tax_exempt = $container.find('.bopobb-detail-table').attr('data-tax-exempt'),
            tax_rate = parseFloat($container.find('.bopobb-detail-table').attr('data-tax-rate')),
            $sticky_items = $('.vi-wcaio-sb-wrap .bopobb-sticky-atc-wrap');

        let arr_price = {};
        $products.find('.bopobb-item-product').each(function (i, e) {
            let $this = $(this);
            let t_id = $this.data('id');
            let t_qty = $this.data('qty') ?? 1;
            let temp_arr_price = {};

            if (parseFloat($this.attr('data-price')) > 0) {
                let this_price = parseFloat($this.attr('data-price')) * parseFloat($this.attr('data-qty'));
                let l_price = this_price;

                if (tax_view == 1 && tax_exempt == 0) {
                    total += this_price + (this_price * (tax_rate / 100));
                } else {
                    total += this_price;
                }
                discount = $this.attr('data-discount-type');
                discount_amount = parseFloat($this.attr('data-discount-number'));

                temp_arr_price['id'] = t_id;
                temp_arr_price['qty'] = t_qty;
                temp_arr_price['this_price'] = this_price;
                temp_arr_price['l_price'] = l_price;
                temp_arr_price['discount'] = discount;
                temp_arr_price['discount_amount'] = discount_amount;
                temp_arr_price['tax_view'] = tax_view;
                temp_arr_price['tax_rate'] = tax_rate;
                temp_arr_price['tax_exempt'] = tax_exempt;
                temp_arr_price['fix'] = fix;
                if (typeof wooMultiCurrencyParams !== 'undefined') {
                    temp_arr_price['current_currency'] = wooMultiCurrencyParams.current_currency ?? '';
                }
                arr_price[i] = temp_arr_price;

                if (discount_amount != 0) {
                    flex_no_discount = false;
                }
                /*Run if Curcy beautiful price not set*/
                if ((typeof bopobbVars.vi_curcy == 'undefined') || bopobbVars.vi_curcy === '0') {
                    if (discount === '0') {
                        this_price *= (100 - discount_amount) / 100;
                        this_price = Math.round(this_price * fix) / fix;
                    } else if (discount === '1') {
                        this_price = discount_amount >= this_price ? 0 : this_price - discount_amount;
                        this_price = Math.round(this_price * fix) / fix;
                    } else if (discount === '2') {
                        this_price = discount_amount;
                        this_price = Math.round(this_price * fix) / fix;
                    }
                    if (tax_view == 1 && tax_exempt == 0) {
                        l_price += l_price * (tax_rate / 100);
                        this_price += this_price * (tax_rate / 100);
                    }
                    let l_total_html = '';
                    if (discount_amount != 0) {
                        l_total_html = bopobb_price_html(l_price, this_price);
                    } else {
                        if (discount === '2') {
                            l_total_html = bopobb_price_html(l_price, this_price);
                        } else {
                            l_total_html = bopobb_price_html(l_price, l_price);
                        }
                    }
                    $(this).find('.bopobb-item-right .bopobb-item-price').html(l_total_html);
                    total_sale += this_price;
                }
            }
        });
        /*Change l_total_html get method to ajax for Curcy compatibility */
        if ((typeof bopobbVars.vi_curcy !== 'undefined') && bopobbVars.vi_curcy === '1') {
            $.ajax({
                type: 'post',
                url: bopobbVars.ajaxurl,
                data: {
                    action: 'bopobb_calc_price_ajax',
                    nonce: bopobbVars.nonce,
                    bundle_items: arr_price,
                },
                success(data) {

                    if (data.success) {
                        let bundle_items = data.data;
                        $products.find('.bopobb-item-product').each(function (i, e) {
                            $(this).find('.bopobb-item-right .bopobb-item-price').html(bundle_items[i]['html']);
                            total_sale += parseFloat(bundle_items[i]['price']);
                        });
                        // fix js number https://www.w3schools.com/js/js_numbers.asp
                        total = bopobb_round(total, bopobbVars.price_decimals);

                        if (fixed_price != 0) {
                            total_sale = parseFloat($products.attr('data-fixed-sale') !== '' ? $products.attr('data-fixed-sale') : 0);
                            saved = bopobb_format_price(total_sale - fixed_sale);
                        } else {
                            if (!flex_no_discount) {
                                let total_sale_amount = total - total_sale;
                                saved = bopobb_format_price(total_sale_amount);
                            } else {
                                total_sale = total;
                            }
                        }

                        let total_html = bopobb_price_html(total, total_sale);
                        let total_all_html = bopobb_price_html(total + total_woobt, total_sale + total_woobt);
                        if (saved != '') {
                            total_html += ' <small class="woocommerce-price-suffix">' + bopobbVars.saved_text.replace('[d]', saved) + '</small>';
                        }

                        let price_selector = '.price';

                        if ((fixed_price == 0)) {
                            // change the main price
                            $container.find(price_selector).html(total_html + price_suffix);
                            if ($sticky_items.length) {
                                $sticky_items.closest('.vi-wcaio-sb-wrap').find('.vi-wcaio-sb-product-price-wrap .price').html(total_html + price_suffix)
                            }
                        }
                        $(document).trigger('bopobb_calc_price', [total_sale, total, total_html, price_suffix]);
                    }
                },
                error(res) {
                    // console.log(res)
                },
            });
        }
        if ((typeof bopobbVars.vi_curcy == 'undefined') || !bopobbVars.vi_curcy) {
// fix js number https://www.w3schools.com/js/js_numbers.asp
            total = bopobb_round(total, bopobbVars.price_decimals);

            if (fixed_price != 0) {
                total_sale = parseFloat($products.attr('data-fixed-sale') !== '' ? $products.attr('data-fixed-sale') : 0);
                saved = bopobb_format_price(total_sale - fixed_sale);
            } else {
                if (!flex_no_discount) {
                    let total_sale_amount = total - total_sale;
                    saved = bopobb_format_price(total_sale_amount);
                } else {
                    total_sale = total;
                }
            }

            let total_html = bopobb_price_html(total, total_sale);
            let total_all_html = bopobb_price_html(total + total_woobt,
                total_sale + total_woobt);
            if (saved != '') {
                total_html += ' <small class="woocommerce-price-suffix">' +
                    bopobbVars.saved_text.replace('[d]', saved) + '</small>';
            }

            let price_selector = '.price';

            if ((fixed_price == 0)) {
                // change the main price
                $container.find(price_selector).html(total_html + price_suffix);
                if ($sticky_items.length) {
                    $sticky_items.closest('.vi-wcaio-sb-wrap').find('.vi-wcaio-sb-product-price-wrap .price').html(total_html + price_suffix)
                }
            }

            $(document).trigger('bopobb_calc_price', [total_sale, total, total_html, price_suffix]);
        }

    }

    function bopobb_change_price($product, price, regular_price, price_html) {
        let $products = $product.closest('.bopobb-products');
        let price_suffix = $product.attr('data-price-suffix');

        // hide ori price
        $product.find('.bopobb-price-ori').hide();

        // calculate new price
        if (bopobbVars.bundled_price === 'subtotal') {
            let ori_price = parseFloat(price) *
                parseFloat($product.attr('data-qty'));

            if (bopobbVars.bundled_price_from === 'regular_price' &&
                regular_price !== undefined) {
                ori_price = parseFloat(regular_price) *
                    parseFloat($product.attr('data-qty'));
            }

            let new_price = ori_price;

            if (parseFloat($products.attr('data-discount')) > 0) {
                new_price = ori_price *
                    (100 - parseFloat($products.attr('data-discount'))) / 100;
            }

            $product.find('.bopobb-price-new').html(bopobb_price_html(ori_price, new_price) + price_suffix).show();
        } else {
            if (parseFloat($products.attr('data-discount')) > 0) {
                let ori_price = parseFloat(price);

                if (bopobbVars.bundled_price_from === 'regular_price' &&
                    regular_price !== undefined) {
                    ori_price = parseFloat(regular_price);
                }

                let new_price = ori_price *
                    (100 - parseFloat($products.attr('data-discount'))) / 100;
                $product.find('.bopobb-price-new').html(bopobb_price_html(ori_price, new_price) + price_suffix).show();
            } else {
                if (bopobbVars.bundled_price_from === 'regular_price' &&
                    regular_price !== undefined) {
                    $product.find('.bopobb-price-new').html(bopobb_price_html(regular_price) + price_suffix).show();
                } else if (price_html !== '') {
                    $product.find('.bopobb-price-new').html(price_html).show();
                }
            }
        }
    }

    function bopobb_check_qty($qty) {
        let $wrap = $qty.closest('.bopobb-single-wrap');
        let qty = parseFloat($qty.val());
        let min = parseFloat($qty.attr('min'));
        let max = parseFloat($qty.attr('max'));

        if ((qty === '') || isNaN(qty)) {
            qty = 0;
        }

        if (!isNaN(min) && (
            qty < min
        )) {
            alert(bopobbVars.alert_min_item.replace('[d]', min));
            qty = min;
        }

        if (!isNaN(max) && (
            qty > max
        )) {
            alert(bopobbVars.alert_max_item.replace('[d]', max));
            qty = max;
        }

        $qty.val(qty);
        $qty.closest('.bopobb-product').attr('data-qty', qty);

        // change subtotal
        if (bopobbVars.bundled_price === 'subtotal') {
            let $products = $wrap.find('.bopobb-detail-table'),
                $product = $qty.closest('.bopobb-item-product');

            $product.attr('data-qty', qty)
        }

        bopobbInit($wrap, 'qty');

        $(document).trigger('bopobb_check_qty', [qty, $qty]);
    }

    function bopobb_cart_qty($qty, caller) {
        let $wrap = $qty.closest('.bopobb-cart-item.bopobb-cart-child');
        let qty = parseFloat($qty.val());
        let def = parseFloat($qty.data('value'));
        let min = parseFloat($qty.attr('min'));
        let max = parseFloat($qty.attr('max'));
        if ((qty === '') || isNaN(qty)) {
            qty = def;
        }

        if (!isNaN(min) && (
            qty < min
        )) {
            qty = def;
            alert(bopobbVars.alert_min_item.replace('[d]', min));
        }

        if (!isNaN(max) && (
            qty > max
        )) {
            qty = def;
            alert(bopobbVars.alert_max_item.replace('[d]', max));
        }
        if (qty == def) {
            $qty.val(qty);
            return;
        }
        $wrap.addClass('bopobb-swap-active');
        let variation_string = '';
        let active_info = $wrap.find('.bopobb-cart-info');
        active_info.data('quantity', qty);
        let index_count = 0, nulable_variation = true;
        $('.bopobb-cart-item.bopobb-cart-child:not(.mini_cart_item) .bopobb-cart-info').each(function () {
            let variation_current = $(this).data('variation') != '' ? '%/' + $(this).data('variation') : '';
            if ('undefined' !== typeof $(this).data('index') && $(this).data('parent') == active_info.data('parent')) {
                if (index_count < parseInt($(this).data('index'))) {
                    let option_count = parseInt($(this).data('index')) - index_count;
                    for (let i = 0; i < option_count; i++) {
                        index_count++;
                        if (variation_string == '' && nulable_variation) {
                            variation_string = '';
                        } else {
                            variation_string += '%&' + '';
                        }
                        nulable_variation = false;
                    }
                }

                if (index_count == parseInt($(this).data('index'))) {
                    if (variation_string == '' && nulable_variation) {
                        variation_string = $(this).data('product-id') + '%/' + $(this).data('quantity') + variation_current;
                    } else {
                        variation_string += '%&' + $(this).data('product-id') + '%/' + $(this).data('quantity') + variation_current;
                    }
                    index_count++;
                    nulable_variation = false;
                }
            }
        });

        if (caller === 'cart') {
            bopobbCartUpdate(active_info.data('id'), active_info.data('parent'), variation_string, 'qty');
        } else {
            bopobbOrderUpdate(active_info.data('id'), active_info.data('parent'), variation_string, 'qty');
        }
    }

    function bopobb_price_html(regular_price, sale_price) {
        let price_html = '';

        if (sale_price < regular_price) {
            price_html = '<del>' + bopobb_format_price(regular_price) + '</del> <ins>' +
                bopobb_format_price(sale_price) + '</ins>';
        } else {
            price_html = bopobb_format_price(regular_price);
        }

        return price_html;
    }

    function bopobb_format_price(price) {
        let price_html = '<span class="woocommerce-Price-amount amount">';
        let price_formatted = bopobb_format_money(price, bopobbVars.price_decimals, '',
            bopobbVars.price_thousand_separator, bopobbVars.price_decimal_separator);

        switch (bopobbVars.price_format) {
            case '%1$s%2$s':
                //left
                price_html += '<span class="woocommerce-Price-currencySymbol">' +
                    bopobbVars.currency_symbol + '</span>' + price_formatted;
                break;
            case '%1$s %2$s':
                //left with space
                price_html += '<span class="woocommerce-Price-currencySymbol">' +
                    bopobbVars.currency_symbol + '</span> ' + price_formatted;
                break;
            case '%2$s%1$s':
                //right
                price_html += price_formatted +
                    '<span class="woocommerce-Price-currencySymbol">' +
                    bopobbVars.currency_symbol + '</span>';
                break;
            case '%2$s %1$s':
                //right with space
                price_html += price_formatted +
                    ' <span class="woocommerce-Price-currencySymbol">' +
                    bopobbVars.currency_symbol + '</span>';
                break;
            default:
                //default
                price_html += '<span class="woocommerce-Price-currencySymbol">' +
                    bopobbVars.currency_symbol + '</span> ' + price_formatted;
        }

        price_html += '</span>';

        return price_html;
    }

    function bopobb_format_money(number, places, symbol, thousand, decimal) {
        number = number || 0;
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        symbol = symbol !== undefined ? symbol : '$';
        thousand = thousand || ',';
        decimal = decimal || '.';

        let negative = number < 0 ? '-' : '',
            i = parseInt(
                number = bopobb_round(Math.abs(+number || 0), places).toFixed(places),
                10) + '',
            j = 0;

        if (i.length > 3) {
            j = i.length % 3;
        }

        return symbol + negative + (
            j ? i.substr(0, j) + thousand : ''
        ) + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) + (
            places ?
                decimal +
                bopobb_round(Math.abs(number - i), places).toFixed(places).slice(2) :
                ''
        );
    }

    function bopobb_round(value, decimals) {
        return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
    }

    function bopobb_option_check(btn_add, frm_data) {
        if (frm_data.attr('data-ready') == 1) {
            btn_add.removeClass('bopobb-disable');
        } else {
            btn_add.addClass('bopobb-disable');
        }
    }

    function bopobb_VariationsIsMatch(variation_attributes, attributes) {
        let match = true;
        for (let attr_name in variation_attributes) {
            if (variation_attributes.hasOwnProperty(attr_name)) {
                let val1 = variation_attributes[attr_name];
                let val2 = attributes[attr_name];
                if (val1 !== undefined && val2 !== undefined && val1.length !== 0 && val2.length !== 0 && val1 !== val2) {
                    match = false;
                }
            }
        }
        return match;
    }

    function bopobb_findMatchingVariations(variations, attributes) {
        let matching = [];
        for (let i = 0; i < variations.length; i++) {
            let variation = variations[i];

            if (bopobb_VariationsIsMatch(variation.attributes, attributes)) {
                matching.push(variation);
            }
        }
        return matching;
    }

    function bopobb_getChosenAttributes(element) {
        let data = {};
        let count = 0;
        let chosen = 0;
        element.find('.bopobb-option-select').each(function () {
            let attribute_name = $(this).data('attribute-name') || $(this).attr('name');
            let value = $(this).val() || '';

            if (value.length > 0) {
                chosen++;
            }
            count++;
            data[attribute_name.toLowerCase()] = value;
        });

        return {
            'count': count,
            'chosenCount': chosen,
            'data': data
        };
    }

    function bopobbAjaxSearchFilter(digit, filter_wrap) {
        let item_id_product = $(filter_wrap).closest('.bopobb-product-list').attr('data-product'),
            item_index = $(filter_wrap).closest('.bopobb-product-list').attr('data-item'),
            filter_cat = $(filter_wrap).find('.bopobb-category-filter').val();
        $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html('').addClass('bopobb-loading');
        let data = {
            action: 'bopobb_product_list',
            item: item_index,
            product: item_id_product,
            category: filter_cat,
            key: digit,
            page: 1,
            lang: bopobbVars.language,
            nonce: bopobbVars.nonce,
        };
        $.post(bopobbVars.ajaxurl, data, function (response) {
            $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').html(response['products']);
            setTimeout(function () {
                $('.bopobb-area .bopobb-inner .bopobb-popup .bopobb-product-list').removeClass('bopobb-loading');
                $('.bopobb-area .bopobb-popup .bopobb-product-list .bopobb-product-paging-wrap .bopobb-category-filter option[value="' + filter_cat + '"]').attr("selected", true);
            }, 100)
        });
    }

    $.fn.bopobbfadeSlideRight = function (speed, fn) {
        return $(this).animate({
            'opacity': 1,
            'width': '750px'
        }, speed || 400, function () {
            $.isFunction(fn) && fn.call(this);
        });
    };

    $.fn.bopobbfadeSlideLeft = function (speed, fn) {
        return $(this).animate({
            'opacity': 0,
            'width': '0px'
        }, speed || 400, function () {
            $.isFunction(fn) && fn.call(this);
        });
    };

    $.fn.bopobbSlideLeft = function (speed, opacity, left, fn) {
        if (opacity == 0) $(this).css('visibility', 'hidden'); else $(this).css('visibility', 'visible');
        if ('rtl' === $('html').attr('dir')) {
            return $(this).animate({
                'opacity': opacity,
                'right': '-' + left + 'px'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        } else {
            return $(this).animate({
                'opacity': opacity,
                'left': '-' + left + 'px'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        }
    };

    $.fn.bopobbLeftReset = function (speed, opacity, fn) {
        if (opacity == 0) $(this).css('visibility', 'hidden'); else $(this).css('visibility', 'visible');
        if ('rtl' === $('html').attr('dir')) {
            return $(this).animate({
                'opacity': opacity,
                'right': '0'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        } else {
            return $(this).animate({
                'opacity': opacity,
                'left': '0'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        }
    };

    $.fn.bopobbSlideRight = function (speed, opacity, right, fn) {
        if (opacity == 0) $(this).css('visibility', 'hidden'); else $(this).css('visibility', 'visible');
        if ('rtl' === $('html').attr('dir')) {
            return $(this).animate({
                'opacity': opacity,
                'right': right + 'px'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        } else {
            return $(this).animate({
                'opacity': opacity,
                'left': right + 'px'
            }, speed || 400, function () {
                $.isFunction(fn) && fn.call(this);
            });
        }
    };
});