/** * Libs */ /** * Utils */ function debounce(func, wait, immediate) { var timeout; return function () { var context = this, args = arguments; var later = function () { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; toastr.options.showEasing = 'swing'; toastr.options.showMethod = 'slideDown'; toastr.options.hideMethod = 'slideUp'; /** * Draw Product Item In search */ function drawItemSearch({ product }) { var price = null; if (product.has_sale_price) { price = `
${product.formatted_sale_price}
${product.formatted_price}
` } else { price = `
${product.formatted_sale_price}
` } return `
${product.name}
${product.name}
${price}
` } /** * Header Form Search */ $(".search-input-input").on("input", function (event) { fetchProductsSearchDebounce(event.currentTarget) }); var fetchProductsSearchDebounce = debounce(function (target) { fetchProductsSearch($(target).attr('data-cat-id'), $(target).val()) }, 650); 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...
`) zid.store.product.fetchAll(catId, { per_page: 10, search: encodeURI(query) }).then(function (response) { if (response.status === 'success') { if (response.data) { $('.autocomplete-items').html(''); for (var i = 0; i < response.data.products.data.length; i++) { var product = response.data.products.data[i]; $('.autocomplete-items').append(drawItemSearch({ product: product })); } } } }).finally(() => { headerIconSearch.html(headerIconSearchHtml) }) } /** * Cart */ function fetchCart() { zid.store.cart.fetch().then(function (response) { if(response.status === 'success'){ if(response.data) { setCartBadge(response.data.cart.products_count) } } }) } function addToCartAnimation(cart, imgtodrag) { if (imgtodrag && cart) { var imgclone = imgtodrag.clone() .offset({ top: imgtodrag.offset().top, left: imgtodrag.offset().left }) .css({ 'opacity': '0.5', 'position': 'absolute', 'height': '150px', 'width': '150px', 'z-index': '100' }) .appendTo($('body')) .animate({ 'top': cart.offset().top + 10, 'left': cart.offset().left + 10, 'width': 75, 'height': 75 }, 1000, 'easeInOutExpo'); imgclone.animate({ 'width': 0, 'height': 0 }, function () { $(this).detach() }); } } function addToCartApi({product_id, quantity, onCompleted}) { zid.store.cart.addProduct({productId: product_id, quantity: quantity}).then(function (response) { if(response.status === 'success') { setCartBadge(response.data.cart.products_count); if (onCompleted) { onCompleted(); } } else{ toastr.error(response.data.message); } }) } function setCartBadge(badge) { if(badge > 0){ $('.cart-badge').removeClass('d-none'); $('.cart-badge').html(badge); }else { $('.cart-badge').html('0'); $('.cart-badge').addClass('d-none'); } } function addToCart(elm,product_id=null) { addToCartApi({product_id:product_id,quantity:1,onCompleted:()=>{ if(elm){ if (!$("#appBody").hasClass('not-animation-cart')) { var getParentDiv = $(elm).parent(); var image = $('#product-card-img-'+product_id, getParentDiv); console.log(image); var cart = $('.header--cart'); addToCartAnimation(cart, image); } } toastr.success(window.translate.cart_success) }}) } /** * Mobile slide menu */ document.addEventListener("DOMContentLoaded", function(){ window.slidingMenuElement = document.getElementById('sliding-menu'); window.slidingMenu = new SlideMenu(window.slidingMenuElement,{ position: (window.appDirection === 'ltr') ? 'left' : 'right', showBackLink: true, backLinkBefore: (window.appDirection === 'ltr') ? '' : '', submenuLinkAfter: (window.appDirection === 'ltr') ? '' : '' }); window.slidingMenuElement.addEventListener('sm.open', function () { $('body').addClass('sidenav-open'); }); window.slidingMenuElement.addEventListener('sm.close', function () { $('body').removeClass('sidenav-open'); }); }) function closeSlidingMenu () { window.slidingMenu.close() } /** * Input quantity */ $(document).delegate('.btn-number', 'click', function (e) { e.preventDefault(); var fieldName = $(this).attr('data-field'), type = $(this).attr('data-type'), input = $("input[name='" + fieldName + "']"), currentVal = parseInt(input.val()); if (!isNaN(currentVal)) { if (type === 'minus') { if (currentVal > input.attr('min')) { input.val(currentVal - 1).change(); } if (parseInt(input.val()) === input.attr('min')) { $(this).attr('disabled', true); } } else if (type === 'plus') { if (currentVal < input.attr('max')) { input.val(currentVal + 1).change(); } if (parseInt(input.val()) === input.attr('max')) { $(this).attr('disabled', true); } } } else { input.val(0); } }); $(document).delegate('.input-number', 'focusin', function (e) { $(this).data('oldValue', $(this).val()); }); $(document).delegate('.input-number', 'change', function (e) { var minValue = parseInt($(this).attr('min')), maxValue = parseInt($(this).attr('max')), valueCurrent = parseInt($(this).val()); var name = $(this).attr('name'); if (valueCurrent >= minValue) { $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled') } else { alert('Sorry, the minimum value was reached'); $(this).val($(this).data('oldValue')); } if (valueCurrent <= maxValue) { $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled') } else { alert('Sorry, the maximum value was reached'); $(this).val($(this).data('oldValue')); } }); $(document).delegate('.input-number', 'keydown', function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode === 65 && e.ctrlKey === true) || // Allow: home, end, left, right (e.keyCode >= 35 && e.keyCode <= 39)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); function clearFilters () { $('.form-products-filter input').val(''); } /** * 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(); $elm.html(`
Loading...
`) 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(); } }).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||''}
`); }); console.log('window.thumbsProductDitalModalSwiper',window.thumbsProductDitalModalSwiper); console.log('window.productDitalModalSlider',window.productDitalModalSlider); window.thumbsProductDitalModalSwiper.removeAllSlides(); window.productDitalModalSlider.removeAllSlides(); window.thumbsProductDitalModalSwiper.appendSlide(thub) window.productDitalModalSlider.appendSlide(itemsSldier) } // Draw Form Conent function drawFormContent(product) { $("#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 choices = []; for (var j = 0; j < option.choices.length; j++) { choices.push(`
  • ${option.choices[j]}
  • `) } items.push(`
    ${option.name}
    `) } optionsHtml = `${items.join('')}`; } return optionsHtml; } // Click Option List Item function productOptionListItemCustomClicked(event){ var currentProductVariants = ''; var attributeValue = ''; modalWrapper.querySelectorAll('.size-box 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; } } if (currentProductVariants) { 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 = []; // custom_input_fields 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); }); } /** * Header */ function headerSticky() { window.onscroll = function () { myFunction(); }; // Get the header var header = document.getElementById("pages-main-header"); // Get the offset position of the navbar var sticky = header.offsetTop; // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position function myFunction() { if (header.classList.contains("header--with--announcement")) { if (window.pageYOffset >= sticky + 50) { header.classList.add("sticky--header"); } else { header.classList.remove("sticky--header"); } }else{ if (window.pageYOffset >= 10) { header.classList.add("sticky--header"); } else { header.classList.remove("sticky--header"); } } } } window.addEventListener( "resize", function (event) { headerSticky(); }, true ); document.addEventListener("DOMContentLoaded", function() { headerSticky(); }); // 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(); /** * * 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 Color */ // document.querySelectorAll(".list--product-card-colors").forEach((elm) => { // elm.querySelectorAll("li").forEach((elmLi) => { // elmLi.addEventListener("click", function (event) { // const imId = event.target.dataset.imgId; // const imgUrl = event.target.dataset.img; // elm.querySelector(".active").classList.remove("active"); // event.target.classList.add("active"); // document.querySelectorAll(imId).forEach((elm) => { // elm.setAttribute("src", imgUrl); // }); // }) // }) // }) document.addEventListener("DOMContentLoaded", function () { document.querySelectorAll(".product--cart").forEach((productCard) => { const swiper = new Swiper(productCard.querySelector(`#productCardImgSlider-${productCard.dataset.productId}`), { slidesPerView: 1, spaceBetween: 0, pagination: { el: `#productCardImgSlider-${productCard.dataset.productId} .swiper-pagination`, type: 'bullets', }, autoplay: { delay: 4000, disableOnInteraction: false, pauseOnMouseEnter: true, }, }); const listItemClick = productCard.querySelectorAll(".list--product-card-colors li"); swiper.on("activeIndexChange", function (swiper) { if (listItemClick.length > 0) { productCard.querySelectorAll('.list--product-card-colors li.active').forEach((elm) => { elm.classList.remove('active'); }); listItemClick[swiper.activeIndex].classList.add('active'); } }) listItemClick.forEach((elm, index) => { elm.addEventListener("click", function (event) { swiper.slideTo(index); }) }) }) // document.querySelectorAll(".list--product-card-colors").forEach((elm) => { // elm.querySelectorAll("li").forEach((elmLi) => { // elmLi.addEventListener("click", function (event) { // const imId = event.target.dataset.imgId; // const imgUrl = event.target.dataset.img; // elm.querySelector(".active").classList.remove("active"); // event.target.classList.add("active"); // document.querySelectorAll(imId).forEach((elm) => { // elm.setAttribute("src", imgUrl); // }); // }) // }) // }) });