<!-- -->
jQuery(document).ready(function ($) {
// Add pagination click handler
$(document).on("click", "#pagination a", function (e) {
e.preventDefault();
var page = $(this).data("page");
jQuery("#pages").val(page);
updateURLParameters();
});
$(".spinner").hide();
var urlParams = new URLSearchParams(window.location.search);
urlParams.forEach(function (value, key) {
var values = value.split(",");
values.forEach(function (val) {
$('input[name="' + key + '[]"][value="' + val + '"]').prop(
"checked",
true
);
});
});
jQuery("body").on("click", ".blockplayvideo", function () {
var $id = $(this).attr("data-id");
$("#block" + $id + " .elementor-image-box-img img").addClass("hidden");
$(".display-v-" + $id).removeClass("hidden");
$(".play-video-btn-" + $id).addClass("hidden");
$(".stop-video-btn-" + $id).removeClass("hidden");
//$('.products').find('a#play-video').addClass('hidden');
//$('.products').find('a#stop-video').removeClass('hidden');
});
jQuery("body").on("click", ".blockstopvideo", function () {
var $id = $(this).attr("data-id");
$("#block" + $id + " .elementor-image-box-img img").removeClass("hidden");
$(".display-v-" + $id).addClass("hidden");
$(".play-video-btn-" + $id).removeClass("hidden");
$(".stop-video-btn-" + $id).addClass("hidden");
//$('.products').find('a#play-video').addClass('hidden');
//$('.products').find('a#stop-video').removeClass('hidden');
});
var $slider = $("#diametervalue");
var $length = $("#lengthvalue");
var $output = $("#sliderValue");
var $lengthValue = $("#lengthbar");
$output.html($slider.val()); // Display the default slider value
$lengthValue.html($length.val()); // Display the default slider value
$slider.on("input", function () {
$output.html($(this).val());
jQuery("#pages").val(1);
console.log('jQuery("#pages").val(1);');
updateURLParameters();
});
$length.on("input", function () {
$lengthValue.html($(this).val());
jQuery("#pages").val(1);
console.log('jQuery("#pages").val(1);');
updateURLParameters();
});
$("#sizeblock .cwi-filter-title").click(function () {
$(".size-content").toggleClass("active");
});
$("#weightblock .cwi-filter-title").click(function () {
$(".contentweight").toggleClass("active");
});
$("#lengthblock .cwi-filter-title").click(function () {
$(".length-content").toggleClass("active");
});
$("#diameterblock .cwi-filter-title").click(function () {
$(".diamter-content").toggleClass("active");
});
var currentPage = 1;
var isLoading = false;
var maxPages = 0;
// Initial AJAX request
// performAjaxRequest(currentPage);
// Event listeners for filter changes
$(
'input[name="accountname[]"],input[name="category[]"], input[name="gem-type[]"], input[name="shape[]"], input[name="size[]"], input[name="color[]"], input[name="treatment[]"], input[name="price[]"], input[name="origin[]"], input[name="location[]"],#weightfrom,#weightto,input[name="contentweight[]"],#lengthfrom,#lengthto,input[name="contentlength[]"],#diameterfrom,#diameterto,input[name="contentdiameter[]"],#sizefrom,#sizeto,input[name="contentsize[]"]'
).on("change", function () {
jQuery("#pages").val(1);
console.log('jQuery("#pages").val(1);');
updateURLParameters();
});
// Event listener for clearing filters
$("#clearFiltersButton").click(function () {
clearFilters();
});
// Function to clear filters
function clearFilters() {
$('input[name="category[]"]:checked').prop("checked", false);
$('input[name="gem-type[]"]:checked').prop("checked", false);
$('input[name="shape[]"]:checked').prop("checked", false);
$('input[name="size[]"]:checked').prop("checked", false);
$('input[name="color[]"]:checked').prop("checked", false);
$('input[name="treatment[]"]:checked').prop("checked", false);
$('input[name="price[]"]:checked').prop("checked", false);
$('input[name="origin[]"]:checked').prop("checked", false);
$('input[name="location[]"]:checked').prop("checked", false);
$('input[name="contentweight[]"]:checked').prop("checked", false);
$('input[name="accountname[]"]:checked').prop("checked", false);
$("#weightfrom").val("");
$("#weightto").val("");
$("#diametervalue").val("1");
$("#sliderValue").html("1");
$("#lengthvalue").val("1");
$("#lengthbar").html("1");
$("#pages").val("1");
updateURLParameters();
}
// Function to update URL parameters
function updateURLParameters() {
const current_url = new URL(window.location.href);
var url = getUrlpathname(current_url);
var params = [];
var contentlength = getCheckedValues("contentlength[]");
if (contentlength.length > 0)
params.push("contentlength=" + contentlength.join(","));
var lengthfrom = $("#lengthfrom").val();
if (lengthfrom != "") {
params.push("lengthfrom=" + lengthfrom);
}
var lengthto = $("#lengthto").val();
if (lengthto != "") {
params.push("lengthto=" + lengthto);
}
var contentdiameter = getCheckedValues("contentdiameter[]");
if (contentdiameter.length > 0)
params.push("contentdiameter=" + contentdiameter.join(","));
var diameterfrom = $("#diameterfrom").val();
if (diameterfrom != "") {
params.push("diameterfrom=" + diameterfrom);
}
var diameterto = $("#diameterto").val();
if (diameterto != "") {
params.push("diameterto=" + diameterto);
}
// Collecting checked filter values
var contentweight = getCheckedValues("contentweight[]");
if (contentweight.length > 0)
params.push("contentweight=" + contentweight.join(","));
var weightfrom = $("#weightfrom").val();
if (weightfrom != "") {
params.push("weightfrom=" + weightfrom);
}
var weightto = $("#weightto").val();
if (weightto != "") {
params.push("weightto=" + weightto);
}
var gemTypes = getCheckedValues("gem-type[]");
if (gemTypes.length > 0) params.push("gem-type=" + gemTypes.join(","));
var shapes = getCheckedValues("shape[]");
if (shapes.length > 0) params.push("shape=" + shapes.join(","));
var contentsize = getCheckedValues("contentsize[]");
if (contentsize.length > 0)
params.push("contentsize=" + contentsize.join(","));
var accountname = getCheckedValues("accountname[]");
if (accountname.length > 0)
params.push("accountname=" + accountname.join(","));
var sizefrom = $("#sizefrom").val();
if (sizefrom != "") {
params.push("sizefrom=" + sizefrom);
}
var sizeto = $("#sizeto").val();
if (sizeto != "") {
params.push("sizeto=" + sizeto);
}
var colors = getCheckedValues("color[]");
if (colors.length > 0) params.push("color=" + colors.join(","));
var treatments = getCheckedValues("treatment[]");
if (treatments.length > 0)
params.push("treatment=" + treatments.join(","));
var prices = getCheckedValues("price[]");
if (prices.length > 0) params.push("price=" + prices.join(","));
var origins = getCheckedValues("origin[]");
if (origins.length > 0) params.push("origin=" + origins.join(","));
var locations = getCheckedValues("location[]");
if (locations.length > 0) params.push("location=" + locations.join(","));
var pages = $("#pages").val();
if (pages != "") {
params.push("page=" + pages);
}
var categories = getCheckedValues("category[]");
if (categories.length > 0) {
params.push("category=" + categories.join(","));
}
// Sorting
var sort = $(".sort-by.active").data("filter");
if (sort) params.push("sort=" + sort);
// Forming the URL
if (params.length > 0) url += "?" + params.join("&");
else url += "?";
window.history.pushState(null, null, url);
currentPage = 1; // Reset to first page when filters are updated
isLoading = false; // Reset isLoading when filters are updated
performAjaxRequest(currentPage); // Force AJAX request after updating URL parameters
}
// Function to get checked values for a given name
function getCheckedValues(name) {
var values = [];
$('input[name="' + name + '"]:checked').each(function () {
values.push($(this).val());
});
return values;
}
// AJAX request function
function performAjaxRequest(page) {
if (isLoading) {
return;
}
isLoading = true;
var url = new URL(window.location.href);
url = url.toString();
$(".spinner").show();
$.ajax({
url: ajax_object.ajax_url,
method: "POST",
data: {
action: "filter_products",
url: url,
page: page,
},
dataType: "json",
beforeSend: function () {
jQuery(".loadproduct").addClass("is-loading");
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).css("opacity", "0.5");
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).css("background", "white");
jQuery(".loading-product-listing").show();
jQuery("body").removeClass("cwi-filter__active");
},
success: function (response) {
if (response.max_num_pages) {
maxPages = response.max_num_pages;
}
if (typeof response.grid_content !== "undefined") {
if (page === 1) {
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).html(response.grid_content);
jQuery("#pagination").html(response.pagination);
} else {
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).append(response.grid_content);
}
}
if (currentPage 0) {
Object.keys(response.data_filter).forEach(function (key) {
const items = response.data_filter[key];
$("." + key + " li small").text("(0)");
if (Array.isArray(items)) {
items.forEach(function (tax) {
const tagSlug = tax.tag_slug;
const tagCount = tax.tag_count;
const element = $(`#${tagSlug}`);
if (element.length) {
const smallElement = element
.closest(".cwi-filter-container")
.find("small");
smallElement.text(`( ${tagCount} )`);
}
});
}
});
} else {
$(".cwi-filters-form-diamond li.cwi-filter-container small").text("(0)"); // Reset all counts if no filter data
}
},
complete: function () {
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).css("opacity", "1");
jQuery(".loading-product-listing").hide();
jQuery(".e-loop__load-more").remove();
jQuery(".loadproduct").removeClass("is-loading");
},
error: function (response) {
isLoading = false; // Reset loading state on error
},
});
}
// Sort button click event
$(document).on("click", ".sort-by", function () {
var sortFilter = $(this).data("filter");
$(".sort-by").removeClass("active");
$(this).addClass("active");
updateURLParameters();
});
// Infinite scroll
$(window).scroll(function () {
if (
$(window).scrollTop() + $(window).height() >=
$(document).height() - 100 &&
!isLoading
) {
//performAjaxRequest(currentPage);
}
});
var $ul = $(".size-container .content");
$ul
.children("li")
.sort(function (a, b) {
var aText = $(a).find("label").text().trim();
var bText = $(b).find("label").text().trim();
var aNumber = parseFloat(aText.match(/[\d.]+/));
var bNumber = parseFloat(bText.match(/[\d.]+/));
return aNumber - bNumber;
})
.appendTo($ul);
function getLastUrlSegment(url) {
// Create URL object to parse the URL properly
let urlObj;
try {
urlObj = new URL(url);
} catch (e) {
return ""; // Return empty string if URL is invalid
}
// Get the pathname (e.g., "/product-category/designs/")
const path = urlObj.pathname;
// Split the path by '/' and filter out empty strings
const segments = path.split("/").filter((segment) => segment !== "");
// Return the last segment or empty string if no segments
return segments.length > 0 ? segments[segments.length - 1] : "";
}
function getUrlpathname(url) {
let urlObj;
try {
urlObj = new URL(url);
} catch (e) {
return ""; // Return empty string if URL is invalid
}
const path = urlObj.pathname;
return path;
}
// Example usage:
const current_url = new URL(window.location.href);
const category = getLastUrlSegment(current_url);
function checkGemTypeExists() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.has('gem-type');
}
const gemTypeExistsx = checkGemTypeExists();
if (gemTypeExistsx) {
$(".spinner").show();
var url = new URL(window.location.href);
url = url.toString();
} else {
var url = "https://aqgems.test/shop/page=1";
}
$.ajax({
url: ajax_object.ajax_url,
method: "POST",
data: {
action: "filter_products",
url: url,
page: 1,
},
dataType: "json",
beforeSend: function () {
},
success: function (response) {
if (typeof response.total_products !== "undefined") {
$(".total-products").text(response.total_products);
}
jQuery("#pagination").html(response.pagination);
if (response.data_filter && Object.keys(response.data_filter).length > 0) {
Object.keys(response.data_filter).forEach(function (key) {
const items = response.data_filter[key];
$("." + key + " li small").text("(0)");
if (Array.isArray(items)) {
items.forEach(function (tax) {
const tagSlug = tax.tag_slug;
const tagCount = tax.tag_count;
const element = $(`#${tagSlug}`);
if (element.length) {
const smallElement = element
.closest(".cwi-filter-container")
.find("small");
smallElement.text(`( ${tagCount} )`);
}
});
}
});
} else {
$(".cwi-filters-form-diamond li.cwi-filter-container small").text("(0)"); // Reset all counts if no filter data
}
jQuery(".filter-select .cwi-filter-checkbox").prop("checked", false);
jQuery("#category_ #" + category).prop("checked", true);
jQuery("#pages").val(1);
//window.history.pushState(null, null, current_url.origin + current_url.pathname);
//console.log(current_url);
const gemTypeExists = checkGemTypeExists();
if (gemTypeExists) {
console.log('Gem type parameter exists in the URL');
// Get the gem type values
const gemTypeValues = new URLSearchParams(window.location.search).get('gem-type');
console.log('Gem types:', gemTypeValues.split(','));
jQuery(
".loadproduct .elementor-widget-container .elementor-grid"
).html(response.grid_content);
Object.keys(response.data_filter).forEach(function (key) {
const items = response.data_filter[key];
$("." + key + " li small").text("(0)");
if (Array.isArray(items)) {
items.forEach(function (tax) {
const tagSlug = tax.tag_slug;
const tagCount = tax.tag_count;
const element = $(`#${tagSlug}`);
if (element.length) {
element.prop("checked", true);
const smallElement = element
.closest(".cwi-filter-container")
.find("small");
smallElement.text(`( ${tagCount} )`);
}
});
}
});
$(".spinner").hide();
} else {
window.history.pushState(
null,
null,
current_url.origin + current_url.pathname
);
}
},
complete: function () {
jQuery(".loadproduct .elementor-widget-container .elementor-grid").css(
"opacity",
"1"
);
jQuery(".loading-product-listing").hide();
jQuery(".e-loop__load-more").remove();
jQuery(".loadproduct").removeClass("is-loading");
},
error: function (response) {
isLoading = false; // Reset loading state on error
},
});
});