feather.replace();

$(document).ready(function() {

    // Homepage slider swipes on mobile
    var touchStartX = 0;

    $('.carousel').on('touchstart', function(e) {
        touchStartX = e.originalEvent.touches[0].pageX;
    });

    $('.carousel').on('touchend', function(e) {
        var touchEndX = e.originalEvent.changedTouches[0].pageX;
        var diff = touchEndX - touchStartX;

        if (diff > 50) {
            $(this).carousel('prev');
        } else if (diff < -50) {
            $(this).carousel('next');
        }
    });

    $('.swatch-option-selector').change(function () {

		$('.swatch-label').removeClass('swatch-active');
		$('.swatch-option-selector:checked').next().addClass('swatch-active');

	});

    
    // Clear form on window load
    $(window).on('load', function(){
        clearForm();
    });

    $('#carousel-gallery').find('.carousel-inner').find(':first-child').addClass('active');

    // Init carousel
    $('#carousel-gallery').carousel({
        interval: false,
        pause: true
    });

    // Hover carousel
    $('.carousel-thumbnails li').hover(function(){
        var goto = Number($(this).attr('data-slide-to'));
        $('.carousel-thumbnails').carousel(goto);
    });

    // Radio button is the variant
    $('.single-option-selector__radio.radio-variant').on('change',function() {
        var variantId = $(this).val(), selectedVariant = $('#variant_' + variantId);

        disabledButtons();
        // resetInputQuantity(0);
        updateThumbnailImage(variantId);
        // $('#max-product-quantity').text(0);
        // $('#max-product-quantity').attr('value', 0);

        if(selectedVariant.data('available')){
            updateSelectedOptionsVariant(variantId);
            enableButtons();
            // resetInputQuantity(1);
            updatePriceText();
            // updateQuantityText();
            // showQuantityText();
        }
    });
    
    // Radio button is the option value
    $('.option').change(function(){
        var optionsLength = $($('#list-variants-options').find('div')[0]).children().length;
        var chooseOptions = $('.option:checked, .option option:selected');
        var currentCheckedRadio, optionName, optionKey, optionValue, chooseOptionsLength = chooseOptions.length, selectedOptions = {};

        // If same length, means that customer have choose each options
        if(optionsLength == chooseOptionsLength) {
            chooseOptions.each(function(){
                currentCheckedRadio = $(this).is('option') ? $(this).parent() : $(this);

                optionName = currentCheckedRadio.attr('name');
                optionKey = optionName.split(/\[|\]/)[1];
                optionValue = currentCheckedRadio.val();

                selectedOptions[optionKey] = optionValue;
            });

            processSelectOptions(selectedOptions);
        }
    });

    // Select box is the option
    // $('.single-option-selector__select.select-option').on('change', function(){
    //     var optionsLength = $($('#list-variants-options').find('div')[0]).children().length;
    //     var chooseOptions = $('#variants_options').find('option:selected').filter('[value!=""]').parent('select');
    //     var currentOption, optionName, optionKey, optionValue, chooseOptionsLength = chooseOptions.length, selectedOptions = {};

    //     // If same length, means that customer have choose each options
    //     if(optionsLength == chooseOptionsLength) {
    //         chooseOptions.each(function(){
    //         currentOption = $(this);

    //             optionName = currentOption.attr('name');
    //             optionKey = optionName.split(/\[|\]/)[1];
    //             optionValue = currentOption.val();

    //             selectedOptions[optionKey] = optionValue;
    //         });

    //         processSelectOptions(selectedOptions);
    //     }
    // });

    // Bundle selection
    $('.single-bundle-selector__select.select-bundle').change(function(){
        var selectBoxes = $('.single-bundle-selector__select.select-bundle'),
        variantId = $(this).val(),
        productId = $(this).prev().val(),
        loopId = $(this).prev().data('loop'),
        selectedVariant = $('#variant_' + variantId + '_' + loopId),
        allSelectionsAvailable = true;

        disabledBundleButtons();
        updateBundleAvailabilityText(productId, variantId, loopId);
        resetBundleInputQuantity(productId, 0, loopId);
        checkBundleSelect(productId, loopId);
        updateBundleThumbnailImage(productId, variantId, loopId);
        updateBundleFixQuantity(productId, variantId, loopId);
        updateBundlePriceText(productId, variantId, loopId);

        selectBoxes.each(function(){
            var eachVariantId = $(this).val(),
            eachLoopId = $(this).prev().data('loop'),
            eachSelectedVariant = $('#variant_' + eachVariantId + '_' + eachLoopId),
            eachCheckAvailable = eachSelectedVariant.data('available');

            if(!eachCheckAvailable){
                allSelectionsAvailable = false;
                return false;
            }
        });

        if(selectedVariant.data('available')){
            resetBundleInputQuantity(productId, 1, loopId);
            updateSelectedBundleVariant(productId, variantId, loopId);// Will update variant first
            updateBundlePriceText(productId, variantId, loopId);
        }

        if(allSelectionsAvailable){
            enableButtons();
        }
    });

    // Bundle plus quantity on click
    $('.bundle-quantity-button.bundle-plus').on('click', function(){
        var productId = $(this).data('product-id'),
        loopId = $(this).data('loop'),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId);

        updateBundleAvailabilityText(productId, selectedProductVariant, loopId);
        checkBundleSelect(productId, loopId);

        if(selectedVariant.data('available')){
            plusBundleQuantity(productId, loopId);
        }
    });

    // Bundle minus quantity on click
    $('.bundle-quantity-button.bundle-minus').on('click', function(){
        var productId = $(this).data('product-id'),
        loopId = $(this).data('loop'),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId);

        updateBundleAvailabilityText(productId, selectedProductVariant, loopId);
        checkBundleSelect(productId, loopId);

        if(selectedVariant.data('available')){
            minusBundleQuantity(productId, loopId);
        }
    });

    // Bundle Quantity input box is on type in value
    $('.bundle-quantity-button.bundle-quantity-form').on('keyup', function(event){
        var productId = $(this).data('product-id'),
        loopId = $(this).data('loop'),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId);

        updateBundleAvailabilityText(productId, selectedProductVariant, loopId);
        checkBundleSelect(productId, loopId)

        if(selectedVariant.data('available')){
            inputBundleQuantity(productId, loopId);
        }
    });

    // Plus quantity on click
    $('#product_plus_quantity').on('click', function(){
        plusQuantity();
    });

    // Minus quantity on click
    $('#product_minus_quantity').on('click', function(){
        minusQuantity();
    });

    // Quantity input box is on type in value
    $('#product_input_quantity').on('keyup', function(event){
        inputQuantity(event);
    });
	 
	// If navbar collapse shown will hide search box collapse
	$('#navbar').on('shown.bs.collapse', function(){
		$('#collapseSearch').collapse('hide');
	});

    // When press search menu will toggle function
    $('body').on('click', '.searchs, .search, .pageOverlay, .close-button', function() {
        $('#collapseSearch').collapse('hide');
    });

    $(document).keyup(function(e) {
    if (e.key === 'Escape') {
        $('#collapseSearch').collapse('hide');
    }
    });
	 
	// When press enter at search textbox
	$('#products-search-input').keyup(function(event){
        if (event.keyCode === 13) {
            searchFunction();
        }
    });

    // If Search box collapse shown will autofocus input
	$('#collapseSearch').on('shown.bs.collapse', function(){
		$('#products-search-input').focus();
        $('#mainNavbar').addClass('bg-open-search-box');
		$('.bg-open-input-search-box').addClass('active');
		$('.pageOverlay').addClass('visible');
		$('#navbar').collapse('hide');
        $('#collapseSearch').collapse('show');
	});

     // If Search box collapse shown will autofocus input
	$('#collapseSearch').on('hide.bs.collapse', function(){
        $('#mainNavbar').removeClass('bg-open-search-box');
		$('.bg-open-input-search-box').removeClass('active');
		$('.pageOverlay').removeClass('visible');
	});
	 
	// When click the search icon button
	$('#buttonSearch').on('click', function(){
		searchFunction();
    });
	 
	var searchValue = new URLSearchParams(window.location.search);
	if (searchValue.has('q') == true) {
		var currentSeachValue = searchValue.get('q');
		$('#searchValueProducts').text(currentSeachValue);
		$('#searchResult').removeClass('d-none');
		$('#products-search-input').val(currentSeachValue);
	}

    $('#navbar .dropdown-menu').on('click', function(e){
        e.stopPropagation();
    });

    $('#navbar .dropdown-menu a').on('click', function(e){
        if($(this).next('.submenu').length){
            $(this).next('.submenu').toggle();
        }
    });

    // When click any of the paginate button
    $('.paginate-btn').on('click', function(e){
        e.preventDefault();

        var params = new URLSearchParams(window.location.search);
        var qValue = params.get('q');
        var clickedUrl = $(this).attr('href'); // Get paginate button href link

        // If qValue is not null
        if (qValue){
            // Check if clickedUrl has other parameters
            if (clickedUrl.indexOf('?') !== -1){
                // If true, append &q=a instead
                clickedUrl += '&q=' + qValue;
            } else {
                clickedUrl += '?q=' + qValue;
            }
        }

        window.location.href = clickedUrl;
    });
});

function searchFunction() {
	var searchBoxValue = $('#products-search-input').val();
	$('#buttonSearch').attr('href', '/products?q=' + searchBoxValue);
	$('#buttonSearch')[0].click();
}

function processSelectOptions(selectedObject){
    var div, key, value, selected_variant, found = [];
    var list_variant = $('#list-variants-options');

    list_variant.find('div').each(function(index, element){
        div = $(element), found[div.data('variant')] = [];
        div.find('input').each(function(index, input){
            key = $(input).data('optionid'),
            value = $(input).val();

            found[div.data('variant')].push((selectedObject[key] === value));
        });
    });

    for(var variantId in found){
        disabledButtons();
        //showQuantityText(false);
        //resetInputQuantity(1);
        //$('#max-product-quantity').text(1);
        //$('#max-product-quantity').attr('value', 1);

        if(found[variantId].includes(false) === false){
            selected_variant = $('#variant_' + variantId);

            updateSelectedOptionsVariant(variantId); // update selected variant first
            updateThumbnailImage(variantId);
            updatePriceText(variantId);
            disabledButtons();

            if(selected_variant.data('available')){
                enableButtons();
                updatePriceText();
                //updateQuantityText();
                //showQuantityText();
            }

            break;
        } else { disabledButtons(); }
    }
    return;
}

function updateSelectedOptionsVariant(variantId){
    $('input#selected-option[name="id"]').attr('value', variantId);
}

function updateSelectedBundleVariant(productId, variantId, loopId){
    $('input#product_bundle_' + productId + '_variant_' + loopId).attr('value', variantId);
}

function updateThumbnailImage(variantId){
    var selectedVariantImage = $('#img_variant' + variantId),
        image_gallery = $('#carousel-gallery');

    // Clear/remove current active
    image_gallery.find('div.carousel-item.active').removeClass('active');

    if(selectedVariantImage.length > 0){
        selectedVariantImage.parent().addClass('active');
    } else {
        image_gallery.find('div.carousel-item').first().addClass('active');
    }
}

function updateBundleThumbnailImage(productId, variantId, loopId){
    var selectedProductBundleImage = $('#img_bundle_' + productId + '_' + loopId),
    selectedVariantBundleImage = $('#img_bundle_' + variantId + '_' + loopId);

    if(variantId == '' || variantId == null || (typeof variantId === 'undefined')){
        variantId = $('#product_bundle_' + productId + '_' + 'variant_' + loopId).val(),
        selectedVariantBundleImage = $('#img_bundle_' + variantId + '_' + loopId);
    }

    var rowElement = $('#row_' + productId + '_' + loopId),
    bundleThumbnailElement = rowElement.find('.bundle-thumbnail').find('[id^="img_bundle_"]'),
    selectedVariant = $('#variant_' + variantId + '_' + loopId),
    image = selectedVariant.data('image');

    bundleThumbnailElement.addClass('d-none').removeClass('d-block');

    if(image == '' || (typeof image === 'undefined')){
        selectedVariantBundleImage = $('#img_bundle_empty_' + variantId + '_' + loopId);

        selectedProductBundleImage.addClass('d-block').removeClass('d-none');
        selectedVariantBundleImage.addClass('d-block').removeClass('d-none');
    }else{
        selectedVariantBundleImage.addClass('d-block').removeClass('d-none');
    }
}

function updateBundleFixQuantity(productId, variantId, loopId){
    var selectedBundleRow = $('#row_' + productId + '_' + loopId),
    selectedVariant = $('#variant_' + variantId + '_' + loopId),
    selectedFixQuantityElement = $('#fixed_quantity_' + loopId),
    bundleFixQuantity = selectedVariant.data('fixed-quantity');

    if(bundleFixQuantity == '' || bundleFixQuantity == null || (typeof bundleFixQuantity === 'undefined')){
        selectedFixQuantityElement.addClass('d-none').removeClass('d-block');
        selectedFixQuantityElement.text('');
        $('input[name="bundle_products[' + loopId + '][product_id]"]').parent('.bundle-variants').addClass('mb-2');

        if(variantId == ''){
            selectedBundleRow.find('.input-quantity').addClass('d-none').removeClass('d-block');
        }else{
            selectedBundleRow.find('.input-quantity').addClass('d-block').removeClass('d-none');
        }
    }else{
        selectedFixQuantityElement.removeClass('d-none');
        selectedFixQuantityElement.text(bundleFixQuantity);
        $('input[name="bundle_products[' + loopId + '][product_id]"]').parent('.bundle-variants').removeClass('mb-2');

        selectedBundleRow.find('.input-quantity').addClass('d-none').removeClass('d-block');
    }
}

function updatePriceText(variantId = null){
    var selectedVariant = $('#variant_' + $('#selected-option').val()),
        currentQuantity = $('#product_input_quantity').val(),
        formattedProductPrice, formattedDiscountPrice,
        formattedTotalPrice, productPrice, discountPrice,
        productPriceElement, discountPriceElement, currencyType, totalPrice = 0;

    // override if variantId not null
    if(variantId){
        selectedVariant = $('#variant_' + variantId);
    }

    formattedProductPrice = selectedVariant.data('price');
    formattedDiscountPrice = selectedVariant.data('discount-price');

    currencyType = formattedProductPrice.match(/^\D+/g)[0];
    productPrice = formattedProductPrice.replace(/^\D+/g, '');
    //discountPrice = formattedDiscountPrice.replace(/^\D+/g, '');

    // if input quantity box not exist, set default to 1
    //currentQuantity = currentQuantity? currentQuantity : 1;

    productPriceElement = $('#product-price');
    productPriceElementAtome = $('#product-price-atome');
    discountPriceElement = $('#discount-price-single');

    //totalPrice = productPrice * currentQuantity;
    //formattedTotalPrice = currencyType + totalPrice.toFixed(2);
    formattedTotalPrice = formattedProductPrice;
    totalPriceAtome = productPrice / 3;
    formattedTotalPriceAtome = currencyType + totalPriceAtome.toFixed(2);

    // Set the price
    productPriceElement.text(formattedTotalPrice);
    productPriceElementAtome.text(formattedTotalPriceAtome);

    // If variant is available and have discount price, set the price. Otherwise clear the text.
    if(selectedVariant.data('available') && formattedDiscountPrice){
        discountPriceElement.text(formattedDiscountPrice);
    } else {
        discountPriceElement.text('');
    }
}

function updateBundlePriceText(productId, bundleVariantId = null, loopId){
    var selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId ),
        input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
        currentQuantity = parseInt(input_quantity_box.attr('value')),
        bundlePriceSection = $('#' + bundleVariantId + '_' + loopId + '.bundle-price-variants').parent('.bundles-price'),
        bundlePriceDiv = bundlePriceSection.find('.bundle-price-variants'),
        productBundleDiscountPrice = calculateTotalVisibleComparePrice(),
        totalBundlesPrice = calculateTotalVisiblePrice(),
        bundlePrice, bundleDiscountPrice,
        formattedProductBundlePrice, formattedProductBundleDiscountPrice, formattedBundlePrice, formattedBundleDiscountPrice,
        productBundlePriceElement, productBundleDiscountPriceElement,
        formattedBundleTotalPrice, formattedTotalBundleDiscountPrice, formattedTotalBundlePriceAtome, formattedTotalBundlesSavedPrice, formattedTotalBundleSavedPrice,
        bundlePriceElement, bundleDiscountPriceElement, bundlePriceElementAtome, bundlesSavedPriceElement, bundleSavedPriceElement, currencyType,
        totalBundlePrice = 0, totalBundleDiscountPrice = 0, totalBundlePriceAtome = 0,
        totalBundlesSavedPrice = calculateSavedPrice(), totalBundleSavedPrice = 0;

        $(bundlePriceDiv).removeClass('d-block').addClass('d-none');
        $(bundlePriceDiv).next('[id^="bundle-saved-price_"]').removeClass('d-block').addClass('d-none');
        $('#' + bundleVariantId + '_' + loopId + '.bundle-price-variants').removeClass('d-block').addClass('d-none');
        $('#' + bundleVariantId + '_' + loopId).removeClass('d-none').addClass('d-block');
        $('#bundle-saved-price_' + bundleVariantId + '_' + loopId).removeClass('d-none').addClass('d-block');

        // override if variantId not null
        if(bundleVariantId){
            selectedVariant = $('#variant_' + bundleVariantId + '_' + loopId );
        }

        formattedBundlePrice = selectedVariant.data('price');

        formattedBundleDiscountPrice = selectedVariant.data('discount-price');

        bundlesPrice = formattedBundlePrice.replace(/^\D+/g, '');
        currencyType = formattedBundlePrice.match(/^\D+/g)[0];
        bundlePrice = formattedBundlePrice.replace(/^\D+/g, '');
        bundleDiscountPrice = formattedBundleDiscountPrice.replace(/^\D+/g, '');

        // if input quantity box not exist, set default to 1
        currentQuantity = currentQuantity? currentQuantity : 1;

        productBundlePriceElement = $('#product-price');
        productBundleDiscountPriceElement = $('#discount-price-single');
        bundlePriceElement = $('#bundle-price_' + bundleVariantId + '_' + loopId);
        bundlePriceElementAtome = $('#product-price-atome');
        bundleDiscountPriceElement = $('#bundle-discount-price-single_' + bundleVariantId + '_' + loopId);
        bundlesSavedPriceElement = $('#bundle-saved-price');
        bundleSavedPriceElement = $('#bundle-saved-price_' + bundleVariantId + '_' + loopId);

        totalBundlePrice = bundlePrice * currentQuantity;
        totalBundleDiscountPrice = bundleDiscountPrice * currentQuantity;
        totalBundleSavedPrice = totalBundleDiscountPrice - totalBundlePrice;
        totalBundlePriceAtome = totalBundlesPrice / 3;

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

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

        formattedProductBundlePrice = currencyType + totalBundlesPrice.toFixed(2);
        formattedProductBundleDiscountPrice = currencyType + productBundleDiscountPrice.toFixed(2);
        formattedBundleTotalPrice = currencyType + totalBundlePrice.toFixed(2);
        formattedTotalBundleDiscountPrice = currencyType + totalBundleDiscountPrice.toFixed(2);
        formattedTotalBundlePriceAtome = currencyType + totalBundlePriceAtome.toFixed(2);
        formattedTotalBundlesSavedPrice = currencyType + totalBundlesSavedPrice.toFixed(2);
        formattedTotalBundleSavedPrice = currencyType + totalBundleSavedPrice.toFixed(2);

        if(totalBundleSavedPrice <= 0){
            totalBundleSavedPrice = 0;
            bundleSavedPriceElement.addClass('d-none').removeClass('d-block');
            bundleDiscountPriceElement.addClass('d-none').removeClass('d-block');
            $('#' + bundleVariantId + '_' + loopId + '.bundle-price-variants').addClass('mb-1');
        }else{
            bundleSavedPriceElement.removeClass('d-none');
            bundleDiscountPriceElement.removeClass('d-none');
            $('#' + bundleVariantId + '_' + loopId + '.bundle-price-variants').removeClass('mb-1');
        }

        if(totalBundlesSavedPrice <= 0){
            bundlesSavedPriceElement.html('Grab This Amazing Bundle Now! 🔥');
        }else{
            bundlesSavedPriceElement.html('<b>Save ' + formattedTotalBundlesSavedPrice + '</b> With This Bundle! 🔥');
        }

        // Set the price
        productBundleDiscountPriceElement.text(formattedProductBundleDiscountPrice);
        productBundlePriceElement.text(formattedProductBundlePrice);
        if(totalBundlesPrice >= productBundleDiscountPrice){
            productBundleDiscountPriceElement.addClass('d-none');
        }else{    
            productBundleDiscountPriceElement.removeClass('d-none');
        }
        bundlePriceElementAtome.text(formattedTotalBundlePriceAtome);
        bundlePriceElement.text(formattedBundleTotalPrice);
        bundleSavedPriceElement.text('(Save ' + formattedTotalBundleSavedPrice + ')');

        // If variant is available and have discount price, set the price. Otherwise clear the text.
        if(formattedBundleDiscountPrice){
            bundleDiscountPriceElement.text(formattedTotalBundleDiscountPrice);
            bundleDiscountPriceElement.removeClass('mr-0');
        } else {
            bundleDiscountPriceElement.text('');
            bundleDiscountPriceElement.addClass('mr-0');
        }
}

function calculateTotalVisibleComparePrice(){
    var bundlesComparePrice = 0;
    $('.single-bundle-selector__select.select-bundle').each(function() {
        var bundleVariant = $(this).val(),
        loopId = $(this).prev().data('loop'),
        selectedBundleVariant = $('#variant_' + bundleVariant + '_' + loopId),
        bundleVariantDiscPrice = selectedBundleVariant.data('discount-price'),
        bundleDiscPrice, currentBundleQuantity, formattedBundleDiscPrice;
        if(!bundleVariantDiscPrice || bundleVariantDiscPrice == ''){
            selectedBundleVariant = $('#variant_' + $(this).find('option:nth-child(2)').val() + '_' + loopId);
            bundleVariantDiscPrice = selectedBundleVariant.data('discount-price');
        }
        currentBundleQuantity = $('input[data-product-id="' + selectedBundleVariant.parent().data('product-id') + '"][data-loop="' + loopId + '"].bundle-quantity-form').val();
        formattedBundleVariantDiscPrice = bundleVariantDiscPrice.replace(/^\D+/g, '');
        bundleDiscPrice = formattedBundleVariantDiscPrice * currentBundleQuantity;
        bundlesComparePrice += bundleDiscPrice;
    });
    return bundlesComparePrice;
}

function calculateTotalVisiblePrice(){
    var bundlePriceAtome = 0;
    $('.single-bundle-selector__select.select-bundle').each(function() {
        var bundleVariant = $(this).val(),
        loopId = $(this).prev().data('loop'),
        selectedBundleVariant = $('#variant_' + bundleVariant + '_' + loopId),
        bundleVariantPrice = selectedBundleVariant.data('price'),
        currentBundleQuantity, formattedBundleVariantPrice;
        if(!bundleVariantPrice || bundleVariantPrice == ''){
            selectedBundleVariant = $('#variant_' + $(this).find('option:nth-child(2)').val() + '_' + loopId);
            bundleVariantPrice = selectedBundleVariant.data('price');
        }
        currentBundleQuantity = $('input[data-product-id="' + selectedBundleVariant.parent().data('product-id') + '"][data-loop="' + loopId + '"].bundle-quantity-form').val(),
        formattedBundleVariantPrice = bundleVariantPrice.replace(/^\D+/g, '');
        bundlePriceAtome += (formattedBundleVariantPrice * currentBundleQuantity);
    });
    return bundlePriceAtome;
}

function calculateSavedPrice(){
    var bundleSavedPrice = 0, totalBundleSavedPrice = 0;
    $('.single-bundle-selector__select.select-bundle').each(function() {
        var bundleVariant = $(this).val(),
        loopId = $(this).prev().data('loop'),
        selectedBundleVariant = $('#variant_' + bundleVariant + '_' + loopId),
        formattedSelectedBundleVariantDiscountPrice, formattedSelectedBundleVariantPrice,
        formattedSelectedBundleVariantDiscountPriceText, formattedSelectedBundleVariantPriceText,
        selectedBundleVariantPrice = selectedBundleVariant.data('price'),
        selectedBundleVariantDiscountPrice = selectedBundleVariant.data('discount-price'),
        currentBundleQuantity;
        if(!bundleVariant || bundleVariant == ''){
            selectedBundleVariant = $('#variant_' + $(this).find('option:nth-child(2)').val() + '_' + loopId);
            selectedBundleVariantPrice = selectedBundleVariant.data('price');
            selectedBundleVariantDiscountPrice = selectedBundleVariant.data('discount-price');
        }
        currentBundleQuantity = $('input[data-product-id="' + selectedBundleVariant.parent().data('product-id') + '"][data-loop="' + loopId + '"].bundle-quantity-form').val(),
        formattedSelectedBundleVariantDiscountPrice = selectedBundleVariantDiscountPrice.replace(/^\D+/g, '');
        formattedSelectedBundleVariantPrice = selectedBundleVariantPrice.replace(/^\D+/g, '');

        formattedSelectedBundleVariantDiscountPriceText =  formattedSelectedBundleVariantDiscountPrice * currentBundleQuantity;
        formattedSelectedBundleVariantPriceText = formattedSelectedBundleVariantPrice * currentBundleQuantity;

        bundleSavedPrice = (formattedSelectedBundleVariantDiscountPriceText - formattedSelectedBundleVariantPriceText);
        totalBundleSavedPrice += bundleSavedPrice;
    });
    return totalBundleSavedPrice;
}

function clearForm() {
    $('#product-options').find('input[type="radio"], select').each(function(){
        var currentElement = $(this);

        if(currentElement.is(':radio')) {
            currentElement.prop('checked', false);
        } else {
            currentElement.prop('selectedIndex',0);
        }
    });
}

function enableButtons(){
    var btn, text;

    $("#btn-buynow, #btn-addtocart").each(function(){
        btn = $(this);
        text = (btn).is('#btn-buynow')? 'Buy now' : 'Add to cart';

        btn.removeAttr('disabled', 'disabled');
        btn.text(''); // clear first

        
        btn.html(text);
    });
}

function disabledButtons(){
    var btn;

    $("#btn-buynow, #btn-addtocart").each(function(){
        btn = $(this);

        btn.attr('disabled', 'disabled');
        btn.text('Sold out');
    });
}

function disabledBundleButtons(){
    var btn;

    $("#btn-buynow, #btn-addtocart").each(function(){
        btn = $(this);

        btn.attr('disabled', 'disabled');
    });
}

function updateBundleAvailabilityText(productId, variantId, loopId){
    var row = $('#row_' + productId + '_' + loopId),
    span = row.find('#bundle_availability_' + variantId + '_' + loopId),
    selectedVariant = $('#variant_'+ variantId + '_' + loopId),
    availability = selectedVariant.data('available'),
    isAvailable = true;

    if(!availability){
        isAvailable = false;
    }
    
    if(isAvailable){
        span.addClass('d-none').removeClass('d-block');
        row.find('[id^="bundle_availability_"]').addClass('d-none').removeClass('d-block');
    }else{
        row.find('[id^="bundle_availability_"]').addClass('d-none').removeClass('d-block');
        span.removeClass('d-none').addClass('d-block');
    }
}

function isUnlimitedVariant(){
    var isManageStock, isUnlimited,
        variantId = $('input#selected-option[name="id"]').attr('value'),
        selectedVariant = $('#variant_'+ variantId);

    // get current selected variant manage stock
    isManageStock = selectedVariant.data('manage-stock');

    // check manage stock boolean, if false, means it unlimited stock
    isUnlimited = (!isManageStock)? true : false;
    return isUnlimited;
}

function isUnlimitedBundleVariant(productId, loopId){
    var isManageStock, isUnlimited,
        variantId = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + variantId + '_' + loopId ),

        // get current selected variant manage stock
        isManageStock = selectedVariant.data('manage-stock');

        // check manage stock boolean, if false, means it unlimited stock
        isUnlimited = (!isManageStock)? true : false;
        return isUnlimited;
}

function checkBundleSelect(productId, loopId) {
    var input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
    buttonPlus = $('.bundle-plus[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
    buttonMinus = $('.bundle-minus[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
    inputProductId = $('.bundle-variants').find('input[value="'+ productId +'"][data-loop="'+ loopId +'"]').val(),
    selectBundleVariants = $('.bundle-variants').find('input[value="'+ productId +'"][data-loop="'+ loopId +'"]').next('select').val(),
    selectedVariant = $('#variant_' + selectBundleVariants + '_' + loopId ),
    available = false;

    if(selectBundleVariants != ''){
        available = selectedVariant.data('available');
    }

    if((selectBundleVariants == '') && (inputProductId == '') || available == false){
        buttonPlus.addClass('disabled').attr('disabled', 'disabled');
        buttonMinus.addClass('disabled').attr('disabled', 'disabled');
        input_quantity_box.prop('readonly', true);
        input_quantity_box.prop('disabled', false);
    }else{
        buttonPlus.removeClass('disabled').removeAttr('disabled', 'disabled');
        buttonMinus.removeClass('disabled').removeAttr('disabled', 'disabled');
        input_quantity_box.prop('readonly', false);
        input_quantity_box.prop('disabled', false);
    }

}

function updateQuantityText(){
    var selectedVariant = selectedVariant = $('#variant_' + $('#selected-option').val()),
        quantity = selectedVariant.attr('data-inventory-quantity'),
        max_product_text = $('#max-product-quantity');

    max_product_text.text(quantity);
    max_product_text.attr('value', quantity);
}

function showQuantityText(show = true){
    var quantity_div_text = $('#variant_quantity_text');

    if(!show || isUnlimitedVariant()){
        quantity_div_text.hide();
    } else {
        quantity_div_text.show();
    }
}

function resetInputQuantity(value = 1){
    var input_quantity_box = $('#product_input_quantity');

    input_quantity_box.attr('value', value);
    input_quantity_box.val(value);
}

function plusQuantity(){
    var input_quantity_box = $('#product_input_quantity'),
        current_value = parseInt($('#product_input_quantity').attr('value')),
        max_value = parseInt($('#max-product-quantity').attr('value')),
        new_value = 1,
        isUnlimited = false;

    new_value = current_value + 1;
    isUnlimited = isUnlimitedVariant();

    // if new value is not less than maximum available stock and stock is unlimited
    if((new_value < max_value) || isUnlimited == true){
        input_quantity_box.attr('value', new_value);
        input_quantity_box.val(new_value);
    }else{
        input_quantity_box.attr('value', max_value);
        input_quantity_box.val(max_value);
    }

    // Update price text after quantity changed
    updatePriceText();
}

function minusQuantity(){
    var input_quantity_box = $('#product_input_quantity'),
        current_value = parseInt($('#product_input_quantity').attr('value')),
        min_value = 1,
        new_value = 1;

    new_value = current_value - 1;

    if(new_value >= min_value && new_value > 0){
        input_quantity_box.attr('value', new_value);
        input_quantity_box.val(new_value);
    }

    // Update price text after quantity changed
    updatePriceText();
}

function inputQuantity(event){
    var input_quantity_box = $('#product_input_quantity'),
        current_value = parseInt($('#product_input_quantity').attr('value')),
        max_value = parseInt($('#max-product-quantity').attr('value')),
        input_value = 1,
        isUnlimited = false;

        isUnlimited = isUnlimitedVariant();

        input_value = input_quantity_box.val();
        input_value = input_value.replace(/[^0-9\.]/g, ''); // regex, which allow number only

        if (input_value != '') {
            input_value = parseInt(input_value);
            if(input_quantity_box.val()){
                if((input_value < max_value) || isUnlimited){
                    input_quantity_box.attr('value', input_value);
                    input_quantity_box.val(input_value);
                } else {
                    input_quantity_box.attr('value', max_value);
                    input_quantity_box.val(max_value);
                }
            }
        } else {
            input_quantity_box.attr('value', 1);
            input_quantity_box.val(1);
        }

    // Update price text after quantity changed
    updatePriceText();
}

function resetBundleInputQuantity(productId, value = 1, loopId){
    var input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]');

    input_quantity_box.attr('value', value);
    input_quantity_box.val(value);
}

function plusBundleQuantity(productId, loopId){
    var input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
        current_value = parseInt(input_quantity_box.attr('value')),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId ),
        max_value = parseInt(selectedVariant.data('inventory-quantity')),
        new_value = 1,
        isUnlimited = false;

        new_value = current_value + 1;
        isUnlimited = isUnlimitedBundleVariant(productId, loopId);

        // if new value is not less than maximum available stock and stock is unlimited
        if((new_value <= max_value) || isUnlimited == true){
            input_quantity_box.attr('value', new_value);
            input_quantity_box.val(new_value);

            // Update price text after quantity changed
            updateBundlePriceText(productId, selectedProductVariant, loopId);
        }else{
            input_quantity_box.attr('value', max_value);
            input_quantity_box.val(max_value);
        }
}

function minusBundleQuantity(productId, loopId){
    var input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
        current_value = parseInt(input_quantity_box.attr('value')),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        min_value = 1,
        new_value = 1;

        new_value = current_value - 1;

        if(new_value >= min_value && new_value > 0){
            input_quantity_box.attr('value', new_value);
            input_quantity_box.val(new_value);
        }

        // Update price text after quantity changed
        updateBundlePriceText(productId, selectedProductVariant, loopId);
}

function inputBundleQuantity(productId, loopId){
    var input_quantity_box = $('input[data-product-id="'+ productId +'"][data-loop="'+ loopId +'"]'),
        selectedProductVariant = $('#product_bundle_' + productId + '_variant_' + loopId).val(),
        selectedVariant = $('#variant_' + selectedProductVariant + '_' + loopId ),
        max_value = parseInt(selectedVariant.data('inventory-quantity')),
        input_value = 1,
        isUnlimited = false;

        isUnlimited = isUnlimitedVariant(); 

        input_value = input_quantity_box.val();
        input_value = input_value.replace(/[^0-9\.]/g,''); // regex, which allow number only
        input_value = parseInt(input_value);

        if(input_quantity_box.val()){
            if((input_value < max_value) || isUnlimited){
                input_quantity_box.attr('value', input_value);
                input_quantity_box.val(input_value);
            } else {
                input_quantity_box.attr('value', max_value);
                input_quantity_box.val(max_value);
            }
        }

        // Update price text after quantity changed
        updateBundlePriceText(productId, selectedProductVariant, loopId);
}