function debounce(t, e, a) { var n; return function () { var i = this, s = arguments, o = a && !n; clearTimeout(n), (n = setTimeout(function () { (n = null), a || t.apply(i, s); }, e)), o && t.apply(i, s); }; } /** * Header Sticky */ function headerSticky() { const header = $(".main--header"); if (window.scrollY > 10) { header.addClass("header-sticky"); } else { header.removeClass("header-sticky"); } } document.addEventListener("scroll", () => { headerSticky() }) /** * Header Form Search */ function fetchProductsSearch(catId, query) { if (!query || query.trim().length <= 0) { $('.autocomplete-items').html(''); return; } $('.autocomplete-items').html(''); const headerIconSearch = $("#headerIconSearch"); const headerIconSearchHtml = headerIconSearch.html(); headerIconSearch.html(`
Loading...
`) headerIconSearch.attr('disabled', true); zid.store.product.fetchAll(catId, { per_page: 10, search: encodeURI(query) }).then(function (response) { if (response.status === 'success') { if (response.data) { $('.autocomplete-items').html(''); if (response.data.products.data.length > 0) { for (var i = 0; i < response.data.products.data.length; i++) { var product = response.data.products.data[i]; $('.autocomplete-items').append(drawItemSearch({ product: product })); } }else{ $('.autocomplete-items').append(`

${window.translate.products_list_empty}

`); } } } }).finally(() => { headerIconSearch.html(headerIconSearchHtml); headerIconSearch.attr('disabled', false); }) } function toggleSearch(){ document.querySelector("#wrapperHeaderSearch").classList.toggle("open--search"); } function drawItemSearch({ product: t }) { var e = null; return ( (e = t.has_sale_price ? `
\n
${t.formatted_sale_price}
\n ${t.formatted_price}\n
` : `
\n
${t.formatted_price}
\n
`), `\n
\n ${t.name}\n
\n
\n
${t.name}
\n ${e}\n
\n
` ); } (toastr.options.showEasing = "swing"), (toastr.options.showMethod = "slideDown"), (toastr.options.hideMethod = "slideUp"), document.addEventListener("DOMContentLoaded", function () { $(".search-input-input").on("input", function (t) { fetchProductsSearchDebounce(t.currentTarget); }); }), $("#btnToggleWrapperSearch").length > 0 && ($("#btnToggleWrapperSearch").on("click", function () { $("#headerWrapperSearch").toggleClass("active"); }), $(document).on("click", function (t) { $(t.target).closest("#headerWrapperSearch").length || $("#headerWrapperSearch").removeClass("active"); })); var fetchProductsSearchDebounce = debounce(function (t) { fetchProductsSearch($(t).attr("data-cat-id"), $(t).val()); }, 650); function fetchCart() { // const headerCartPrice = document.querySelector('.wrapper--header-cart .header--cart-price'); zid.store.cart.fetch().then(function (t) { if("success" === t.status){ setCartBadge(t.data.cart.products_count); // const {cart} = t.data; // headerCartPrice.textContent = cart.total.value.toFixed(2); } }); } function addToCartAnimation(t, e) { e && t && e .clone() .offset({ top: e.offset().top, left: e.offset().left }) .css({ opacity: "0.5", position: "absolute", height: "150px", width: "150px", "z-index": "100", }) .appendTo($("body")) .animate( { top: t.offset().top + 10, left: t.offset().left + 10, width: 75, height: 75, }, 1e3, "easeInOutExpo" ) .animate({ width: 0, height: 0 }, function () { $(this).detach(); }); } function addToCartApi({ product_id: t, quantity: e, onCompleted: a }) { zid.store.cart.addProduct({ productId: t, quantity: e }).then(function (t) { "success" === t.status ? (setCartBadge(t.data.cart.products_count), a && a()) : toastr.error(t.data.message); }); } function setCartBadge(t) { t > 0 ? ($(".cart-badge").removeClass("d-none"), $(".cart-badge").html(t)) : ($(".cart-badge").html("0"), $(".cart-badge").addClass("d-none")); } function setCartTotalAndBadge(t) { setCartBadge(t.products_count); } function addToCart(t, e = null) { const $btn = $(t); if($btn.hasClass('loading')) return; const tHtml = $btn.html(); $btn.addClass("loading"); $btn.html(''); addToCartApi({ product_id: e, quantity: 1, onCompleted: () => { $btn.removeClass("loading"); $btn.html(tHtml); fetchCart(); toastr.success($("#appBody").attr("data-cartsuccess")); $("#gift-tooltip").length > 0 && ($("#gift-tooltip").removeClass("d-none"), setTimeout(() => { $("#gift-tooltip").addClass("d-none"); }, 7e3)); }, }); } function closeSlidingMenu() { window.slidingMenu.close(); } window.toggleSidebar = function () { if(window.slidingMenu.isOpen){ window.slidingMenu.close(); }else{ window.slidingMenu.open(); } } function clearFilters() { $(".form-products-filter input").val(""); } document.addEventListener("DOMContentLoaded", function () { fetchCart(), (window.slidingMenuElement = document.getElementById("sliding-menu")), (window.slidingMenu = new SlideMenu(window.slidingMenuElement, { position: "right",//"ltr" === window.appDirection ? "left" : "right", showBackLink: !0, backLinkBefore: "ltr" === window.appDirection ? '' : '', submenuLinkAfter: "ltr" === window.appDirection ? '' : '', })), window.slidingMenuElement.addEventListener("sm.open", function () { $("body").addClass("sidenav-open"); }), window.slidingMenuElement.addEventListener("sm.close", function () { $("body").removeClass("sidenav-open"); }); }), $(document).delegate(".btn-number", "click", function (t) { t.preventDefault(); var e = $(this).attr("data-field"), a = $(this).attr("data-type"), n = $("input[name='" + e + "']"), i = parseInt(n.val()); isNaN(i) ? n.val(0) : "minus" === a ? (i > n.attr("min") && n.val(i - 1).change(), parseInt(n.val()) === n.attr("min") && $(this).attr("disabled", !0)) : "plus" === a && (i < n.attr("max") && n.val(i + 1).change(), parseInt(n.val()) === n.attr("max") && $(this).attr("disabled", !0)); }), $(document).delegate(".input-number", "focusin", function (t) { $(this).data("oldValue", $(this).val()); }), $(document).delegate(".input-number", "change", function (t) { var e = parseInt($(this).attr("min")), a = parseInt($(this).attr("max")), n = parseInt($(this).val()), i = $(this).attr("name"); n >= e ? $(".btn-number[data-type='minus'][data-field='" + i + "']").removeAttr( "disabled" ) : (alert("Sorry, the minimum value was reached"), $(this).val($(this).data("oldValue"))), n <= a ? $(".btn-number[data-type='plus'][data-field='" + i + "']").removeAttr( "disabled" ) : (alert("Sorry, the maximum value was reached"), $(this).val($(this).data("oldValue"))); }), $(document).delegate(".input-number", "keydown", function (t) { -1 !== $.inArray(t.keyCode, [46, 8, 9, 27, 13, 190]) || (65 === t.keyCode && !0 === t.ctrlKey) || (t.keyCode >= 35 && t.keyCode <= 39) || ((t.shiftKey || t.keyCode < 48 || t.keyCode > 57) && (t.keyCode < 96 || t.keyCode > 105) && t.preventDefault()); }); document.addEventListener("DOMContentLoaded", function(){ productsQuestions.checkAddQuestionPossibility(); }); class ProductsQuestions { constructor() { this.emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; this.customer = window.customer; this.customerName = $('#addQuestionShowModal input[name="name"]'); this.customerEmail = $('#addQuestionShowModal input[name="email"]'); this.customerQuestion = $('#addQuestionShowModal textarea[name="question"]'); this.isAnonymous = $('#addQuestionShowModal input[name="is_anonymous"]'); this.submitButton = $('.btn-submit-new-question'); } init() { const $this = this; document.addEventListener('zid-customer-fetched', function(event) { var customer = event.detail.customer; // null if the user is a guest if (customer) { $this.customer = customer; } }); } isValidEmail() { return this.emailRegex.test(this.customerEmail.val()); } showError(inputName) { $(`#addQuestionShowModal .input-error-${inputName}`).removeClass('d-none'); $(`#addQuestionShowModal input[name="${inputName}"], textarea[name="${inputName}"]`).addClass('border-danger'); } hideError(inputName) { $(`#addQuestionShowModal .input-error-${inputName}`).addClass('d-none'); $(`#addQuestionShowModal input[name="${inputName}"], textarea[name="${inputName}"]`).removeClass('border-danger'); } validateInputs() { let isValid = true; if (!this.customerQuestion.val().length) { this.showError('question'); isValid = false; } else { this.hideError('question'); } if (!this.customerEmail.val().length) { this.showError('email'); isValid = false; } else { this.hideError('email'); } if (this.customerEmail.val().length && !this.isValidEmail()) { $('#addQuestionShowModal .input-error-invalid-email').removeClass('d-none'); $('#addQuestionShowModal input[name="email"]').addClass('border-danger'); isValid = false; } else { $('#addQuestionShowModal .input-error-invalid-email').addClass('d-none'); } if (!this.customerName.val().length) { this.showError('name'); isValid = false; } else { this.hideError('name'); } return isValid; } fillCustomerData() { if (this.customer && this.customer.name && this.customer.email) { if (!this.customerName.val()) this.customerName.val(this.customer.name); if (!this.customerEmail.val()) this.customerEmail.val(this.customer.email); } } checkAddQuestionPossibility() { $('#addQuestionButton').click(function () { if (window.customer) { $('#addQuestionShowModal').modal('show'); productsQuestions.fillCustomerData(); } else { const currentPathname = location.pathname; const params = location.search; location.href = `/auth/login?redirect_to=${encodeURIComponent(currentPathname + params)}`; return; } }); } async submitQuestion(productId) { const isValid = this.validateInputs(); if (isValid) { $('.add-review-progress').removeClass('d-none'); this.submitButton.attr('disabled', true); try { const response = await zid.store.product.addQuestion( productId, this.customerQuestion.val(), this.customerName.val(), this.customerEmail.val(), this.isAnonymous.is(':checked'), ); if (response.status === 'success') { toastr.success(locales_messages.success, locales_messages.success_header); $('textarea[name="question"]').val(''); } } catch (error) { toastr.error(error, locales_messages.error); } finally { $('.add-review-progress').addClass('d-none'); $('#addQuestionShowModal').modal('hide'); this.submitButton.removeAttr('disabled'); } } } } const productsQuestions = new ProductsQuestions(); productsQuestions.init(); /** * ADDED To Cart With Option from product card */ /** * add To Cart With Option from product card */ window.productDitalVariants = []; const modalWrapper = document.querySelector('#productDitalModal'); // Get Product ditails function addToCartWithOption(elm, product_id) { const $elm = $(elm); if($elm.hasClass('loading')) return; $elm.addClass('loading'); $elm.closest('.product--cart').addClass('opacty-loading'); const $elmHtml = $elm.html(); zid.store.product.fetch(product_id).then((response)=>{ if(response.status === 'success'){ const product = response.data.product; window.productDitalVariants = product.variants; const images = product.images; productDitalViewSlider(images); drawFormContent(product); // Modal const modal = bootstrap.Modal.getOrCreateInstance('#productDitalModal'); modal.show(); }else{ console.log(response); } }).catch((errors)=>{ console.log(errors); toastr.error(errors); }).finally(() => { $elm.html($elmHtml); $elm.removeClass('loading'); $elm.closest('.product--cart').removeClass('opacty-loading'); }); } //Draw Slider function productDitalViewSlider(images) { if (images.length === 0) return; var thub = [] var itemsSldier = [] images.forEach(imageObj => { thub.push(`
${imageObj.alt_text||''}
`); itemsSldier.push(`
${imageObj.alt_text||''}
`); }); window.thumbsProductDitalModalSwiper.removeAllSlides(); window.productDitalModalSlider.removeAllSlides(); window.thumbsProductDitalModalSwiper.appendSlide(thub) window.productDitalModalSlider.appendSlide(itemsSldier) } // Draw Form Conent function drawFormContent(product) { const btnSubmit = $("#btnaddToCartProductModal"); btnSubmit.attr('data-product', JSON.stringify(product,null,0)); $("#productDitalModalFormConent").html('') var price = ''; if (product.has_sale_price) { price = `
${product.formatted_sale_price}
${product.formatted_price}
`; }else{ price = `
${product.formatted_price}
`; } const html = ` ${drawRating(product)}

${product.name}

${price}
${window.translate.product_sku}
${product.sku}
${drawOptions(product)}
${drawFilds(product)}`; $("#productDitalModalFormConent").html(html) } // Draw Rating function drawRating(product) { var ratingHtml= ''; // if (product.rating) { // ratingHtml = `
//
// // // // // //
//
// ${product.rating.total_count || '0'} // ${window.translate.product_reviews_x_count} //
//
`; // } return ratingHtml; } // Draw Options function drawOptions(product) { var optionsHtml = ''; const items = []; if (product?.options?.length > 0) { for (var i = 0; i < product.options.length; i++) { const option = product.options[i]; const ulUniqueId = `ul-option-ul-${i}` const choices = []; for (var j = 0; j < option.choices.length; j++) { if(product.options[i].name == 'Colors' || product.options[i].name == 'الألوان'){ let productVariant = ""; product?.variants?.forEach(variant => { variant?.attributes.forEach(attribute => { if(attribute.value == option.choices[j]){ productVariant = variant; } }) }) if (productVariant) { choices.push(`
  • ${option.choices[j]}
  • `) }else{ choices.push(`
  • ${option.choices[j]}
  • `) } }else{ choices.push(`
  • ${option.choices[j]}
  • `) } } items.push(`
    ${option.name}
    `) } optionsHtml = `${items.join('')}`; } return optionsHtml; } // Click Option List Item function productOptionListItemCustomClicked(event,ulUniqueId){ var currentProductVariants = ''; var attributeValue = ''; modalWrapper.querySelectorAll(`.size-box ul.${ulUniqueId} li`).forEach(element => { element.classList.remove('active'); }) event.target.classList.add('active'); const value = event.target.getAttribute('value'); modalWrapper.querySelector('#product-id').classList.remove('is-started'); for (let index = 0; index < window.productDitalVariants.length; index++) { const variant = window.productDitalVariants[index]; for (let index = 0; index < variant.attributes.length; index++) { const element = variant.attributes[index]; if (element.value === value) { attributeValue = element; currentProductVariants = variant; break; } } if (currentProductVariants) { break; } } const btnSubmit = $("#btnaddToCartProductModal"); toastr.clear() toastr.remove() if (currentProductVariants) { if(currentProductVariants.is_infinite == false && currentProductVariants.quantity < 1 ){ toastr.error(window.translate.lbl_error_product_out_of_stock); modalWrapper.querySelector('#btnaddToCartProductModal').classList.add('d-none'); }else{ modalWrapper.querySelector('#btnaddToCartProductModal').classList.remove('d-none'); btnSubmit.attr('data-product', JSON.stringify(currentProductVariants,null,0)); } productDitalViewSlider(currentProductVariants.images); modalWrapper.querySelector("#productName").innerHTML = currentProductVariants.name; modalWrapper.querySelector('#productDitalModalSku').innerHTML = currentProductVariants.sku; if (attributeValue) { modalWrapper.querySelector("#product-id").setAttribute('value',attributeValue.product_id); } if (currentProductVariants.formatted_sale_price) { modalWrapper.querySelector('#product-formatted-price').innerHTML = currentProductVariants.formatted_sale_price; modalWrapper.querySelector('#product-formatted-price-old').innerHTML = currentProductVariants?.formatted_price; }else{ modalWrapper.querySelector('#product-formatted-price').innerHTML = currentProductVariants.formatted_price; modalWrapper.querySelector('#product-formatted-price-old').innerHTML = ' '; } if(currentProductVariants.is_infinite || currentProductVariants.quantity > 0){ modalWrapper.querySelector('#btnaddToCartProductModal').classList.remove('d-none'); }else{ modalWrapper.querySelector('#btnaddToCartProductModal').classList.add('d-none'); } } } // Draw Filds function drawFilds(product) { /* var fildsHtml = []; if (product?.custom_input_fields?.length > 0) { for (let index = 0; index < product?.custom_input_fields.length; index++) { const type = product?.custom_input_fields[index].type; var conentValue = ''; switch (type) { case "CHECKBOX": const choices = product?.custom_input_fields[index].choices; conentValue = drawCheckbox(choices); break; default: break; } const element = product?.custom_input_fields[index]; var item = `
    ${element.label}
    ${conentValue}
    `; fildsHtml.push(item); } } */ return '';//fildsHtml.join(''); } // drow checkbox function drawCheckbox(choices) { var checkboxsHtml = []; for (let index = 0; index < choices.length; index++) { const element = choices[index]; var price = ''; if (element.formatted_price) { price = ` ( + ${element.formatted_price} ) `; } var item = ``; checkboxsHtml.push(item); } return checkboxsHtml.join(''); } // Add To Cart With Option function addToCartProductModal(elm) { if(modalWrapper.querySelector('#product-id').value == ''){ toastr.error(window.translate.required_options); return; } if (modalWrapper.querySelector('#product-id').classList.contains('is-started')) { toastr.error(window.translate.required_options); return; } var html = $(elm).html(); $(elm).html('
    Loading...
    '); zid.store.cart.addProduct({ formId:'productDitalModal-form' }).then(function (response) { if(response.status === 'success'){ setCartBadge(response.data.cart.products_count); // Modal Close const modal = bootstrap.Modal.getOrCreateInstance('#productDitalModal'); modal.hide(); toastr.success($('body').attr('data-cartsuccess')); }else{ toastr.error(`${response.data.message}, ${sorry}`); } }).catch(function (error) { toastr.error(`${sorry}`); }) .finally(function () { $(elm).html(html); }); } /** * ADD to Cart div fixed position if hide visible */ function fixedWrapperActionFormProduct() { // const wraapperFormAddToCartProduct = document.getElementById('wraapperFormAddToCartProduct'); // const wraapperFormAddToCartProductOffset = wraapperFormAddToCartProduct.offsetTop; // window.addEventListener('scroll', function (e) { // const scrollPosition = window.scrollY; // if(scrollPosition > wraapperFormAddToCartProductOffset){ // wraapperFormAddToCartProduct.classList.add("add--animation-pCard"); // }else{ // wraapperFormAddToCartProduct.classList.remove("add--animation-pCard"); // } // }) } document.addEventListener("DOMContentLoaded", function() { fixedWrapperActionFormProduct(); }); /** * Wishlist */ function fillWishlistItems(items) { items.forEach((product) => { $(`.add-to-wishlist[data-wishlist-id=${product.id}]`) .find(".icon-heart-mask") .addClass("filled"); }); } function addToWishlist(elm, productId) { $(elm).siblings(".add-to-wishlist .loader").removeClass("d-none"); $(elm).addClass("d-none"); // Remove From Wishlist if added if ($(elm).hasClass("filled")) { return removeFromWishlist(elm, productId); } zid.store.customer.addToWishlist(productId).then((response) => { if (response.status === "success") { $(elm).siblings(".add-to-wishlist .loader").addClass("d-none"); $(elm).addClass("filled").removeClass("d-none"); toastr.success(response.data.message); } else { toastr.error(response.data.message); } }); } function removeFromWishlist(elm, productId) { $(elm).siblings(".add-to-wishlist .loader").removeClass("d-none"); $(elm).addClass("d-none"); zid.store.customer.removeFromWishlist(productId).then((response) => { if (response.status === "success") { $(elm).siblings(".add-to-wishlist .loader").addClass("d-none"); $(elm).removeClass("d-none filled"); toastr.success(response.data.message); if (location.pathname === '/account-wishlist') { location.reload(); } } else { toastr.error(response.data.message); } }); } function shareWishlist() { $(".share-wishlist .loader").removeClass("d-none").siblings(".share-icon").addClass("d-none"); zid.store.customer.shareWishlist().then(async (response) => { if (response.status === "success") { $(".share-wishlist .loader").addClass("d-none").siblings(".share-icon").removeClass("d-none"); if (response.data.link) { try { await navigator.clipboard.writeText(response.data.link); toastr.success(response.data.message); } catch (error) { console.log(error); } } } else { toastr.error(response.data.message); } }); } // Product Card Image Slider function productCardInitSwiper() { if (document.querySelectorAll('.swiper-slider-product-card').length > 0) { new Swiper('.swiper-slider-product-card', { slidesPerView: 1, spaceBetween: 0, watchSlidesProgress: true, preventClicksPropagation:false, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, pagination: { el: '.swiper-pagination', type: 'bullets', }, }); } } function drawListColorsProductCard(item,productId){ const li = document.createElement('li'); li.setAttribute("onclick",`colorsClickItem(this,'#product-card-${productId}')`) li.setAttribute("data-images",JSON.stringify(item.images)); const img = document.createElement('img'); img.classList.add('img-fluid'); img.width = "18"; img.height = "18"; img.src = item.image; li.appendChild(img); return li } function setColorsProductCard() { const listPromise = []; document.querySelectorAll(".product--cart .list-colors-product-card[data-loading='false']").forEach((elm) => { function fetchProductC() { const elmProductID = elm.getAttribute("data-product-id"); zid.store.product.fetch(elmProductID).then(function (response) { if (response.status === "success") { const variants = response.data.product.variants; const items = []; variants.forEach((variant) => { variant.attributes.find((attribute) => { if (attribute.name === "Color" || attribute.name === "الألوان") { if (variant.images.length > 0) { items.push({ id: variant.id, image: variant.images[0]?.image.thumbnail, images: variant.images, }) } } }) }) items.forEach((item) => { elm.appendChild(drawListColorsProductCard(item,elmProductID)) }); } }).catch((error) => { // console.log(error); }).finally(() => { elm.setAttribute("data-loading","true"); }); } listPromise.push(fetchProductC()); }) Promise.all(listPromise); } document.addEventListener("DOMContentLoaded", function() { productCardInitSwiper(); setColorsProductCard(); const divSlidingMenu = document.querySelector("#sliding-menu") divSlidingMenu.querySelectorAll("a").forEach((linkEml)=>{ linkEml.addEventListener("click",function(e){ divSlidingMenu.scrollTo(0,0) }) }) }); function colorsClickItem(event, id) { const cardsByID = document.querySelectorAll(id); cardsByID.forEach((elm) => { const children = elm.querySelectorAll(".list-colors-product-card li"); children.forEach((elmLi) => { elmLi.classList.remove("active"); }); var itemsSldier = []; const images = JSON.parse(event?.getAttribute("data-images")); const sliderSwiper = elm.querySelector(".swiper-slider-product-card"); if (Array.isArray(images)) { images.forEach((image) => { itemsSldier.push(`
    `) }) } if (itemsSldier.length > 0) { sliderSwiper.swiper.removeAllSlides(); itemsSldier.forEach((item) => { sliderSwiper.swiper.appendSlide(item); }) } event.classList.add("active"); }); } // function colorsClickItem(event, id) { // const cardsByID = document.querySelectorAll(id); // cardsByID.forEach((elm) => { // const children = elm.querySelectorAll(".list-colors-product-card li"); // children.forEach((elmLi) => { // elmLi.classList.remove("active"); // }); // const imgUrl = event.getAttribute("img-url"); // const imgElm = elm.querySelector(".main-img"); // imgElm.setAttribute("src",imgUrl); // event.classList.add("active"); // }); // } // Change product card column function changeProductCardColumn(className) { if (document.querySelector("#contentPageProducts")) { const container = document.querySelector("#contentPageProducts"); container.classList.remove("cout-coulumns-1"); container.classList.remove("cout-coulumns-2"); container.classList.remove("cout-coulumns-3"); container.classList.remove("cout-coulumns-4"); container.classList.add(className); } } function initChangeProductCardColumn() { const container = document.querySelector("#contentPageProducts"); const isFilter = $("#products-list").attr('data-is-filter') == '1' ? true : false; if (isFilter && window.matchMedia("(min-width: 992px)").matches) { changeProductCardColumn("cout-coulumns-3"); }else if(!isFilter && window.matchMedia("(min-width: 992px)").matches) { changeProductCardColumn("cout-coulumns-4"); }else{ changeProductCardColumn("cout-coulumns-2"); } } initChangeProductCardColumn(); // Draw Product Card function drawProductCard({product,isPreviews = false,isFilter=false,isNoSlider=true,isRemoveEmpty=false}) { const out_of_stockClass = product.out_of_stock ? 'out-stock' : ''; const out_of_stockLabel = product.out_of_stock ? `` : ''; const sliderImages = []; let btnAddToCart = ''; let optionColors = ''; // let product_reviews = ''; const jsonString = JSON.stringify(product,null,0); let product_price = ''; if (isRemoveEmpty && product?.out_of_stock) { return null; } if (product.images.length > 0) { product.images.forEach((image) => { sliderImages.push(`
    ${product.name}
    `) }) } if (product.out_of_stock) { btnAddToCart = ''; } if (product.has_options || product.has_field && !product.out_of_stock) { btnAddToCart = ``; } if(!product.has_options && !product.has_field && !product.out_of_stock){ btnAddToCart = ``; } if (Array.isArray(product?.metafields) && product?.metafields?.length > 0) { product.metafields.forEach((metafield) => { if (metafield.slug == "show-colors-4") { optionColors = ``; } }); } if (isPreviews) { // product_reviews = `
    //
    // 0 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 1 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 2 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 3 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 4 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> //
    // ${ product?.rating?.average ? product?.rating?.average : '0' } //
    `; } if (product.formatted_sale_price) { product_price = `
    ${product.currency_symbol} ${product.price}
    ${product.currency_symbol} ${product.sale_price}
    `; }else{ product_price = `
    ${product.currency_symbol} ${product.price}
    `; } return `
    ${out_of_stockLabel}
    ${sliderImages.join(' ')}
    ${btnAddToCart}
    ${optionColors} ${product.name}
    ${product.short_description}
    ${product_price}
    `; } function drawProductCard2({product,isPreviews = false,isFilter=false,isNoSlider=true,isRemoveEmpty=false}) { const out_of_stockClass = !product.is_available ? 'out-stock' : ''; const out_of_stockLabel = !product.is_available ? `` : ''; const sliderImages = []; let btnAddToCart = ''; let optionColors = ''; const jsonString = JSON.stringify(product,null,0); // let product_reviews = ''; let product_price = ''; if (isRemoveEmpty && !product?.is_available) { return null; } if (product.images.length > 0) { product.images.forEach((image) => { sliderImages.push(`
    ${product.name}
    `) }) } if (!product?.is_available || product.quantity <= 0) { btnAddToCart = ''; }else{ btnAddToCart = ``; } // if (product.has_options || product.has_field && product?.is_available) { // btnAddToCart = ``; // } // if(!product.has_options && !product.has_field && !product?.is_available){ // btnAddToCart = ``; // } if (Array.isArray(product?.metafields) && product?.metafields?.length > 0) { product.metafields.forEach((metafield) => { if (metafield.slug == "show-colors-4") { optionColors = ``; } }); } if (isPreviews) { // product_reviews = `
    //
    // 0 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 1 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 2 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 3 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> // 4 ? `class="fa-solid fa-star"` : `class="fa-regular fa-star"`}> //
    // ${ product?.rating?.average ? product?.rating?.average : '0' } //
    `; } if (product.formatted_sale_price) { product_price = `
    ${product.currency} ${product.price}
    ${product.currency} ${product.sale_price}
    `; }else{ product_price = `
    ${product.currency} ${product.price}
    `; } return `
    ${out_of_stockLabel}
    ${sliderImages.join(' ')}
    ${btnAddToCart}
    ${optionColors} ${product.name}
    ${product.short_description}
    ${product_price}
    `; } // Load more products function getAttributesUrl(arr) { if (!Array.isArray(arr)) { return; } return arr.reduce((acc, curr) => { const [key, value] = curr.split('='); const newKey = key.replace('[]', ''); if (newKey === 'attribute_values') { acc[newKey] = (acc[newKey] || []).concat(value); } else { acc[newKey] = value; } return acc; }, {}); } function getData() { // const btnloadMore = document.querySelector(".btn--loadmore"); const btnLoadMoreProducts = $("#btnLoadMoreProducts"); const queryStringArray = decodeURIComponent(window.location.search.includes('?') && window.location.search.replace('?','')).split('&'); let queryString = {}; let categoryID = document.querySelector("#contentPageProducts").getAttribute("data-category-id") != '' ? Number(document.querySelector("#contentPageProducts").getAttribute("data-category-id")) : null; if (decodeURIComponent(window.location.search.includes('?') && window.location.search.replace('?','')).split('&').includes("false")) { queryString.page = btnLoadMoreProducts.attr("data-page"); }else{ queryString = { page:btnLoadMoreProducts.attr("data-page"), ...getAttributesUrl(queryStringArray) } } queryString.zid_country = window.zid_country; queryString.zid_currency = window.zid_currency; queryString.zid_language = window.zid_language; queryString.per_page = 34; const btnHtml = btnLoadMoreProducts.html(); btnLoadMoreProducts.html(`
    Loading...
    `); zid.store.product.fetchAll(categoryID, queryString).then(function (response) { const {status, data} = response; if (status == 'success') { const {products} = data; const page = products.next_page_url ? products.next_page_url.split('=')[products.next_page_url.split('=').length - 1] : false; if (page) { btnLoadMoreProducts.attr('data-page', products.next_page_url.split('=')[products.next_page_url.split('=').length - 1]); }else{ btnLoadMoreProducts.removeClass("d-flex"); btnLoadMoreProducts.addClass("d-none"); } if (Array.isArray(products.data)) { const isPreviews = $("body").attr('data-productreviews') == '1' ? true : false; const isFilter = $("#products-list").attr('data-is-filter') == '1' ? true : false; const items = []; const listProducts = products.data; listProducts.map((p)=>{ items.push(drawProductCard({product:p,isPreviews:isPreviews,isFilter:isFilter})) }) $("#products-list").append(items.join(' ')); } } }).catch(function (error) { }).finally(function () { btnLoadMoreProducts.html(btnHtml); productCardInitSwiper(); setColorsProductCard(); initBundleOffer(); }); } function loadMoreProducts() { getData(); } // Bundle offer && Badge function initBundleOffer() { let bundle_products_ids_elements = document.querySelectorAll('[data-bundle-offer-product-id]'); if(bundle_products_ids_elements && bundle_products_ids_elements.length > 0 && zid.store.product.fetchProductsBundleOffer) { let productIds = []; bundle_products_ids_elements.forEach((bundle_products_ids_element) => { let productId = bundle_products_ids_element.getAttribute('data-bundle-offer-product-id'); if(productIds.indexOf(productId) === -1) { productIds.push(productId); } }) if(productIds.length > 0) { zid.store.product.fetchProductsBundleOffer(productIds).then((response) => { if(response.status === "success" && response.data && response.data.bundle_offer && response.data.bundle_offer.payload ) { if(response.data.bundle_offer && response.data.bundle_offer.payload) { response.data.bundle_offer.payload.forEach((productBundleOffer) => { productBundleOffer.product_ids.forEach((id) => { let target_bundle_products_ids_elements = document.querySelectorAll('[data-bundle-offer-product-id="'+id+'"]'); let target_badge_products_ids_elements = document.querySelectorAll('[data-badge-name-product-id="'+id+'"]'); target_bundle_products_ids_elements.forEach((target_bundle_products_ids_element) => { target_bundle_products_ids_element.innerHTML = productBundleOffer.name; target_bundle_products_ids_element.classList.add("bundle-offer-product-tag"); }) target_badge_products_ids_elements.forEach((target_badge_products_ids_element) => { const lang = document.documentElement.lang; target_badge_products_ids_element.style.top = "44px"; if(lang == 'ar') { target_badge_products_ids_element.style.right = "15px"; } else { target_badge_products_ids_element.style.right = "auto"; target_badge_products_ids_element.style.left = "17px"; } }) }) }) } } }) } } } // Modal Video function onPlayerReady(event) { event.target.setLoop(1); event.target.playVideo(); } function openShortVideoModal(elm) { const videoPath = elm.getAttribute("data-video-path"); const myModalEl = document.querySelector('#videoWithProducts'); const productDitalModalElm = document.querySelector('#productDitalModal'); const btnVideoSound = myModalEl.querySelector("#videoSound"); const modal = bootstrap.Modal.getOrCreateInstance(myModalEl); const videoShortPlayer = myModalEl.querySelector("#videoShortPlayer"); // const slider = ; const products = elm.getAttribute("data-products") ? JSON.parse(elm.getAttribute("data-products")) : []; const videoElment = document.createElement('video'); videoElment.src = videoPath; videoElment.volume = 1; videoElment.loop = 1; videoElment.autoplay = 1; videoShortPlayer.append(videoElment); if (window.shortvideoSliderProduct) { window.shortvideoSliderProduct.removeAllSlides(); if (Array.isArray(products)) { products.forEach((p)=>{ if (drawProductCard({ product:p, isPreviews:false, isFilter:false, isNoSlider:false,isRemoveEmpty:true })) { window.shortvideoSliderProduct.appendSlide(`
    ${drawProductCard({ product:p, isPreviews:false, isFilter:false, isNoSlider:false,isRemoveEmpty:true })}
    `); } }) productCardInitSwiper(); } } modal.show(); btnVideoSound.addEventListener('click', event => { if (videoElment.volume > 0) { btnVideoSound.classList.remove("sound-on"); btnVideoSound.classList.add("sound-off"); videoElment.volume = 0; }else{ btnVideoSound.classList.remove("sound-off"); btnVideoSound.classList.add("sound-on"); videoElment.volume = 1; } }) myModalEl.addEventListener('hidden.bs.modal', event => { btnVideoSound.classList.remove("sound-off"); btnVideoSound.classList.add("sound-on"); if (videoElment) { videoElment.remove(); } }) productDitalModalElm.addEventListener('show.bs.modal', event => { modal.hide() }) } const rangeArr = (start, end, step = 1) => { let output = []; if (typeof end === 'undefined') { end = start; start = 0; } for (let i = start; i < end; i += step) { output.push(i); } return output; }; window.onProductAttributesTriggered = function(){ $('#products-list').css('opacity', '0.4'); $('#product-pagination').css('opacity', '0'); } window.onProductAttributesChanged = function(htmlStr){ const urlParams = new URLSearchParams(window.location.search); if (!urlParams.has('search')) { const productsList = $("#products-list"); productsList.removeClass("d-none"); $("#product-pagination").removeClass("opacity-0") $("#products-list").removeClass("opacity-0") $('#products-list').css('opacity', '1'); $('#product-pagination').css('opacity', '1'); var html = $.parseHTML( htmlStr ); $('#products-list').html($('#products-list', html).html()); $('#products-list').css('opacity', '1'); $('#product-filter-count').html($('#product-filter-count', html).html()); $('#product-filter-count').css('opacity', '1'); if($('#product-pagination', html).length>0){ $('#product-pagination').html($('#product-pagination', html).html()); $('#product-pagination').css('opacity', '1'); } productCardInitSwiper(); }else{ searchProductsWithPagination(); } } document.addEventListener("DOMContentLoaded",function(){ const urlParams = new URLSearchParams(window.location.search); const productsList = $("#products-list"); if (urlParams.has('search')) { searchProductsWithPagination(); }else{ productsList.removeClass("d-none"); $("#product-pagination").removeClass("opacity-0") $("#products-list").removeClass("opacity-0") $('#products-list').css('opacity', '1'); $('#product-pagination').css('opacity', '1'); } })