// source --> https://maskinexperten.com/wp-content/plugins/dp-elementor-addons/assets/js/misc.js?ver=1.1.7 
jQuery(document).ready(function ($) {

    $(document).on('click', '.wc-quant-minus, .wc-quant-plus', function(e) {

        const action = $(this).val();
        const qty = $(this).siblings('input.qty');
        const min = qty.attr('min');
        let amount = parseInt( qty.val() );

        if ( ! amount ) amount = 1;

        switch( action ) {
            case '+':
                amount++;
              break;
            case '-':
                amount--;
              break;
            default:
                amount = amount;
        }

        if ( amount < 1 ) amount = 1;
        if ( amount < min ) amount = min;

        qty.val( amount );
        qty.trigger('change');

    });
    
    $(document).on('change', 'input.qty', function(e) {
        const min = $(this).attr('min');
        if ( parseInt( $(this).val() ) < min ) $(this).val(min); 
        $("[name='update_cart']").attr('disabled',false).trigger("click").attr('disabled',true);
    });
    /*
    $(document).on('click', '.dp-product', function(e) {
        if ( $(e.target).hasClass('dp-quickview') || $(e.target).parent().hasClass('dp-quickview') ) return;
        if ( $(e.target).hasClass('dp-add-to-cart') || $(e.target).parent().hasClass('dp-add-to-cart') ) return;
        window.location.href = $(this).data('url');
    });
    */
    $(document).on('click', '.dp-quickview', function(e) {

        const product_id = $(this).data('id');

        jQuery.ajax({
            url: dpmisc.ajaxurl,
            type: "POST",
            data: {
                action: 'dp_load_quickview',
                product_id: product_id,
            },
            beforeSend: function() {
                $('.dp-popup-container .dp-popup-content').html('');
            },
            success: function (res) { 
                $('.dp-popup-container .dp-popup-content').html(res.html);
                $('.dp-popup-container').addClass('active');
            },
            error: function(res) {
            },
            complete: function(res) {
            }
        });

    });

    $(document).on('mouseenter touchstart', '.dp-product .colors a.color', function(e) {

        const gallery = $(this).parents('.dp-product').find('.gallery-images');
        const image = $(this).parents('.dp-product').find('.thumbnail > img');
        const image_url = $(this).data('image');

        if ( image_url ) {

            image.attr('srcset', '');
            image.attr('src', image_url);

            if ( gallery.length && gallery.find('div[data-image="'+image_url+'"]').length ) {
                gallery.find('div').removeClass('active');
                gallery.find('div[data-image="'+image_url+'"]').addClass('active');
            }

        }

        $(this).siblings().removeClass('active');
        $(this).addClass('active');

    });

    $(document).on('mouseleave touchend', '.dp-product .colors .color', function(e) {
        $(this).removeClass('active');
    });

    $(document).on('click', '.dp-product .gallery-button', function(e) {

        const image = $(this).parents('.dp-product').find('.thumbnail > img');
        const gallery = $(this).siblings('.gallery-images');
        const action = $(this).data('action');
        let image_url = '';

        if ( action == 'next' ) {
            let active = gallery.find('.active');
            if ( ! active.length ) active = gallery.find('div').first();
            let next = active.next();
            if ( ! next.length ) next = gallery.find('div').first();
            active.removeClass('active');
            next.addClass('active');
            image_url = next.data('image');
        }

        if ( action == 'prev' ) {
            let active = gallery.find('.active');
            if ( ! active.length ) active = gallery.find('div').first();
            let prev = active.prev();
            if ( ! prev.length ) prev = gallery.find('div').last();
            active.removeClass('active');
            prev.addClass('active');
            image_url = prev.data('image');
        }

        if ( image_url ) {
            image.attr('srcset', '');
            image.attr('src', image_url);
        }

    });

    $(document).on('click', '.dp-popup-container', function(e) {
        if ( e.target == this ) {
            $('.dp-popup-container').removeClass('active');
        }
    });

    $(document).on('click', '.single_add_to_cart_button:not(.disabled)', function (e) {

        if ( ! dpmisc.ajaxcart || dpmisc.ajaxcart == undefined || dpmisc.ajaxcart == 0 ) {
            return;
        }

        e.preventDefault();

        const button = $(this);
        const form = button.closest('form.cart');
        const id = button.val();
        const product_qty = form.find('input[name=quantity]').val() || 1;
        const product_id = form.find('input[name=product_id]').val() || id;
        const variation_id = form.find('input[name=variation_id]').val() || 0;

        const data = {
            action: 'dp_woocommerce_ajax_add_to_cart',
            product_id: product_id,
            product_sku: '',
            quantity: product_qty,
            variation_id: variation_id,
            form: form.serializeArray(),
        };

        $(document.body).trigger('adding_to_cart', [button, data]);

        $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            beforeSend: function (response) {
                button.addClass('loading');
            },
            success: function (response) {

                if ( response.error & response.product_url ) {
                    window.location = response.product_url;
                    return;
                }else {
                    $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, button]);  
                }

                if ( wc_add_to_cart_params.cart_redirect_after_add == 'yes' ) {
                    window.location = wc_add_to_cart_params.cart_url;
                }

            },
            complete: function (response) {
                button.removeClass('loading');
                button.addClass('added');
                setTimeout(function() {
                    button.removeClass('added');
                }, 1500);
            },
        });

        return false;

    });

    $(document).on( 'found_variation', 'form.cart', function( event, variation ) {
		
		$.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'dp_get_variation_price',
				variation_id: variation.variation_id,
            },
            beforeSend: function() {
            },
            success: function( res ) {
				$(document).trigger( 'dp_found_variation', res );
            },
            complete: function() {
            },
        });
		
	});
    
});















    /*
    let initialPrice = '';
    function increaseAmount () {
    var amountInputContainer = document.getElementsByClassName('woocommerce-variation-add-to-cart')[0]?.firstElementChild ? document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].firstElementChild : document.getElementsByClassName('elementor-add-to-cart')[0].firstElementChild.firstElementChild;
        var currentValue = amountInputContainer.querySelectorAll('[name="quantity"]')[0].value !== '' ? parseInt(amountInputContainer.querySelectorAll('[name="quantity"]')[0].value) : 0;
        amountInputContainer.querySelectorAll('[name="quantity"]')[0].value = currentValue + 1;
    }
    function decreaseAmount () {
        var amountInputContainer = document.getElementsByClassName('woocommerce-variation-add-to-cart')[0]?.firstElementChild ? document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].firstElementChild : document.getElementsByClassName('elementor-add-to-cart')[0].firstElementChild.firstElementChild;
        var currentValue = amountInputContainer.querySelectorAll('[name="quantity"]')[0].value !== '' ? parseInt(amountInputContainer.querySelectorAll('[name="quantity"]')[0].value) : 0;
        amountInputContainer.querySelectorAll('[name="quantity"]')[0].value = currentValue === 0 ? currentValue : currentValue - 1;
    }
    window.addEventListener('load',
        function() {
            initialPrice = document.getElementById('main-price-custom').innerHTML;
            var amountInput = document.getElementsByClassName('woocommerce-variation-add-to-cart')[0]?.firstElementChild ? document.getElementsByClassName('woocommerce-variation-add-to-cart')[0].firstElementChild : document.getElementsByClassName('elementor-add-to-cart')[0].firstElementChild.firstElementChild;
            amountInput.style.display = 'flex';
            amountInput.insertAdjacentHTML("afterbegin", '<span style="background:#F8F8F8; font-size: 24px;cursor: pointer;display:flex; align-items:center;width:34px;justify-content:center;    user-select: none;" onclick="decreaseAmount()">-</span>');
            amountInput.insertAdjacentHTML("beforeend", '<span style="background:#F8F8F8; font-size: 24px;cursor: pointer;display:flex; align-items:center;width:34px;justify-content:center;    user-select: none;" onclick="increaseAmount()">+</span>');
            var variations = document.getElementsByClassName('variations')[0];
            if (variations) {
              var selects = variations.querySelectorAll('select');
                for (let select of selects) {
                    select.addEventListener('change', preselectVariations);
                    // if (select.options.length == 2) {
                    //     select.parentNode.parentNode.style.display = 'none';
                    // }
                }
                for (let span of document.getElementsByClassName('variable-item-span')) {
                    span.addEventListener('click', preselectVariations);
                    // if (select.options.length == 2) {
                    //     select.parentNode.parentNode.style.display = 'none';
                    // }
                }
                document.getElementsByClassName('reset_variations')[0].addEventListener('click', () => {
                        setTimeout(() => {
                            jQuery('.dp-tax-toggle input').trigger("change")
                            preselectVariations();
                        }, 200);
                    });
            }
            setTimeout(() => {
                preselectVariations();                
            }, 0);
        }
    );
    
    function preselectVariations(tax = null) {
        var variations = document.getElementsByClassName('variations')[0];
        var attributeEmpty = false;
        if (variations) {
           var selects = variations.querySelectorAll('select');
            for (let select of selects) {
                setTimeout(() => {
                    let queryParams = new URLSearchParams(window.location.search);
                    queryParams.set(select.name, select.value);
                    history.pushState({}, null, window.location.href.split('?')[0] + `?${queryParams}`);
                }, 100);
                if (select.options.length == 2) {
                    select.selectedIndex = 1;
                }
                if (select.value === null || select.value === '') {
                    attributeEmpty = true;
                }
            }
        }
                                                
        setTimeout(() => {
            document.querySelector('.zoomImg')?.remove();
        document.getElementsByClassName('woocommerce-product-gallery__image')[0].querySelector('a').classList.add('image-for-zoom');
        jQuery('.image-for-zoom').zoom({url: document.getElementsByClassName('woocommerce-product-gallery__image')[0].querySelector('a').getAttribute('href')});
        if (window.innerWidth < 768) {
            jQuery('.image-for-zoom').trigger('zoom.destroy');
        }
        if (window.innerWidth < 968 && !attributeEmpty) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
        }, 100);
        
        setTimeout(() => {
            if (document.getElementsByClassName('woocommerce-variation-price')[0]) {
                document.getElementById('main-price-custom').innerHTML = document.getElementsByClassName('single_variation')[0]?.style.display == 'none' ? initialPrice : document.getElementsByClassName('woocommerce-variation-price')[0].innerHTML;
 
                document.getElementById('main-price-custom-mobile').innerHTML = document.getElementsByClassName('single_variation')[0]?.style.display == 'none' ? initialPrice : document.getElementsByClassName('woocommerce-variation-price')[0].innerHTML;                    

                if (typeof tax !== 'string') {
                    tax = Cookies.get('dp_user_tax') ? JSON.parse(Cookies.get('dp_user_tax'))?.tax : 'private';
                }
                 document.getElementById('main-price-custom').querySelector('.dp-prices').style.display = 'block';
              document.getElementById('main-price-custom-mobile').querySelector('.dp-prices').style.display = 'block';
                 if (document.getElementsByClassName('single_variation')[0]?.style.display == 'none') {
                    document.getElementById('main-price-custom').querySelector('.woocommerce-Price-amount').style.display = 'inline';    
                    document.getElementById('main-price-custom').querySelector('.dp-prices').style.display = 'none'; 
                    document.getElementById('main-price-custom-mobile').querySelector('.woocommerce-Price-amount').style.display = 'inline';      
                    document.getElementById('main-price-custom-mobile').querySelector('.dp-prices').style.display = 'none';      
                 } else {
                    document.getElementById('main-price-custom').querySelector('.woocommerce-Price-amount').style.display = 'none';
                    document.getElementById('main-price-custom-mobile').querySelector('.woocommerce-Price-amount').style.display = 'none';
                 };
                if (tax === 'business') {
                 document.getElementById('main-price-custom').querySelector('.excl').style.display = 'block';
                 document.getElementById('main-price-custom').querySelector('.incl').style.display = 'none';
                 document.getElementById('main-price-custom-mobile').querySelector('.excl').style.display = 'block';
                 document.getElementById('main-price-custom-mobile').querySelector('.incl').style.display = 'none';
                } else {
                    document.getElementById('main-price-custom').querySelector('.excl').style.display = 'none';
                    document.getElementById('main-price-custom').querySelector('.incl').style.display = 'block';
                    document.getElementById('main-price-custom-mobile').querySelector('.excl').style.display = 'none';
                    document.getElementById('main-price-custom-mobile').querySelector('.incl').style.display = 'block';
                }
            }
        }, 100);
    }
    let isFirstClick = false;
    window.addEventListener('load',
        function() {
            console.log('template 1')
            const firstVariationsWrapper = document.getElementsByClassName('variable-items-wrapper')[0];
                            for (let span of firstVariationsWrapper.getElementsByClassName('variable-item-span')) {
                    span.addEventListener('click', function () {
 
                        let isFirst = true;
                        for (let wrapper of document.getElementsByClassName('variable-items-wrapper')) {
                            let isSelected = false;
                            for (let span of wrapper.getElementsByClassName('variable-item-span')) {
                                if (span.parentNode.parentNode.classList.contains('selected')) {
                                    isSelected = true;
                                }
                            }
                            if (!isFirst && !isSelected) {
                                wrapper.getElementsByClassName('variable-item-span')[0].click();
                            }
                            isFirst = false;
                        }
                    });
                }
                
            document.getElementById('js-mobile-description').innerHTML = document.getElementById('js-description').innerHTML;
            
  var elem = document.createElement('img');
  elem.setAttribute('src', 'https://enwex.se/wp-content/uploads/2023/05/product-badges-1.png');
  elem.style.width = '130px';
  elem.style.position = 'absolute';
    elem.style.top = '1px';
    elem.style.right = '60px';
   document.getElementsByClassName('woocommerce-product-gallery__image')[0]. querySelector
('a').style.position = 'relative';
  document.getElementsByClassName('woocommerce-product-gallery__image')[0].querySelector
('a').prepend(elem);

        }
    )
    
    jQuery(document).on('change', '.dp-tax-toggle input', function(e) {
        let tax = jQuery(this).is(':checked') ? 'business' : 'private';
        setTimeout(() => {
          preselectVariations(tax);  
        }, 200)
    });
*/;