
// کد سلکت

var x, i, j, l, ll, selElmnt, a, b, c;
/* Look for any elements with the class "custom-select": */
x = document.getElementsByClassName("selectmehrnoosh");
l = x.length;
for (i = 0; i < l; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  ll = selElmnt.length;
  /* For each element, create a new DIV that will act as the selected item: */
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /* For each element, create a new DIV that will contain the option list: */
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < ll; j++) {
    /* For each option in the original select element,
    create a new DIV that will act as an option item: */
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /* When an item is clicked, update the original select box,
        and the selected item: */
        var y, i, k, s, h, sl, yl;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        sl = s.length;
        h = this.parentNode.previousSibling;
        for (i = 0; i < sl; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            yl = y.length;
            for (k = 0; k < yl; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /* When the select box is clicked, close any other select boxes,
    and open/close the current select box: */
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /* A function that will close all select boxes in the document,
  except the current select box: */
  var x, y, i, xl, yl, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  xl = x.length;
  yl = y.length;
  for (i = 0; i < yl; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < xl; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}

/* If the user clicks anywhere outside the select box,
then close all select boxes: */
document.addEventListener("click", closeAllSelect); 


// کد اسکورل فیلتر
jQuery(document).ready(function($) {
    $('.product-categories-filter').each(function() {
        var $filterBox = $(this);
        if ($filterBox.prop('scrollHeight') > 250) {
            $filterBox.css('overflow-y', 'scroll');
        }
    });
});

/**
* کد لود کننده سبد خرید
 */

jQuery(document).ready(function ($) {
    // مدیریت کلیک روی دکمه "افزودن به سبد"
    $(document).on('click', '.add_to_cart_button', function (e) {
        // اگر دکمه دارای کلاس disabled باشد
        if ($(this).hasClass('disabled')) {
            e.preventDefault(); // جلوگیری از رفتار پیش‌فرض
            e.stopImmediatePropagation(); // جلوگیری از سایر رویدادها
            return false; // توقف اجرای کد
        }

        // نمایش لودینگ در هنگام کلیک
        $('#loading-overlay').css('display', 'grid');
    });

    // مدیریت رویداد "اضافه شدن به سبد خرید"
    $(document).on('added_to_cart', function () {
        // مخفی کردن لودینگ
        $('#loading-overlay').css('display', 'none');
        // نمایش اعلان شناور
        $('#floating-notification').fadeIn().delay(3000).fadeOut();
    });
});




// کد سبد خرید
document.addEventListener('DOMContentLoaded', function() {
   
    var cartBoxes = document.querySelectorAll('.mehrnoosh-iran-bazshoekht');

    cartBoxes.forEach(function(cartBox) {
        var cartId = cartBox.getAttribute('data-cart-id');
        var cartBar = document.querySelector('.mehrnoosh-cart-left-bar-two[data-cart-id="' + cartId + '"]');
        var closeBtn = cartBar.querySelector('.close-btnback');

        
        cartBox.addEventListener('click', function() {
            cartBar.classList.toggle('active');
        });

       
        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                cartBar.classList.remove('active');
            });
        }

       
        document.addEventListener('click', function(event) {
            if (!cartBar.contains(event.target) && !cartBox.contains(event.target)) {
                cartBar.classList.remove('active');
            }
        });

        
        var scrollableContent = cartBar.querySelector('.scrollable-content .woocommerce-mini-cart.cart_list.product_list_widget');
        if (scrollableContent && scrollableContent.scrollHeight > 270) {
            scrollableContent.classList.add('scroll-active');
        }
    });
});




// کد نمایش لود کننده دسته بندی



                    jQuery(document).ready(function($) {
                        $(".product-categories-filter a").click(function(e) {
                            e.preventDefault();
                            var url = $(this).attr("href");

                          
    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'grid'; 
    }
                            
                            window.location.href = url;
                        });
                    });
					
					

document.addEventListener('DOMContentLoaded', function() {
    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('on_sale')) {
        document.querySelector('.all-products-buttonone').style.display = 'block';
    }

    if (urlParams.has('in_stock')) {
        document.querySelector('.all-products-button').style.display = 'block';
    }
});

function removeOnSaleFilter() {

    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'grid'; 
    }

    var urlParams = new URLSearchParams(window.location.search);
    urlParams.delete('on_sale');

    
    removePageFromURL(urlParams);

   
    var newUrl = window.location.pathname + '?' + urlParams.toString();
    window.location.href = newUrl;
}

function removeInStockFilter() {

    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'grid'; 
    }

    var urlParams = new URLSearchParams(window.location.search);
    urlParams.delete('in_stock');


    removePageFromURL(urlParams);

  
    var newUrl = window.location.pathname + '?' + urlParams.toString();
    window.location.href = newUrl;
}

function removePageFromURL(urlParams) {
   
    const currentUrl = window.location.href;
    const newUrl = currentUrl.replace(/\/page\/\d+\//, '/'); 


    const finalUrl = newUrl.replace(/\?$/, '');

   
    window.history.replaceState(null, '', finalUrl); 
}



// کد دکمه ها
jQuery(document).ready(function($) {
   
    $('.on-sale-filter-button, .in-stock-filter-button').click(function(event) {
        event.preventDefault(); 

        
        var currentUrl = window.location.href;
        
        
        var filterParam = $(this).attr('href').split('?')[1]; 
        var newUrl = currentUrl; 
        
        if (currentUrl.indexOf('?') !== -1) {
            
            newUrl += '&' + filterParam;
        } else {
            
            newUrl += '?' + filterParam;
        }

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


// کد فیلتر ویژگی ها



jQuery(document).ready(function($) {
    
    function updateCheckboxes() {
        var urlParams = new URLSearchParams(window.location.search);
        $('.testform input[type="checkbox"]').each(function() {
            var name = $(this).attr('name');
            var value = $(this).val();
            var isChecked = urlParams.has(name) && urlParams.get(name).split(',').includes(value);
            $(this).prop('checked', isChecked);
        });
    }

    function addRemoveFilterButton(key, values) {
        
        if (typeof values === 'string') {
            values = values.split(',');
        }

        
        values.forEach(function(value) {
            
            var checkbox = $('.testform input[name="' + key + '"][value="' + value + '"]');
            var displayName = checkbox.parent().text().trim();

            
            const buttonText = `فیلتر ${displayName}`;

            
            const button = $('<button>')
                .text(buttonText)
                .addClass('remove-filter-button mehrnoosh-remove-filter-button')
                .append($('<i>').addClass('fi fi-rr-cross-small')) 
                .addClass(value) 
                .click(function() {
                    
                    const loadingOverlay = document.getElementById('loading-overlay');
                    if (loadingOverlay) {
                        loadingOverlay.style.display = 'grid';
                    }

                    
                    var currentUrl = window.location.href;
                    var newUrl = removeFilterFromUrl(currentUrl, key, value);
                    newUrl = removePageFromURL(newUrl); 
                    window.location.href = newUrl;
                });

           
            $('#filter-buttons-container').append(button);
        });
    }

    
    updateCheckboxes();

    
    var urlParams = new URLSearchParams(window.location.search);
    urlParams.forEach(function(value, key) {
        if (key.startsWith('filter_')) {
            addRemoveFilterButton(key, value);
            value.split(',').forEach(function(val) {
                $('input[name="' + key + '"][value="' + val + '"]').prop('checked', true);
            });
        }
    });

   
    $('.testform input[type="checkbox"]').change(function() {
        const loadingOverlay = document.getElementById('loading-overlay');
        if (loadingOverlay) {
            loadingOverlay.style.display = 'grid';
        }
        applyFilter();
    });

    
    function applyFilter() {
        var currentUrl = window.location.href;
        var filterParams = $('.testform input[type="checkbox"]:checked').serializeArray();
        var newUrl = updateUrlWithFilters(currentUrl, filterParams);
        newUrl = removePageFromURL(newUrl); 
        window.location.href = newUrl;
    }

    
    function updateUrlWithFilters(url, filterParams) {
        var newUrl = new URL(url);
        var keysToDelete = [];
        newUrl.searchParams.forEach(function(value, key) {
            if (key.startsWith('filter_')) {
                keysToDelete.push(key);
            }
        });
        keysToDelete.forEach(function(key) {
            newUrl.searchParams.delete(key);
        });
        filterParams.forEach(function(param) {
            var key = param.name;
            var value = param.value;
            if (value) {
                if (newUrl.searchParams.has(key)) {
                    var existingValues = newUrl.searchParams.get(key).split(',');
                    if (!existingValues.includes(value)) {
                        existingValues.push(value);
                    }
                    newUrl.searchParams.set(key, existingValues.join(','));
                } else {
                    newUrl.searchParams.append(key, value);
                }
            }
        });
        return newUrl.toString();
    }

    
    function removeFilterFromUrl(url, filterKey, filterValue) {
        var newUrl = new URL(url);
        var existingValues = newUrl.searchParams.get(filterKey) ? newUrl.searchParams.get(filterKey).split(',') : [];
        existingValues = existingValues.filter(val => val !== filterValue);
        newUrl.searchParams.delete(filterKey);
        if (existingValues.length) {
            newUrl.searchParams.append(filterKey, existingValues.join(','));
        }
        return newUrl.toString();
    }

    
    function removePageFromURL(url) {
        
        const newUrl = url.replace(/\/page\/\d+\//, '/'); 
        return newUrl.replace(/\?$/, ''); 
    }
});


// کد فیلتر
jQuery(document).ready(function($) {
    function updateCheckboxesbrand() {
        var urlParams = new URLSearchParams(window.location.search);
        var selectedBrands = urlParams.get('filterb_brands') ? urlParams.get('filterb_brands').split(',') : [];
        
        $('.brand-filter-form input[type="checkbox"]').each(function() {
            var value = $(this).val();
            var isChecked = selectedBrands.includes(value);
            $(this).prop('checked', isChecked);
        });
    }

    function addRemoveFilterButtonbrand(value) {
        var checkbox = $('.brand-filter-form input[type="checkbox"][value="' + value + '"]');
        
        if (checkbox.length) {
            var displayName = checkbox.parent().text().trim();
            const button = $('<button>')
                .text(`فیلتر ${displayName}`)
                .addClass('remove-filter-button mehrnoosh-remove-filter-button')
                .addClass(value)
                .append($('<i>').addClass('fi fi-rr-cross-small'))
                .click(function() {
                    console.log('Remove button clicked for:', value);
                    const loadingOverlay = document.getElementById('loading-overlay');
                    if (loadingOverlay) {
                        loadingOverlay.style.display = 'grid';
                    }

                    var currentUrl = window.location.href;
                    var newUrl = removeFilterFromUrlbrand(currentUrl, value);
                    newUrl = removePageFromURL(newUrl); 
                    console.log('New URL after removal:', newUrl);
                    window.location.href = newUrl;
                });

            $('#filter-buttons-containertwo').append(button);
        }
    }

    function updateRemoveFilterButtonsbrand() {
        var urlParams = new URLSearchParams(window.location.search);
        $('#filter-buttons-containertwo').empty();
        var selectedBrands = urlParams.get('filterb_brands') ? urlParams.get('filterb_brands').split(',') : [];
        selectedBrands.forEach(function(brand) {
            addRemoveFilterButtonbrand(brand);
        });
    }

    function removeFilterFromUrlbrand(url, filterValue) {
        var newUrl = new URL(url);
        var currentParams = new URLSearchParams(newUrl.search);

        // جدا کردن مقادیر
        var values = currentParams.get('filterb_brands') ? currentParams.get('filterb_brands').split(',') : [];
        
        values = values.filter(function(val) {
            return val.trim() !== filterValue; 
        });

        if (values.length > 0) {
            currentParams.set('filterb_brands', values.join(','));
        } else {
            currentParams.delete('filterb_brands');
        }

        return newUrl.origin + newUrl.pathname + '?' + currentParams.toString();
    }

    
    function removePageFromURL(url) {
        
        const newUrl = url.replace(/\/page\/\d+\//, '/'); 
        return newUrl.replace(/\?$/, ''); 
    }

    updateRemoveFilterButtonsbrand();
    updateCheckboxesbrand();

    $('.brand-filter-form input[type="checkbox"]').change(function() {
        applyFilterbrand();
    });

    function applyFilterbrand() {
        const loadingOverlay = document.getElementById('loading-overlay');

        if (loadingOverlay) {
            loadingOverlay.style.display = 'grid';
        }
        
        var currentUrl = new URL(window.location.href);
        var currentParams = new URLSearchParams(currentUrl.search);
        var selectedBrands = [];

        $('.brand-filter-form input[type="checkbox"]:checked').each(function() {
            selectedBrands.push($(this).val());
        });

        if (selectedBrands.length > 0) {
            currentParams.set('filterb_brands', selectedBrands.join(','));
        } else {
            currentParams.delete('filterb_brands');
        }

        var newUrl = currentUrl.origin + currentUrl.pathname + '?' + currentParams.toString();
        newUrl = removePageFromURL(newUrl); 
        console.log('New URL after applying filter:', newUrl);
        window.location.href = newUrl; 
    }
});




// کد لود کننده محصول تخفیفی و لود نشدن لودر

function showLoadingOverlay() {
    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'grid';
    }
}


function hideLoadingOverlay() {
    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'none';
    }
}


function toggleOnSaleFilter() {
    showLoadingOverlay();

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('on_sale')) {
        urlParams.delete('on_sale');
    } else {
        urlParams.set('on_sale', '1');
    }
    
   
    setTimeout(() => {
        window.location.search = urlParams.toString();
    }, 300); 
}


window.addEventListener('pageshow', function(event) {
    if (event.persisted) {
        hideLoadingOverlay();
    }
});


window.onload = function() {
    hideLoadingOverlay();
};


// کد محصولات موجود
function toggleInStockFilter() {
    const loadingOverlay = document.getElementById('loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'grid';
    }

    const urlParams = new URLSearchParams(window.location.search);

   
    if (urlParams.has('in_stock')) {
        urlParams.delete('in_stock');
    } else {
        urlParams.set('in_stock', '1');
    }

    
    const newUrl = window.location.pathname + '?' + urlParams.toString();

    
    window.location.href = newUrl; 
}


document.addEventListener('DOMContentLoaded', function() {
    
    var inStockCheckbox = document.querySelector('#in-stock-switch');


        


     if (inStockCheckbox) { // بررسی اینکه عنصر وجود دارد

    inStockCheckbox.addEventListener('change', function(event) {
  
        updateURL();
    });
    
     } else {
    }    

    function updateURL() {
        var currentUrl = window.location.href;

        
        var newUrl = currentUrl.replace(/\/page\/\d+\//, '/');

        
        newUrl = newUrl.replace(/\?$/, '');

        
        const urlParams = new URLSearchParams(newUrl.split('?')[1]);

        
        if (inStockCheckbox.checked) {
            urlParams.set('in_stock', '1'); 
        } else {
            urlParams.delete('in_stock'); 
        }

        
        newUrl = newUrl.split('?')[0] + '?' + urlParams.toString();

        
        window.history.replaceState(null, '', newUrl);

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


	
	// کد مرتب سازی
	
	

document.addEventListener('DOMContentLoaded', function() {
    
    var sortingLinks = document.querySelectorAll('.mehrnoosh-sorting a');
    
    if (sortingLinks.length > 0) {
        sortingLinks.forEach(function(link) {
            link.addEventListener('click', function(event) {
                event.preventDefault(); 

                
                var loadingOverlay = document.getElementById('loading-overlay');
                if (loadingOverlay) {
                    loadingOverlay.style.display = 'grid'; 
                }

                
                var currentUrl = new URL(window.location.href);

                
                var newOrderby = new URL(link.href).searchParams.get('orderby');

                
                currentUrl.searchParams.set('orderby', newOrderby);

                
                setTimeout(function() {
                    window.location.href = currentUrl.toString();
                }, 500);
            });
        });
    } else {

    }
});





// کد فیلتر در موبایل

 
 
document.addEventListener('DOMContentLoaded', function() {
    var cartBox = document.querySelector('.filter-open-mobile');
    var cartBar = document.querySelector('.mehrnoosh-shop-nav-one');

    // بررسی اینکه cartBar و cartBox وجود دارند
    if (cartBar && cartBox) {
        var closeBtn = cartBar.querySelector('.close-btn-mehr-filter');

        if (closeBtn) {
            closeBtn.addEventListener('click', function() {
                cartBar.classList.remove('active');
            });
        } else {
        }

        cartBox.addEventListener('click', function() {
            cartBar.classList.toggle('active');
        });

        document.addEventListener('click', function(event) {
            if (!cartBar.contains(event.target) && !cartBox.contains(event.target)) {
                cartBar.classList.remove('active');
            }
        });
    } else {
    }

    // بررسی اسکرول در scrollableContent
    const scrollableContent = document.querySelector('.scrollable-content .product_list_widget');
    if (scrollableContent && scrollableContent.scrollHeight > 270) {
        scrollableContent.classList.add('scroll-active');
    }
});




// کد حذف page

document.addEventListener('DOMContentLoaded', function() {
    
    var stockFilterInputs = document.querySelectorAll('.widget_wc_attributes_filter_widget input , .mehrnoosh-shop-nav-one select , .widget_wc_brand_filter_widget input , .on_sale_products_widget input');

    stockFilterInputs.forEach(function(inputElement) {
        inputElement.addEventListener('change', function(event) {
           
            removePageFromURL();

            
        });
    });

    function removePageFromURL() {
        var currentUrl = window.location.href;

        
        var newUrl = currentUrl.replace(/\/page\/\d+\//, '/');

        
        newUrl = newUrl.replace(/\?$/, '');

        
        window.history.replaceState(null, '', newUrl);
    }
});







jQuery(document).ready(function($) {
    
    $(document.body).on('removed_from_cart', function() {
       
        $.ajax({
            url: wc_add_to_cart_params.ajax_url,
            type: 'POST',
            data: {
                action: 'woocommerce_get_refreshed_fragments'
            },
            success: function(response) {
                if (response && response.fragments) {
                    $.each(response.fragments, function(key, value) {
                        $(key).replaceWith(value);
                    });

                    
                    if ($('.woocommerce-cart-form').length === 0) {
                        $('.wc-empty-cart-message').show(); // نمایش پیام خالی بودن سبد
                    }
                }
            }
        });
    });
});


// لود کننده کد تخفیف 

 jQuery(document).ready(function($) {
            $('body').on('click', '.mehrnoosh-coupen-baznasho button[name="apply_coupon"]', function(e) {
                
  var loadingOverlay = document.getElementById('loading-overlay');
        if (loadingOverlay) {
            loadingOverlay.style.display = 'grid'; 
        }
              
            });
        });
		
document.addEventListener('DOMContentLoaded', function() {
    var hiddenInputs = document.querySelectorAll('.qty');
    hiddenInputs.forEach(function(input) {
        if (input.type === 'hidden') {
            var parentElement = input.closest('.button-plus-minus-mehrnooshj');
            if (parentElement) {
                parentElement.style.display = 'none';
            }
        }
    });
});