document.addEventListener("DOMContentLoaded", () => { const domain = "https://productreview.myappgurus.com/api/", customerId = __st.cid, shopId = __st.a, shopName = Shopify.shop, reviewData = (document.querySelector('.mag-product-review-summary').textContent.trim() != '') ? JSON.parse(document.querySelector('.mag-product-review-summary').textContent) : {}; const getFirstImage = (imageUrl) => { if (!imageUrl) return null; // Check if image URL contains multiple images (comma-separated) if (imageUrl.includes(',')) { const images = imageUrl.split(','); return images[0].trim(); // Return first image URL } return imageUrl; // Return single image URL } const metafieldUpdater = () => { fetch(`${domain}metafieldDatasUpdates`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ shop: Shopify.shop, }), }) .then(response => response.json()) .then(response => { if (response) { customArraysdata = myappgurusreviewsettings; } }); } let customArraysdata = false; const myappgurusreviewsettings = window.myappgurusreviewsettings; if (myappgurusreviewsettings && myappgurusreviewsettings.length > 0) { customArraysdata = myappgurusreviewsettings; } else { customArraysdata = false; } if (myappgurusreviewsettings == null || myappgurusreviewsettings == undefined || myappgurusreviewsettings == "") { metafieldUpdater(); } const customArrayData = (customArraysdata) ? JSON.parse(customArraysdata) : {}; // const toptenreviews = window.toptenmyappgurusreview; // const reviewspopup = (toptenreviews) ? JSON.parse(toptenreviews) : {}; // const latesttenReview = reviewspopup.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); // const latestReview = latesttenReview.length > 0 ? latesttenReview[0] : null; const toptenreviews = window.toptenmyappgurusreview || "[]"; let reviewspopup = []; try { reviewspopup = JSON.parse(toptenreviews); if (!Array.isArray(reviewspopup)) { reviewspopup = []; } } catch (error) { console.error("Error parsing reviews JSON:", error); reviewspopup = []; } const latesttenReview = reviewspopup.length ? reviewspopup.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)) : []; const latestReview = latesttenReview.length > 0 ? latesttenReview[0] : null; function formatDateAndRelativeTime(dateString) { const inputDate = new Date(dateString); const currentDate = new Date(); const formattedDate = inputDate.toISOString().split('T')[0]; const diffYears = currentDate.getFullYear() - inputDate.getFullYear(); const diffMonths = (currentDate.getMonth() - inputDate.getMonth()) + (diffYears * 12); let relativeTime; if (diffYears >= 1) { relativeTime = `${diffYears} year${diffYears > 1 ? 's' : ''} ago on ${formattedDate}`; } else if (diffMonths >= 6) { relativeTime = `6 months ago on ${formattedDate}`; } else if (diffMonths >= 3) { relativeTime = `3 months ago on ${formattedDate}`; } else if (diffMonths >= 1) { relativeTime = `1 month ago on ${formattedDate}`; } else { relativeTime = `on ${formattedDate}`; } return { relativeTime: relativeTime, formattedDate: formattedDate }; } const checkFileType = (url) => { let extension = url.split('.').pop().toLowerCase(), videoExtensions = ['mp4', 'mov', 'webm', 'mkv']; if (videoExtensions.includes(extension)) { return 'video'; } else { return 'image'; } } const appendElementInHtml = (data) => { let parser = new DOMParser(), htmlBtnDocument = parser.parseFromString(data, 'text/html'), htmlBtnElement = htmlBtnDocument.body.firstChild; return htmlBtnElement; } // const isLink = (str) => {const urlPattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/; return urlPattern.test(str);} const isLink = (url) => { if (url.startsWith('https://cdn.shopify.com')) { return url; } else if (url.startsWith('assets/')) { let fullUrl = `${domain}${url}`; return fullUrl; } else { return url; } } const starStyleCollectionPage = (star_style, color, response, status) => { let reviews = '', starColor = (color !== null && color.trim() !== '' && color !== undefined) ? color : 'currentColor', ratings = (response != undefined) ? (response.average != undefined) ? parseFloat(response.average).toFixed(1) : '0.0' : '0.0', ratingCount = (response != undefined) ? (response.totalCount != undefined) ? response.totalCount : '0' : '0'; switch (star_style) { case 'single_star_with_rating': reviews = ``; if (Math.floor(ratings) !== 0) { reviews += star((response != undefined) ? (parseFloat(response.average) !== 0) ? 'filled' : 'not-filled' : 'not-filled', starColor); reviews += `(${ratings})`; } else { reviews += starWithNoRating('not-filled'); } reviews += ``; break; case 'single_star_with_total_reviews': reviews = ``; if (Math.floor(ratings) !== 0) { reviews += star((response != undefined) ? (parseFloat(response.average) !== 0) ? 'filled' : 'not-filled' : 'not-filled', starColor); reviews += `(${ratingCount})`; } else { reviews += starWithNoRating('not-filled'); } reviews += ``; break; case 'star_with_rating_or_total_reviews': reviews = ``; if (Math.floor(ratings) !== 0) { reviews += star((response != undefined) ? (parseFloat(response.average) !== 0) ? 'filled' : 'not-filled' : 'not-filled', starColor); reviews += `${ratings} (${ratingCount})`; } else { reviews += starWithNoRating('not-filled'); } reviews += ``; break; case 'star_with_rating': reviews += ``; for (index = 0; index < 5; index++) { if (index < Math.floor(ratings) && Math.floor(ratings) != 0) { reviews += star('filled', starColor); } else if ((ratings - Math.floor(ratings)) > 0 && index < Math.ceil(ratings)) { reviews += star('half-filled', starColor); } else { reviews += (Math.floor(ratings) !== 0) ? star('not-filled', starColor) : starWithNoRating('not-filled'); } } if (Math.floor(ratings) !== 0) { reviews += `(${ratings})` } reviews += ``; break; case 'star_with_total_reviews': reviews += ``; for (index = 0; index < 5; index++) { if (index < Math.floor(ratings) && Math.floor(ratings) != 0) { reviews += star('filled', starColor); } else if ((ratings - Math.floor(ratings)) > 0 && index < Math.ceil(ratings)) { reviews += star('half-filled', starColor); } else { reviews += (Math.floor(ratings) !== 0) ? star('not-filled', starColor) : starWithNoRating('not-filled'); } } if (Math.floor(ratings) !== 0) { reviews += `(${ratingCount})` } reviews += ``; break; case 'star_rating': reviews += ``; let reviewLabel = (__st.a === 76038046042 || __st.a === 75680579909 || __st.a === 77037207880) ? status == true ? ratingCount > 1 ? 'Reviews' : 'Review' : '' : ''; for (index = 0; index < 5; index++) { if (index < Math.floor(ratings) && Math.floor(ratings) != 0) { reviews += star('filled', starColor); } else if ((ratings - Math.floor(ratings)) > 0 && index < Math.ceil(ratings)) { reviews += star('half-filled', starColor); } else { reviews += (Math.floor(ratings) !== 0) ? star('not-filled', starColor) : starWithNoRating('not-filled'); } } if (Math.floor(ratings) !== 0) { reviews += `${ratings} (${ratingCount}${reviewLabel ? ` ${reviewLabel}` : ''})` } reviews += ``; break; default: break; } return reviews; } const checkLogo = () => { let formLogo = document.querySelector('#erpReviewFrom .mag-logo-image'); if (!formLogo || (document.querySelector('.mag-logo-image').getAttribute('style') != 'display:block !important;') || (document.querySelector('.form.mag-logo-wrapper').getAttribute('style') != 'display:flex !important;') || (document.querySelector('.form.mag-logo-wrapper a').getAttribute('style') != 'display:flex !important;') || (document.querySelector('.form.mag-logo-wrapper a span')?.getAttribute('style') != 'display:inline !important;') || (document.querySelector('.form.mag-logo-wrapper a img').getAttribute('style') != 'display:inline !important;')) { if ((__st.a !== 82898092358)) { if (customArrayData.removeWaterMark != '1') { if (__st.a == '13326581') { } else { let logoData = `
${window.myappgurus.prm.powered_by.label}
`, logo = appendElementInHtml(logoData); document.querySelector('#erpReviewFrom')?.insertAdjacentElement('beforeend', logo); } } } } } const star = (type, color) => { let star = ''; switch (type) { case 'not-filled': star = ``; break; case 'filled': star = ``; break; case 'half-filled': star = ` `; break; default: star = ``; break; } return star; } const starWithNoRating = (type) => { let star = ''; starColor = (customArrayData.noReviewStarcolor && customArrayData.noReviewStarcolor !== null && customArrayData.noReviewStarcolor !== undefined && customArrayData.noReviewStarcolor.trim() !== '') ? customArrayData.noReviewStarcolor : 'currentColor'; switch (type) { case 'not-filled': if (customArrayData.noStarPatter[0] == 'prefill_stars') { star = ``; } else if (customArrayData.noStarPatter[0] == 'empty_stars') { star = ``; } else if (customArrayData.noStarPatter[0] == 'no_reviews') { star = ``; } else { star = ``; } break; default: break; } return star; } const reviewFooter = (response) => { let html = ``; return html; } const reviewPagination = (response, url) => { let html = '', page = (url !== null) ? new URLSearchParams(url.split('?')[1]) : null, pageNo = (page !== null) ? page.get('page') : 1; starcolor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : 'currentColor'; html += ``; return html; } const reviewVerified = (response) => { let verified = '', starcolor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : 'currentColor'; if (response.varified == '1') { verified = ` Verified Customer `; } return verified; } var getProTitle = async () => { if (document.querySelector('#epr-product-title-review')?.hasAttribute('data-product-title')) { return Promise.resolve(document.querySelector('#epr-product-title-review')?.getAttribute('data-product-title')); } else { let proHandle = document.querySelector('#epr-product-title-review').getAttribute('data-product-handle'); let fd = new FormData(); fd.append('shop', Shopify.shop); fd.append('proHandle', proHandle); fetch(`${domain}getproducttitle`, { method: "POST", headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: fd, }) .then(res => res.json()) .then(response => { return response; }) } } const richSnippet = (response, proTitle) => { let reviewData = response.reviewData, reviews = []; reviewData.forEach(curr => { reviews.push(`{ "@type": "Review", "reviewRating": { "@type": "Rating", "ratingValue": ${parseFloat(curr.rating).toFixed(1)}, "bestRating": 5 }, "author": { "@type": "Person", "name": "${curr.name}" } }`); }); reviews = reviews.join(',\n'); let existingProductJSONLD = Array.from(document.querySelectorAll('script[type="application/ld+json"]')).find(script => { try { let parsedData = JSON.parse(script.textContent); return parsedData && parsedData["@type"] === "Product"; } catch (error) { return false; } }); if (existingProductJSONLD) { let existingData = JSON.parse(existingProductJSONLD.textContent); existingData.review = existingData.review || []; existingData.review = existingData.review.concat(JSON.parse(`[${reviews}]`)); existingData.aggregateRating = { "@type": "AggregateRating", "ratingValue": existingData.aggregateRating?.ratingValue || response.rating.toFixed(1), "reviewCount": existingData.aggregateRating?.reviewCount || response.count }; existingProductJSONLD.textContent = JSON.stringify(existingData, null, 2); } else { createNewJSONLD(); } function createNewJSONLD() { let scriptData = `{ "@context": "https://schema.org/", "@type": "Product", "name": "${proTitle}", "review": [${reviews}], "aggregateRating": { "@type": "AggregateRating", "ratingValue": ${parseFloat(response.rating).toFixed(1)}, "reviewCount": ${response.count} } }`; let scriptElement = document.createElement('script'); scriptElement.setAttribute('type', 'application/ld+json'); scriptElement.innerHTML = scriptData; document.head.appendChild(scriptElement); } } const starsWithProgressBar = (response, color) => { let reviewStars = ''; for (index = 5; index > 0; index--) { let starReviews = '', reviewInPer = parseInt((((response.reviewCount.find(item => item.rating == index) != undefined) ? response.reviewCount.find(item => item.rating == index).count : 0) * 100) / response.count); for (index1 = 0; index1 < 5; index1++) { if (index1 < index) { starReviews += star('filled', color); } else { starReviews += star('not-filled', color); } } reviewStars += `
${starReviews}
${((response.reviewCount.find(item => item.rating == index) != undefined) ? response.reviewCount.find(item => item.rating == index).count : 0) == 0 ? `${(response.reviewCount.find(item => item.rating == index) != undefined) ? response.reviewCount.find(item => item.rating == index).count : 0}` : ` ${(response.reviewCount.find(item => item.rating == index) != undefined) ? response.reviewCount.find(item => item.rating == index).count : 0} `}
`; } return reviewStars; } var authenticate = () => { addCustomisationCss(); if (__st.a == '8795291711') { setTimeout(() => { appendCollectionClass(true); }, 5000); } else { appendCollectionClass(true); } verifiedReviewBadge(); allReviewsCounterBadge(); // if (customArrayData.allowSliderAllPages == true && __st.p != 'product') { // showSliderOnHopePage(); // } if (__st.a == 22292234304 || __st.a == 80304406877 || __st.a == 91505328467) { appendStarOnPdpPage(); checkReviewRestriction(); } if (__st.p == 'product') { appendStarOnPdpPage(); checkReviewRestriction(); updateMetafieldValue(); } if (customArrayData.showAllreViewPageWidget == "1") { if (customArrayData?.allReviewListingPattern?.includes("slider") || __st.a == 71307133193 || __st.a == 73731342622 || __st.a == 67112665398 || __st.a == 67358294318) { showReviewsOnHomePageSlider(); } else { appendAllReviews('25'); let reviewPagination = document.querySelector('.mag-all-review-pagination'); if (reviewPagination) { reviewPagination.addEventListener('change', () => { appendAllReviews(reviewPagination.value); }); } } } if (customArrayData.enableCustomerReviewConfirmaionNotifications == true) { var proHandle = (window.location.href.includes('products')) ? window.location.href.split('products/')[1].split('?')[0] : null; var proHandleValue = ((proHandle != null) && (proHandle.trim() != "")) ? decodeURIComponent(proHandle) : false; var customerEmail = (window.location.href.includes('mag_customer_email=')) ? window.location.href.split('mag_customer_email=')[1].split('&')[0] : null; var customerEmailValue = ((customerEmail != null) && (customerEmail.trim() != "")) ? decodeURIComponent(customerEmail) : false; var reviewConfirmation = (window.location.href.includes('mag_review_confirmation=')) ? window.location.href.split('mag_review_confirmation=')[1].split('&')[0] : null; var reviewId = (window.location.href.includes('mag_review_id=')) ? window.location.href.split('mag_review_id=')[1].split('&')[0] : null; var reviewConfirmationValue = ((reviewConfirmation != null) && (reviewConfirmation.trim() != "")) ? decodeURIComponent(reviewConfirmation) : false; if ((customerEmailValue != false) && (reviewConfirmationValue != false) && (proHandleValue != false) && (reviewId != null) && (reviewId.trim() != "")) { reviewConfirmationEmail(customerEmailValue, reviewConfirmationValue, proHandleValue, reviewId); } } } var reviewConfirmationEmail = (customerEmail, reviewConfirmation, proHandle, reviewId) => { fetch(`${domain}reviewConfirmationEmailSet`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ customerEmail: customerEmail, reviewConfirmation: reviewConfirmation, shopId: shopId, shopName: shopName, proHandle: proHandle, reviewId: reviewId, }), }) .then(res => res.json()) .then(response => { var container = document.createElement('div'); var beforeclass = document.querySelector('.epr-wrapper'); var closingButton = document.createElement('span'); closingButton.innerHTML = "×"; closingButton.addEventListener('click', () => { container.remove(); }); container.setAttribute("class", "mag-review-confirmation"); if (response.status == 'review_confirmation_already') { container.innerHTML = window.myappgurus.form.success_message.success_msg1 ? window.myappgurus.form.success_message.success_msg1 : "Your Review has been already confirmed successfully."; container.style.color = "#664d03"; container.style.backgroundColor = "#fff3cd"; container.style.border = "1px solid #ffecb5"; container.appendChild(closingButton); beforeclass.insertAdjacentElement('afterbegin', container); } if (response.status == 'review_confirmation_success') { container.innerHTML = window.myappgurus.form.success_message.success_msg2 ? window.myappgurus.form.success_message.success_msg2 : "Your Review has been confirmed successfully."; container.style.color = "#155724"; container.style.backgroundColor = "#d4edda"; container.style.border = "1px solid #c3e6cb"; container.appendChild(closingButton); beforeclass.insertAdjacentElement('afterbegin', container); } setTimeout(() => { container.remove(); }, 10000); }); } var verifiedReviewBadge = () => { var verifiedBadge = document.querySelector('#mag-verified-review-badge'); if (verifiedBadge) { let userId = customArrayData.userId; fetch(`${domain}verifiedReviews`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ userId: userId }), }) .then(res => res.json()) .then(response => { if (response > 20) { let html = `

${response}

${window.myappgurus.verifiedReviewsBadge && window.myappgurus.verifiedReviewsBadge.custom_settings && window.myappgurus.verifiedReviewsBadge.custom_settings.Verified_Review_label ? window.myappgurus.verifiedReviewsBadge.custom_settings.Verified_Review_label : window.myappgurus.verifiedReviewsBadge.Verified_Review}

`; verifiedBadge.innerHTML = html; } }); } } var allReviewsCounterBadge = () => { var starcolor = (customArrayData.reviewStarcolor !== undefined && customArrayData.reviewStarcolor !== '') ? customArrayData.reviewStarcolor : 'orange'; var allReviewBadge = document.querySelector('#mag-all-review-counter-badge'); if (allReviewBadge) { let userId = customArrayData.userId; fetch(`${domain}allReviewsBadge`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ userId: userId }), }) .then(res => res.json()) .then(response => { let reviews = ''; if (response.count > 0) { for (index = 0; index < 5; index++) { if (index < Math.floor(response.average) && Math.floor(response.average) != 0) { reviews += star('filled', "orange"); } else if ((response.average - Math.floor(response.average)) > 0 && index < Math.ceil(response.average)) { reviews += star('half-filled', "orange"); } else { reviews += star('not-filled', "orange"); } } let html = `
${response.average.toFixed(1)} ${reviews} ${response.average.toFixed(1)} ${window.myappgurus.allReviewsCounter && window.myappgurus.allReviewsCounter.custom_settings && window.myappgurus.allReviewsCounter.custom_settings.out_of_label ? window.myappgurus.allReviewsCounter.custom_settings.out_of_label : window.myappgurus.allReviewsCounter.out_of} 5.0 ${window.myappgurus.allReviewsCounter && window.myappgurus.allReviewsCounter.custom_settings && window.myappgurus.allReviewsCounter.custom_settings.stars_based_on_label ? window.myappgurus.allReviewsCounter.custom_settings.stars_based_on_label : window.myappgurus.allReviewsCounter.stars_based_on} ${response.count} ${window.myappgurus.allReviewsCounter && window.myappgurus.allReviewsCounter.custom_settings && window.myappgurus.allReviewsCounter.custom_settings.reviews_label ? window.myappgurus.allReviewsCounter.custom_settings.reviews_label : window.myappgurus.allReviewsCounter.reviews}
`; allReviewBadge.innerHTML = html; } }); } } var appendAllReviews = (perPage) => { let allReviews = document.querySelector('.mag-all-reviews'); if (allReviews) { fetch(`${domain}getAllReviews`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ shop: Shopify.shop, perPage: perPage }), }) .then(res => res.json()) .then(response => { if (response) { allReviewsWidget(response, perPage); } }); } }; var showReviewsOnHomePageSlider = () => { fetch(`${domain}getReviewsSlider`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ shopId: shopId, shopName: shopName }), }) .then(res => res.json()) .then(response => { let linkElement = document.createElement('link'), scriptElement = document.createElement('script'); linkElement.rel = 'stylesheet'; linkElement.href = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css'; document.head.appendChild(linkElement); scriptElement.src = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js'; scriptElement.onload = function () { initSwiper(response.getData, 'customstore'); }; document.head.appendChild(scriptElement); }); } var allReviewsWidget = (response, perPage, page = 1) => { var allReviews = ""; if (response) { response.getData.data.forEach((curr, k) => { var review = curr; ratings = review.rating; filledStars = parseInt(ratings); emptyStars = 5 - filledStars; starSvgs = ""; for (var i = 0; i < filledStars; i++) { var fillColors = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : "#FFDF00"; starSvgs += `` } for (var j = 0; j < emptyStars; j++) { starSvgs += ``; } let hiddenTitle = ""; let hiddenDescription = ""; if (customArrayData.restrictPersonalInfo == "1") { hiddenTitle = hideContactInformation(review.title); hiddenDescription = hideContactInformation( review.description ); } else { hiddenTitle = review.title; hiddenDescription = review.description; } allReviews += `
  • ${(review.review_image !== null && review.review_image !== '') ? checkFileType(review.review_image) == 'video' ? `
    ` : `
    ` : '' }
    ${review.name ? `

    ${review.name} ${review.varified === "1" ? `verified.svg` : ``}

    ` : ``}
    ${starSvgs}
  • `; }); } allReviews = `` if (response.getData.next_page_url != null || response.getData.prev_page_url != null) { allReviews += allReviewsPagination(response, perPage, page); } if (document.querySelector('.mag-all-reviews')) { document.querySelector('.mag-all-reviews').innerHTML = allReviews; } allReviewsClickPagination(perPage); showWholeDescription(); } var showWholeDescription = () => { const readMoreDescp = document.querySelectorAll('.readMoreDescp'); if (readMoreDescp) { readMoreDescp.forEach(curr => { curr.addEventListener('click', (event) => { event.preventDefault(); let id = curr.getAttribute('data-id'); let descp = document.querySelector(`.mag-review-description-content[data-id="${id}"]`); curr.classList.toggle('hide'); if (!curr.classList.contains('hide')) { descp.querySelector('p').innerHTML = descp.getAttribute('data-content') + `${window.myappgurus.form ? window.myappgurus.form.read_less : 'Read less'}`; } else { descp.querySelector('p').innerHTML = descp.getAttribute('data-content').substring(0, 200) + `...${window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'}`; } descp.querySelector('a.readMoreDescp').addEventListener('click', (event) => { event.preventDefault(); curr.click(); }); }) }) } } var allReviewsClickPagination = (perPage) => { let paginationButtons = document.querySelectorAll('.relative-inner-all-reviews'); if (paginationButtons) { paginationButtons.forEach(button => { button.addEventListener('click', () => { let pageUrl = button.getAttribute('page_url'); let urlObj = new URL(pageUrl); let params = new URLSearchParams(urlObj.search); let page = params.get('page'); if (pageUrl) { fetch(pageUrl, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}`, }, body: JSON.stringify({ shop: Shopify.shop, perPage: perPage }), }) .then(res => res.json()) .then(response => { document.querySelector('.mag-all-reviews').scrollIntoView({ behavior: 'smooth', block: 'start' }); allReviewsWidget(response, perPage, page); }); } }); }); } }; var allReviewsPagination = (response, perPage, currentPage) => { let html = '', page = (currentPage != null) ? currentPage : 1; totalPages = Math.ceil(response.getData.total / perPage); starcolor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : 'currentColor'; html += ``; return html; } var showWholeReviewDescription = () => { const readMoreDescp = document.querySelectorAll('.readMoreReviewDescp'); readMoreDescp.forEach(curr => { curr.addEventListener('click', (event) => { event.preventDefault(); let id = curr.getAttribute('data-id'); let descp = document.querySelector(`.epr-review-description[data-id="${id}"]`); let fullContent = descp.querySelector('.full-review-content').textContent; let pElement = descp.querySelector('p'); let isExpanded = curr.classList.contains('hide'); if (isExpanded) { pElement.innerHTML = `${fullContent.substring(0, 200)}... ${window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'}`; } else { pElement.innerHTML = `${fullContent} ${window.myappgurus.form ? window.myappgurus.form.read_less : 'Read less'}`; } descp.querySelector('a.readMoreReviewDescp').addEventListener('click', (event) => { event.preventDefault(); curr.click(); }); curr.classList.toggle('hide'); }); }); }; var updateMetafieldValue = () => { var ratingForm = document.querySelector('#mag-product-review'); if (ratingForm) { let productHandle = ratingForm.getAttribute('data-product-handle'); fetch(`${domain}updateMetafieldFun`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ userId: customArrayData.userId, proHandle: productHandle }), }) .then(res => res.json()) .then(response => { }); } } var addCustomisationCss = () => { let linkElement = document.createElement('style'); linkElement.innerHTML = customArrayData.customCss; document.head.appendChild(linkElement); } var getProductHandle = (element) => { let href = element.getAttribute('href'); if (!href || typeof href !== 'string') { return null; } let url = new URL(href, window.location.origin); let productPath = url.pathname; let segments = productPath.split('/'); let productsIndex = segments.indexOf('products'); if (productsIndex !== -1 && segments.length > productsIndex + 1) { return segments[productsIndex + 1]; // Return the handle } return null; } var getIdFromGid = (gid) => { return gid.split('/').pop(); } var appendCollectionClass = async (status) => { let targetClassReview = '', fetchPromises = []; if (window.myappgurus.prm.hide_star == "false") { const existingReviews = document.querySelectorAll('#epr-product-collection-review'); if (existingReviews.length > 0 && status == true) { existingReviews.forEach(curr => { let proId = curr.getAttribute('data-product-id'); let reviewData1 = reviewData.filter(item => item.productId == proId); let star = starStyleCollectionPage( customArrayData.fillStarPatter[0], customArrayData.reviewStarcolor, reviewData1[0], false ); curr.innerHTML = star; }); } else { if ( window.myappgurus && window.myappgurus.prm && window.myappgurus.prm.product_review ) { targetClassReview = window.myappgurus.prm.product_review; } else { targetClassReview = `.card__heading.h5`; } const reviewClass = document.querySelectorAll(`${targetClassReview} a`); reviewClass.forEach(curr => { const proHandle = getProductHandle(curr); let fd = new FormData(); fd.append('shop', Shopify.shop); fd.append('proHandle', proHandle); if (proHandle) { // let fetchPromise = fetch(`${domain}getProId`, { // method: "POST", // headers: { // 'Accept': 'application/json', // 'Authorization': `Bearer ${window.sessionToken}` // }, // body: fd, // }) let fetchPromise = fetch(`/products/${proHandle}.json`) .then(res => res.json()) .then(response => { const productId = response.product.id; const reviewData1 = reviewData.filter(item => item.productId == productId); const star = starStyleCollectionPage( customArrayData.fillStarPatter[0], customArrayData.reviewStarcolor, reviewData1[0], false ); if (!curr.nextElementSibling || !curr.nextElementSibling.matches('#epr-product-collection-review')) { const appendData = document.createElement('div'); appendData.id = 'epr-product-collection-review'; appendData.setAttribute('data-product-id', productId); appendData.setAttribute('data-product-handle', proHandle); appendData.innerHTML = star; curr.insertAdjacentElement('afterend', appendData); } }); fetchPromises.push(fetchPromise); } }); } } await Promise.all(fetchPromises); }; const targetNode = document.body; const config = { childList: true, subtree: true }; let targetClassReviewCount = ''; if (window.myappgurus && window.myappgurus.prm !== null && window.myappgurus.prm !== undefined && window.myappgurus.prm !== '' && window.myappgurus.prm.product_review != '') { targetClassReviewCount = window.myappgurus.prm.product_review; } else { targetClassReviewCount = `.card__heading.h5`; } let previousCount = document.querySelectorAll(targetClassReviewCount).length; const callback = (mutationsList) => { for (const mutation of mutationsList) { if (mutation.type === 'childList') { const currentCount = document.querySelectorAll(targetClassReviewCount).length; if (currentCount > previousCount) { appendCollectionClass(false); previousCount = currentCount; } } } }; const observer = new MutationObserver(callback); observer.observe(targetNode, config); var appendStarOnPdpPage = () => { let targetClass = document.querySelector('#epr-product-title-review'), proId = targetClass?.getAttribute('data-product-id'), reviewDataJson = document.querySelector('.mag-pro-summary')?.textContent, reviewDataJson1 = reviewData.filter(item => { return item.productId == proId }), reviews = ''; if (reviewDataJson != undefined) { reviews = starStyleCollectionPage(customArrayData.fillStarPatter[0], customArrayData.reviewStarcolor, JSON.parse(reviewDataJson), true); } else { reviews = starStyleCollectionPage(customArrayData.fillStarPatter[0], customArrayData.reviewStarcolor, reviewDataJson1[0]), true; } if (targetClass) { targetClass.innerHTML = reviews; } starClick(); } var starClick = () => { document.querySelector('#epr-product-title-review')?.addEventListener('click', function () { document.querySelector('#mag-product-review').scrollIntoView({ behavior: 'smooth', block: 'start' }); }); } var showRatingWiseReviews = () => { let targetClass = document.querySelector('#mag-product-review'), proId = targetClass?.getAttribute('data-product'), proHandle = targetClass?.getAttribute('data-product-handle'), reviewCount = document.querySelectorAll('.mag-review-count'), seeAllReviews = document.querySelector('.see-all-reviews'); if (customArrayData.reviewListingPattern[0] == 'slider') { reviewCount.forEach(curr => { curr.addEventListener('click', () => { seeAllReviews.classList.remove('hide'); let review = curr.getAttribute('data-id'); if (review !== null) { fetch(`${domain}getReviewWiseDataSlider`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, review: review, }), }) .then(res => res.json()) .then(response => { showReviewsOnFrontInSlider(response.getData, 'product') let productReview = document.querySelector('#epr-product-reviews'); if (productReview) { let offsetTop = productReview.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({ top: offsetTop, behavior: 'smooth' }); } }); } }); }) } else { reviewCount.forEach(curr => { curr.addEventListener('click', () => { seeAllReviews.classList.remove('hide'); let review = curr.getAttribute('data-id'); if (review !== null) { fetch(`${domain}getReviewWiseData`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, review: review, }), }) .then(res => res.json()) .then(response => { switch (customArrayData.reviewListingPattern[0]) { case 'list': showReviewsOnFrontInList(response, null, null, review); break; case 'grid': showReviewsOnFrontInGrid(response, null, null, review); break; default: break; } let productReview = document.querySelector('#epr-product-reviews'); if (productReview) { let offsetTop = productReview.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({ top: offsetTop, behavior: 'smooth' }); } }); } }); }) } } var checkOnlyBuyers = (formData, email, proId) => { let fd = new FormData(); fd.append('user_id', customArrayData.userId); fd.append('email', email); fd.append('productId', proId); fetch(`${domain}checkOrders`, { method: "POST", headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: fd, }) .then(res => res.json()) .then(response => { if (response == 1) { submitReviewForm(formData); } else { formData.reset(); document.querySelector('#submit-btn-text').classList.remove('not-click'); document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_btn; document.querySelector('#charCountTitle').innerHTML = '0 / 50'; document.querySelector('#charCount').innerHTML = '0 / 1500'; document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelector('.epr-review-form').classList.add('hide'); document.querySelector('#alert-text').innerHTML = `

    You can't add a review because you haven't bought this product.

    `; document.querySelector('.epr-form-content-wrapp').scrollIntoView({ behavior: 'smooth', block: 'start' }); setTimeout(() => { document.querySelector('#alert-text').innerHTML = ''; }, 10000); } }); } var checkReviewRestriction = () => { let targetClass = document.querySelector('#mag-product-review'), proId = targetClass?.getAttribute('data-product'), writeReviewBtn = ''; switch (customArrayData.reviewRestrictions[0]) { case "no_restrictions": writeReviewBtn = `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.review_btn ? window.myappgurus.form.custom_settings.review_btn : window.myappgurus.prm.form.review_btn}
    `; appendFormOnProductPage(true, 'no_restrictions'); break; case "only_buyers": writeReviewBtn = `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.review_btn ? window.myappgurus.form.custom_settings.review_btn : window.myappgurus.prm.form.review_btn}
    `; appendFormOnProductPage(true, 'only_buyers'); break; case "only_buyers_with_review_request_email": if (window.location.href.includes('mag_customer_email=')) { writeReviewBtn = `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.review_btn ? window.myappgurus.form.custom_settings.review_btn : window.myappgurus.prm.form.review_btn}
    `; appendFormOnProductPage(true, 'only_buyers_with_review_request_email'); } else { appendFormOnProductPage(false, 'only_buyers_with_review_request_email'); } break; default: appendFormOnProductPage(true, ''); break; } } if (customArrayData.showPopUpWidget == true && latestReview) { const popupHtml = `
    ${latestReview.review_image ? `Product` : `
    ${latestReview.name ? latestReview.name.charAt(0).toUpperCase() : ""}
    `}

    ${latestReview.name}

    ${Array(5).fill(0).map((_, index) => ` `).join('')}

    ${latestReview.description}

    `; document.body.insertAdjacentHTML('beforeend', popupHtml); const popupElement = document.querySelector('.mag-product-float-popup'); const updatePopupClass = () => { popupElement.classList.toggle(`${customArrayData.widgetPosition}-shown`); }; const intervalId = setInterval(updatePopupClass, 10000); document.querySelector('.mag-product-close-icon').addEventListener('click', () => { clearInterval(intervalId); popupElement.remove(); }); } var appendFormOnProductPage = (writeReviewBtn, type) => { let targetClass = document.querySelector('#mag-product-review'), proId = targetClass?.getAttribute('data-product'), proHandle = targetClass?.getAttribute('data-product-handle'), protitle = document.querySelector('#epr-product-title-review')?.getAttribute('data-product-title'), starcolor = (customArrayData.reviewStarcolor !== undefined && customArrayData.reviewStarcolor !== '') ? customArrayData.reviewStarcolor : 'currentColor', reviewDataJson = reviewData.filter(item => { return item.productId == proId }); if (customArrayData.allowVideoUploads == true) { var imagelabel = window.myappgurus.prm.form.form_fields.review_image_video; } else { var imagelabel = window.myappgurus.prm.form.form_fields.review_image; } var customerEmail = (window.location.href.includes('mag_customer_email=')) ? window.location.href.split('mag_customer_email=')[1].split('&')[0] : ''; var productRating = (window.location.href.includes('mag_rating=')) ? window.location.href.split('mag_rating=')[1].split('&')[0] : ''; var customerName = (window.location.href.includes('mag_customer_name=')) ? window.location.href.split('mag_customer_name=')[1].split('&')[0] : ''; var reviewTitle = (window.location.href.includes('mag_review_title=')) ? window.location.href.split('mag_review_title=')[1].split('&')[0] : ''; var reviewDescription = (window.location.href.includes('mag_review_description=')) ? window.location.href.split('mag_review_description=')[1].split('&')[0] : ''; var deliveryRating = (window.location.href.includes('mag_delivery_review=')) ? window.location.href.split('mag_delivery_review=')[1].split('&')[0] : ''; var paymentRating = (window.location.href.includes('mag_payment_review=')) ? window.location.href.split('mag_payment_review=')[1].split('&')[0] : ''; var priceRating = (window.location.href.includes('mag_price_review=')) ? window.location.href.split('mag_price_review=')[1].split('&')[0] : ''; var customerEmailValue = customerEmail ? decodeURIComponent(customerEmail) : ''; var ratingValue = productRating ? decodeURIComponent(productRating) : ''; var customerNameValue = customerName ? decodeURIComponent(customerName) : ''; var reviewTitleValue = reviewTitle ? decodeURIComponent(reviewTitle) : ''; var reviewDescriptionValue = reviewDescription ? decodeURIComponent(reviewDescription) : ''; var deliveryRatingValue = deliveryRating ? decodeURIComponent(deliveryRating) : ''; var paymentRatingValue = paymentRating ? decodeURIComponent(paymentRating) : ''; var priceRatingValue = priceRating ? decodeURIComponent(priceRating) : ''; var prefillRatings = { 'rating': ratingValue, 'delivery_review': deliveryRatingValue, 'payment_review': paymentRatingValue, 'price_review': priceRatingValue }; var product_base_url = window.location.href; var product_base_url_split = product_base_url.split('?mag_'); var new_product_base_url = product_base_url_split[0]; var formSubmittedMediaReminder = 'MediaReminder' var formData = `
    ${(type == 'only_buyers_with_review_request_email' || window.location.href.includes('mag_customer_email=') == true) ? `` : ''} ${ratingValue ? `` : ``} ${ratingValue ? `` : ''}
    ${(window.myappgurus.prm.form_elements.name == "false") ? `
    ${customerNameValue ? `` : ``}
    ` : ''}
    ${customerEmailValue ? `` : ``}
    ${(window.myappgurus.prm.form_elements.title == "false") ? `
    ${reviewTitleValue ? `` : ``}
    0 / 50
    ` : ''}
    ${reviewDescriptionValue ? `` : ``}
    0 / 1500
    ${window?.myappgurus?.form?.validation?.rating_required || "Rating is required."}
    ${(customArrayData.requestReview !== undefined) ? (customArrayData.requestReview.includes("delivery")) ? `
    ${window?.myappgurus?.form?.validation?.rating_required || "Rating is required."}
    ` : '' : ''} ${(customArrayData.requestReview !== undefined) ? (customArrayData.requestReview.includes("payment")) ? `
    ${window?.myappgurus?.form?.validation?.rating_required || "Rating is required."}
    ` : '' : ''} ${(customArrayData.requestReview !== undefined) ? (customArrayData.requestReview.includes("price")) ? `
    ${window?.myappgurus?.form?.validation?.rating_required || "Rating is required."}
    ` : '' : ''}
    ${(window.myappgurus.prm.form_elements.image == "false") ? `
    ` : ''}
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.cancel_btn_label ? window.myappgurus.form.custom_settings.cancel_btn_label : window.myappgurus.prm.form.form_fields.cancel_btn}
    ${(__st.a !== 82898092358) ? (customArrayData.removeWaterMark != '1') ? (__st.a == '13326581') ? `
    ` : `
    ` : '' : ''}
    `; fetch(`${domain}fetchData`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, userId: customArrayData.userId, }), }) .then(res => res.json()) .then(response => { if (response != 1) { if (document.querySelector('#epr-product-title-review')) { if (response !== 1) { if (document.querySelector('#epr-product-title-review')?.hasAttribute('data-product-title')) { richSnippet(response, document.querySelector('#epr-product-title-review').getAttribute('data-product-title')); } else { getProTitle().then(proTitle => { richSnippet(response, proTitle); }); } } } let reviews = '', ratings = response.rating, starColor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange'; for (index = 0; index < 5; index++) { if (index < Math.floor(ratings) && Math.floor(ratings) != 0) { reviews += star('filled', starColor); } else if ((ratings - Math.floor(ratings)) > 0 && index < Math.ceil(ratings)) { reviews += star('half-filled', starColor); } else { reviews += star('not-filled', starColor); } } var reviewData = `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.block_heading ? window.myappgurus.form.custom_settings.block_heading : window.myappgurus.prm.form.block_heading}

    ${parseFloat(response.rating).toFixed(1)}/5.0

    ${reviews}

    ${response.count} ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.subtitle2 ? window.myappgurus.form.custom_settings.subtitle2 : window.myappgurus.prm.form.subtitle2}

    ${(writeReviewBtn == true) ? `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.review_btn ? window.myappgurus.form.custom_settings.review_btn : window.myappgurus.prm.form.review_btn}
    ` : ''}

    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.form_heading ? window.myappgurus.form.custom_settings.form_heading : window.myappgurus.prm.form.form_heading}

    ${formData}
    `; } else { var reviewData = (writeReviewBtn == true) ? `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.block_heading ? window.myappgurus.form.custom_settings.block_heading : window.myappgurus.prm.form.block_heading}
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.no_rating ? window.myappgurus.form.custom_settings.no_rating : window.myappgurus.prm.form.no_rating}
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.review_btn ? window.myappgurus.form.custom_settings.review_btn : window.myappgurus.prm.form.review_btn}

    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.form_heading ? window.myappgurus.form.custom_settings.form_heading : window.myappgurus.prm.form.form_heading}

    ${formData}
    ` : ''; } if (document.querySelector(`#mag-product-review[data-product="${proId}"]`)) { document.querySelector(`#mag-product-review[data-product="${proId}"]`).innerHTML = reviewData; } showAllReviews(proId, proHandle); showReview(); reviewValueChange(prefillRatings); formSubmit(); checkLogo(); showRatingWiseReviews(); cancelFormBtn(); countCharacters(); }); } var countCharacters = () => { addEventListener('keyup', () => { var textarea = document.querySelector("textarea[name='description']"); var maxLength = 1500; var charCount = textarea.value.length; var charCountElement = document.querySelector('#charCount'); charCountElement.textContent = charCount + ' / ' + maxLength; if (charCount > maxLength) { textarea.value = textarea.value.slice(0, maxLength); charCountElement.style.color = 'red'; } else { charCountElement.style.color = 'black'; } var textareaTitle = document.querySelector("input[name='title']"); var maxLengthTitle = 50; var charCountTitle = textareaTitle.value.length; var charCountElementTitle = document.querySelector('#charCountTitle'); charCountElementTitle.textContent = charCountTitle + ' / ' + maxLengthTitle; if (charCountTitle > maxLengthTitle) { textareaTitle.value = textareaTitle.value.slice(0, maxLengthTitle); charCountElementTitle.style.color = 'red'; } else { charCountElementTitle.style.color = 'black'; } }); } var cancelFormBtn = () => { let cancelBtn = document.querySelector('#mag-cancel-btn-text'); if (cancelBtn) { cancelBtn.addEventListener('click', () => { document.querySelector('#erpReviewFrom').reset(); document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelectorAll('#erpReviewFrom span').forEach(span => { span.textContent = ''; }); document.querySelector('.epr-review-form').classList.toggle('hide'); document.querySelector('.epr-review').scrollIntoView({ behavior: 'smooth', block: 'start' }); }); } } var formSubmit = () => { let form = document.querySelector('#erpReviewFrom'), fileExtension = []; if (form) { form.addEventListener('submit', (e) => { e.preventDefault(); let proId = document.querySelector('#mag-product-review').getAttribute('data-product'); let name = (document.querySelector('#name')) ? document.querySelector('#name').value : ''; let email = (document.querySelector('#email')) ? document.querySelector('#email').value : ''; let title = (document.querySelector('#title')) ? document.querySelector('#title').value : ''; let description = (document.querySelector('#description')) ? document.querySelector('#description').value : ''; let namePattern = /^[a-zA-Z]*$/; let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z]{3,63}\.[a-zA-Z]{2,3}$/; document.querySelector('.mag-review-required').classList.add('hide'); (document.querySelector('.mag-name-value')) ? document.querySelector('.mag-name-value').innerHTML = '' : ''; (document.querySelector('.mag-email-value')) ? document.querySelector('.mag-email-value').innerHTML = '' : ''; (document.querySelector('.mag-title-value')) ? document.querySelector('.mag-title-value').innerHTML = '' : ''; (document.querySelector('.mag-description-value')) ? document.querySelector('.mag-description-value').innerHTML = '' : ''; (document.querySelector('.required-review-image')) ? document.querySelector('.required-review-image').innerHTML = '' : ''; if (customArrayData.allowVideoUploads == "1") { fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'svg', 'mp4', 'mov', 'webm', 'mkv']; } else { fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'svg']; } if (document.querySelector('[name="rating"]').value == '') { document.querySelector('.mag-review-required').classList.remove('hide'); } else if (document.querySelector('#review_image') && (document.querySelector('#review_image').value != '') && fileExtension.includes(document.querySelector('#review_image').value.split('.').pop().toLowerCase()) == false) { document.querySelector('.mag-review-required').classList.add('hide'); document.querySelector('.required-review-image').innerHTML = window.myappgurus.prm.form.validation_message.file_type; } else if (document.querySelector('#review_image')?.files[0]?.size > 2000000) { document.querySelector('.mag-review-required').classList.add('hide'); document.querySelector('.required-review-image').innerHTML = window.myappgurus.prm.form.validation_message.file_size; } else if (!name && name.trim() == "" && window.myappgurus.prm.form_elements.name == "false") { document.querySelector('.mag-name-value').innerHTML = "Name field is required."; document.querySelector('#name').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (name && name.length > 50) { document.querySelector('.mag-name-value').innerHTML = "Name field exceeds character limit."; document.querySelector('#name').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (!email && email.trim() == "") { document.querySelector('.mag-email-value').innerHTML = "Email field is required."; document.querySelector('#email').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (email && email.length > 320) { let email = document.querySelector('#email').value.split('@'); email[0].length > 64 ? document.querySelector('.mag-email-value').innerHTML = "Email field exceeds character limit." : document.querySelector('.mag-email-value').innerHTML = ""; email[1].length > 255 ? document.querySelector('.mag-email-value').innerHTML = "Email field exceeds character limit." : document.querySelector('.mag-email-value').innerHTML = ""; document.querySelector('#email').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (title && title.trim() == '') { document.querySelector('.mag-title-value').innerHTML = "Title field is required."; document.querySelector('#title').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (title && title.length > 150) { document.querySelector('.mag-title-value').innerHTML = "Title field exceeds character limit."; document.querySelector('#title').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (!description && description.trim() == "") { document.querySelector('.mag-description-value').innerHTML = "Description field is required."; document.querySelector('#description').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else if (description && description.length >= 1500) { document.querySelector('.mag-description-value').innerHTML = "Description field exceeds character limit."; document.querySelector('#description').scrollIntoView({ behavior: 'smooth', block: 'start' }); } else { (document.querySelector('#submit-btn-text')) ? document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_button_clicked : ''; if (form.getAttribute('data-id') == 'only_buyers') { checkOnlyBuyers(form, email, proId); } else { submitReviewForm(form); } } }); } } var checkEmailDomain = (emailInput, submitButton) => { const emailValue = emailInput.value.trim(); const emailDomain = emailValue.split("@")[1] || ""; const restrictedDomains = customArrayData?.restrictedEmailDomains || [] const restrictedDomainMessage = "Email domain is not allowed"; const emailValueSpan = document.querySelector('.mag-email-value'); if (!emailValueSpan) { return false; } emailInput.addEventListener('input', () => { emailValueSpan.textContent = ''; submitButton.removeAttribute("disabled"); submitButton.classList.remove('not-click'); }); if (restrictedDomains.includes(emailDomain)) { emailValueSpan.textContent = restrictedDomainMessage; emailValueSpan.style.color = "red"; submitButton.setAttribute("disabled", "disabled"); return false; } else { emailValueSpan.textContent = ''; submitButton.removeAttribute("disabled"); return true; } }; var submitReviewForm = (formData) => { document.querySelector('.mag-review-required').classList.add('hide'); (document.querySelector('.mag-name-value')) ? document.querySelector('.mag-name-value').innerHTML = '' : ''; (document.querySelector('.mag-email-value')) ? document.querySelector('.mag-email-value').innerHTML = '' : ''; (document.querySelector('.mag-title-value')) ? document.querySelector('.mag-title-value').innerHTML = '' : ''; (document.querySelector('.mag-description-value')) ? document.querySelector('.mag-description-value').innerHTML = '' : ''; document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(element => { element.classList.remove('filled'); }); (document.querySelector('.required-review-image')) ? document.querySelector('.required-review-image').innerHTML = '' : ''; document.querySelector('#submit-btn-text').classList.add('not-click'); let fd = new FormData(formData); const emailInput = document.getElementById("email"); const submitButton = document.getElementById("submit-btn-text"); if (!checkEmailDomain(emailInput, submitButton)) { return; } fetch(`${domain}erpReviewFrom`, { method: "POST", headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: fd, }) .then(res => res.json()) .then(response => { if (response.status == 'review_exists') { formData.reset(); document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelector('#submit-btn-text').classList.remove('not-click'); document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_btn; document.querySelector('#charCountTitle').innerHTML = '0 / 50'; document.querySelector('#charCount').innerHTML = '0 / 1500'; document.querySelector('.epr-review-form').classList.add('hide'); document.querySelector('#alert-text').innerHTML = `

    ${window.myappgurus.form.success_message.success_msg3 ? window.myappgurus.form.success_message.success_msg3 : "Your existing review has been updated successfully."}

    `; document.querySelector('.epr-form-content-wrapp').scrollIntoView({ behavior: 'smooth', block: 'start' }); setTimeout(() => { document.querySelector('#alert-text').innerHTML = ''; }, 3000); } else if (response.status == 'approval_status') { formData.reset(); document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelector('#submit-btn-text').classList.remove('not-click'); document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_btn; document.querySelector('#charCountTitle').innerHTML = '0 / 50'; document.querySelector('#charCount').innerHTML = '0 / 1500'; document.querySelector('.epr-review-form').classList.add('hide'); document.querySelector('#alert-text').innerHTML = `

    ${window.myappgurus.form.success_message.success_msg4 ? window.myappgurus.form.success_message.success_msg4 : "Your review have been submitted."}

    `; document.querySelector('.epr-form-content-wrapp').scrollIntoView({ behavior: 'smooth', block: 'start' }); setTimeout(() => { document.querySelector('#alert-text').innerHTML = ''; }, 3000); } else if (response.status == 'success') { formData.reset(); document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelector('#submit-btn-text').classList.remove('not-click'); document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_btn; document.querySelector('#charCountTitle').innerHTML = '0 / 50'; document.querySelector('#charCount').innerHTML = '0 / 1500'; document.querySelector('.epr-review-form').classList.add('hide'); document.querySelector('#alert-text').innerHTML = `

    ${window.myappgurus.prm.form.form_fields.success_message}

    `; document.querySelector('.epr-form-content-wrapp').scrollIntoView({ behavior: 'smooth', block: 'start' }); setTimeout(() => { document.querySelector('#alert-text').innerHTML = ''; }, 3000); } else if (response.status == 'media_added_successfully') { formData.reset(); document.querySelector('[name="rating"]').value = ''; if (document.querySelector('[name="payment_review"]')) { document.querySelector('[name="payment_review"]').value = ''; } if (document.querySelector('[name="price_review"]')) { document.querySelector('[name="price_review"]').value = ''; } if (document.querySelector('[name="delivery_review"]')) { document.querySelector('[name="delivery_review"]').value = ''; } document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelectorAll('.bi-star-fill.mag-ratings').forEach(curr => { curr.setAttribute('fill', 'none'); }); document.querySelector('#submit-btn-text').classList.remove('not-click'); document.querySelector('#submit-btn-text').innerHTML = window.myappgurus.prm.form.form_fields.submit_btn; document.querySelector('#charCountTitle').innerHTML = '0 / 50'; document.querySelector('#charCount').innerHTML = '0 / 1500'; document.querySelector('.epr-review-form').classList.add('hide'); document.querySelector('#alert-text').innerHTML = `

    ${window.myappgurus.form.success_message.success_msg3 ? window.myappgurus.form.success_message.success_msg3 : "Your existing review has been updated successfully."}

    `; document.querySelector('.epr-form-content-wrapp').scrollIntoView({ behavior: 'smooth', block: 'start' }); setTimeout(() => { document.querySelector('#alert-text').innerHTML = ''; }, 3000); } }); } var reviewValueChange = (prefillRatings) => { var prefillRatingStars = (category, rating) => { if (rating) { let stars = document.querySelectorAll(`.bi-star-fill.mag-ratings[data-rating='${category}']`); let starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange'; stars.forEach((star, index) => { if (index < parseInt(rating)) { star.classList.add('prefilled'); star.setAttribute('fill', starcolor); star.setAttribute('stroke', starcolor); } else { star.classList.add('prefilled'); star.setAttribute('fill', 'none'); star.setAttribute('stroke', starcolor); } }); document.getElementById(category).value = rating; } } if (prefillRatings) { for (let key in prefillRatings) { if (prefillRatings.hasOwnProperty(key)) { prefillRatingStars(key, prefillRatings[key]); } } } let reviews = document.querySelectorAll('.bi-star-fill.mag-ratings'); if (reviews) { reviews.forEach(curr => { curr.addEventListener('click', () => { if (!curr.classList.contains('prefilled')) { let val = curr.getAttribute('star-data'), reviewType = curr.getAttribute('data-rating'), starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange', reviewRating = document.querySelectorAll(`.mag-ratings[data-rating="${reviewType}"]`); reviewRating.forEach((curr, index) => { if (index < parseInt(val)) { curr.classList.add('filled'); curr.setAttribute('fill', starcolor); curr.setAttribute('stroke', starcolor); } else { curr.classList.remove('filled'); curr.setAttribute('fill', 'none'); curr.setAttribute('stroke', starcolor); } }); document.querySelector(`[name="${reviewType}"]`).value = val; document.querySelector('.mag-review-required').classList.add('hide'); } }); curr.addEventListener('mouseover', () => { if (!curr.classList.contains('prefilled')) { let val = curr.getAttribute('star-data'), reviewType = curr.getAttribute('data-rating'), starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange', reviewRating = document.querySelectorAll(`.mag-ratings[data-rating="${reviewType}"]`); reviewRating.forEach((curr, index) => { if (index < parseInt(val)) { curr.classList.add('hovered'); curr.setAttribute('fill', starcolor); curr.setAttribute('stroke', starcolor); } }); } }); curr.addEventListener('mouseout', () => { if (!curr.classList.contains('prefilled')) { if (curr.classList.contains('hovered')) { reviewType = curr.getAttribute('data-rating'), starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange', reviewRating = document.querySelectorAll(`.mag-ratings[data-rating="${reviewType}"]`); reviewRating.forEach((curr) => { if (!curr.classList.contains('filled')) { curr.classList.remove('hovered'); curr.setAttribute('fill', 'none'); curr.setAttribute('stroke', starcolor); } }); } } }); }); } }; var showReview = () => { let reviewBtn = document.querySelectorAll('.epr-collaps-btn'); if (reviewBtn) { reviewBtn.forEach(curr => { curr.addEventListener('click', () => { checkLogo(); document.querySelector('.epr-review-form').classList.toggle('hide'); }); }); } } var showAllReviews = (proId, proHandle) => { if (customArrayData.reviewListingPattern[0] != 'slider') { fetch(`${domain}getAllReviewToshow`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, sortingTypeValue: customArrayData.reviewListSorting, }), }) .then(res => res.json()) .then(response => { switch (customArrayData.reviewListingPattern[0]) { case 'list': showReviewsOnFrontInList(response, customArrayData.reviewListSorting, null, null); break; case 'grid': showReviewsOnFrontInGrid(response, customArrayData.reviewListSorting, null, null); break; default: break; } }); } else { fetch(`${domain}getAllReviewSlider`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName }), }) .then(res => res.json()) .then(response => { showReviewsOnFrontInSlider(response.getData, 'product'); }); } } function hideContactInformation(text) { if (text !== null) { var pattern = /(\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b)|(\b\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}\b)/g; var hiddenText = text.replace(pattern, function (match) { var length = match.length; return "*".repeat(length); }); } return hiddenText; } var showReviewsOnFrontInList = (response, sortingTypeValue, url, review) => { if (response.getData.data == undefined) { var responseData = response.getData; } else { var responseData = response.getData.data; } let targetClass = document.querySelector('#mag-product-review'); let proId = targetClass?.getAttribute('data-product'); let proHandle = targetClass?.getAttribute('data-product-handle'); let starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange'; let html = `${(responseData.length > 0) ? `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.sortbtn ? window.myappgurus.form.custom_settings.sortbtn : window.myappgurus.prm.form.form_fields.sortbtn}
    ` : ''}
    `, reviewPaginationFun = reviewPagination(response, url); for (i = 0; i < responseData.length; i++) { let starRating = '', starColor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : 'orange', reviewVerifiedFun = reviewVerified(responseData[i]), reviewFooterFun = reviewFooter(responseData[i]); date = formatDateAndRelativeTime(responseData[i].created_at); let hiddenTitle = ""; let hiddenDescription = ""; if (customArrayData.restrictPersonalInfo == "1") { hiddenTitle = hideContactInformation(responseData[i].title || ''); hiddenDescription = hideContactInformation( responseData[i].description || '' ); } else { hiddenTitle = responseData[i].title || ''; hiddenDescription = responseData[i].description || ''; } for (index = 0; index < 5; index++) { if (index < Math.floor(responseData[i].rating) && Math.floor(responseData[i].rating) != 0) { starRating += star('filled', starColor); } else if ((responseData[i].rating - Math.floor(responseData[i].rating)) > 0 && index < Math.ceil(responseData[i].rating)) { starRating += star('half-filled', starColor); } else { starRating += star('not-filled', starColor); } } html += `
    ${(responseData[i].review_image !== null && responseData[i].review_image.trim() !== "") ? checkFileType(getFirstImage(responseData[i].review_image)) == 'video' ? `` : `` : `
    ${(responseData[i].name?.trim() != '' && responseData[i].name?.trim() != undefined) ? responseData[i].name?.trim().slice(0, 1) : 'N'}
    ` }
    ${(responseData[i].name) !== null ? responseData[i].name : ''}${reviewVerifiedFun} ${starRating}
    ${customArrayData.reviewDate !== undefined ? customArrayData.reviewDate == '1' ? `${date.formattedDate}` : '' : ''}
    ${(responseData[i].title !== null) ? hiddenTitle : ''} ${responseData[i].description !== null ? `

    ${hiddenDescription.length > 200 ? `${hiddenDescription.substring(0, 200)}... ${window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'}

    ` : `

    ${hiddenDescription}

    `}
    ` : ``}
    ${(responseData[i].review_status == 'published' || responseData[i].review_status == 1 || responseData[i].review_status == 'all') ? (responseData[i].replay !== null && responseData[i].replay?.trim() != '') ? `

    ${(responseData[i].replay?.length > 200) ? `${responseData[i].replay.substring(0, 200)}...` : responseData[i].replay}

    ${(responseData[i].replay?.length > 200) ? `` : ''}
    ` : '' : ''} ${reviewFooterFun}
    `; } html += "
    "; if (response.getData.next_page_url != null || response.getData.prev_page_url != null) { html += reviewPaginationFun; } if (document.querySelector('#epr-product-reviews')) { document.querySelector('#epr-product-reviews').innerHTML = html; } if (document.querySelector('.see-all-reviews') && !document.querySelector('.see-all-reviews').classList.contains('hide')) { document.querySelector('.see-all-reviews').addEventListener('click', function handleClick() { document.querySelector('.see-all-reviews').classList.add('hide'); showAllReviews(proId, proHandle); document.querySelector('#epr-product-reviews').scrollIntoView({ behavior: 'smooth', block: 'start' }); document.querySelector('.see-all-reviews').removeEventListener('click', handleClick); }); } showSocialMedia(); showWholeReply(); clickPagination('list', sortingTypeValue, review); sortingReviews(); showWholeReviewDescription(); } var showWholeReply = () => { let readMoreBtn = document.querySelectorAll('.readMore'); if (readMoreBtn) { readMoreBtn.forEach(curr => { curr.addEventListener('click', () => { let id = curr.getAttribute('data-id'), reviewReply = document.querySelector(`.mag-comment-content[data-id="${id}"]`); document.querySelector(`.readMore[data-id="${id}"]`).classList.toggle('hide'); if (!curr.classList.contains('hide')) { reviewReply.querySelector('p').innerHTML = reviewReply.getAttribute('data-content'); document.querySelector(`.readMore[data-id="${id}"]`).innerHTML = window.myappgurus.form ? window.myappgurus.form.read_less : 'Read less'; } else { reviewReply.querySelector('p').innerHTML = reviewReply.getAttribute('data-content').substring(0, 200) + '...'; document.querySelector(`.readMore[data-id="${id}"]`).innerHTML = window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'; } }); }); } } var showReviewsOnFrontInGrid = (response, sortingTypeValue, url, review) => { if (response.getData.data == undefined) { var responseData = response.getData; } else { var responseData = response.getData.data; } let targetClass = document.querySelector('#mag-product-review'); let proId = targetClass?.getAttribute('data-product'); let proHandle = targetClass?.getAttribute('data-product-handle'); let starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange'; let html = `${(responseData.length > 0) ? `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.sortbtn ? window.myappgurus.form.custom_settings.sortbtn : window.myappgurus.prm.form.form_fields.sortbtn}
    ` : ''}
    `, reviewPaginationFun = reviewPagination(response, url); for (i = 0; i < responseData.length; i++) { let starRating = '', starColor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : 'orange', reviewVerifiedFun = reviewVerified(responseData[i]), reviewFooterFun = reviewFooter(responseData[i]); date = formatDateAndRelativeTime(responseData[i].created_at); let hiddenTitle = ""; let hiddenDescription = ""; if (customArrayData.restrictPersonalInfo == "1") { hiddenTitle = hideContactInformation(responseData[i].title); hiddenDescription = hideContactInformation( responseData[i].description ); } else { hiddenTitle = responseData[i].title; hiddenDescription = responseData[i].description; } for (index = 0; index < 5; index++) { if (index < Math.floor(responseData[i].rating) && Math.floor(responseData[i].rating) != 0) { starRating += star('filled', starColor); } else if ((responseData[i].rating - Math.floor(responseData[i].rating)) > 0 && index < Math.ceil(responseData[i].rating)) { starRating += star('half-filled', starColor); } else { starRating += star('not-filled', starColor); } } html += `
    ${(responseData[i].review_image !== null && responseData[i].review_image.trim() !== "") ? checkFileType(getFirstImage(responseData[i].review_image)) == 'video' ? `` : `` : `
    ${(responseData[i].name?.trim() != '' && responseData[i].name?.trim() != undefined) ? responseData[i].name?.trim().slice(0, 1) : 'N'}
    ` }
    ${(responseData[i].name) !== null ? responseData[i].name : ''}${reviewVerifiedFun} ${starRating} ${customArrayData.reviewDate !== undefined ? customArrayData.reviewDate == '1' ? `${date.formattedDate}` : '' : ''}
    ${(responseData[i].title !== null) ? hiddenTitle : ''} ${responseData[i].description !== null ? `

    ${hiddenDescription.length > 200 ? `${hiddenDescription.substring(0, 200)}... ${window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'}

    ` : `

    ${hiddenDescription}

    `}
    ` : ``}
    ${(responseData[i].review_status == 'published' || responseData[i].review_status == 1 || responseData[i].review_status == 'all') ? (responseData[i].replay !== null && responseData[i].replay?.trim() != '') ? `

    ${(responseData[i].replay?.length > 200) ? `${responseData[i].replay.substring(0, 200)}...` : responseData[i].replay}

    ${(responseData[i].replay?.length > 200) ? `` : ''}
    ` : '' : ''}
    `; } html += "
    "; if (response.getData.next_page_url != null || response.getData.prev_page_url != null) { html += reviewPaginationFun; } if (document.querySelector('#epr-product-reviews')) { document.querySelector('#epr-product-reviews').innerHTML = html; } if (document.querySelector('.see-all-reviews')) { if (!document.querySelector('.see-all-reviews').classList.contains('hide')) { document.querySelector('.see-all-reviews').addEventListener('click', function handleClick() { document.documentElement.style.setProperty('--star-color', starcolor); document.querySelector('.see-all-reviews').classList.add('hide'); showAllReviews(proId, proHandle); document.querySelector('#epr-product-reviews').scrollIntoView({ behavior: 'smooth', block: 'start' }); document.querySelector('.see-all-reviews').removeEventListener('click', handleClick); }); } } showSocialMedia(); showWholeReply(); clickPagination('grid', sortingTypeValue, review); sortingReviews(); showWholeReviewDescription(); } var clickPagination = (type, sortingTypeValue, review) => { let pagination = document.querySelectorAll('.relative-inner') proId = document.querySelector('#mag-product-review')?.getAttribute('data-product'), proHandle = document.querySelector('#mag-product-review')?.getAttribute('data-product-handle'); if (pagination) { pagination.forEach(curr => { curr.addEventListener('click', () => { let url = curr.getAttribute('page_url'); if (url != null) { fetch(url, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, sortingTypeValue: sortingTypeValue, review: review, }), }) .then(res => res.json()) .then(response => { document.querySelector('#epr-product-reviews').scrollIntoView({ behavior: 'smooth', block: 'start' }); switch (type) { case 'list': showReviewsOnFrontInList(response, sortingTypeValue, url, review); break; case 'grid': showReviewsOnFrontInGrid(response, sortingTypeValue, url, review); break; default: break; } }) } }); }) } } var showReviewsOnFrontInSlider = (response, page) => { let targetClass = document.querySelector('#mag-product-review'); let proId = targetClass?.getAttribute('data-product'); let proHandle = targetClass?.getAttribute('data-product-handle'); let linkElement = document.createElement('link'), scriptElement = document.createElement('script'); linkElement.rel = 'stylesheet'; linkElement.href = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css'; document.head.appendChild(linkElement); scriptElement.src = 'https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js'; scriptElement.onload = function () { initSwiper(response, page); }; document.head.appendChild(scriptElement); } var initSwiper = (response, page) => { let starcolor = (customArrayData.reviewStarcolor !== null && customArrayData.reviewStarcolor !== undefined) ? customArrayData.reviewStarcolor : 'orange'; let html = `${page == 'product' ? (response.length > 0) ? `
    ${window.myappgurus.form && window.myappgurus.form.custom_settings && window.myappgurus.form.custom_settings.sortbtn ? window.myappgurus.form.custom_settings.sortbtn : window.myappgurus.prm.form.form_fields.sortbtn}
    ` : '' : ''}
    `; for (i = 0; i < response.length; i++) { let starRating = '', starColor = (customArrayData.reviewStarcolor) ? customArrayData.reviewStarcolor : "currentColor", reviewVerifiedFun = reviewVerified(response[i]), date = formatDateAndRelativeTime(response[i].created_at); imgdata = `${(response[i].review_image !== null && response[i].review_image.trim() !== "") ? checkFileType(getFirstImage(response[i].review_image)) == 'video' ? `` : `` : `
    ${(response[i].name?.trim() != '' && response[i].name?.trim() != undefined) ? response[i].name?.trim().slice(0, 1) : 'N'}
    ` }`; let hiddenTitle = ""; let hiddenDescription = ""; if (customArrayData.restrictPersonalInfo == "1") { hiddenTitle = hideContactInformation(response[i].title); hiddenDescription = hideContactInformation( response[i].description ); } else { hiddenTitle = response[i].title; hiddenDescription = response[i].description; } for (index = 0; index < 5; index++) { if (index < Math.floor(response[i].rating) && Math.floor(response[i].rating) != 0) { starRating += star('filled', starColor); } else if ((response[i].rating - Math.floor(response[i].rating)) > 0 && index < Math.ceil(response[i].rating)) { starRating += star('half-filled', starColor); } else { starRating += star('not-filled', starColor); } } html += `
    ${imgdata}
    ${customArrayData.reviewDate !== undefined ? customArrayData.reviewDate == '1' ? `${date.formattedDate}` : '' : ''}
    ${(response[i].title !== null) ? hiddenTitle : ''} ${response[i].description !== null ? `

    ${hiddenDescription.length > 200 ? `${hiddenDescription.substring(0, 200)}... ${window.myappgurus.form ? window.myappgurus.form.read_more : 'Read more'}

    ` : `

    ${hiddenDescription}

    `}
    ` : ``}
    `; } html += `
    ${response.length > 0 ? `
    ` : ''}
    `; if (page == 'all') { if (response.length != 0) { let swiperSlider = `
    ${window.myappgurus.prm.review_slider.label}

    ${html} ${(__st.a !== 82898092358) ? (customArrayData.removeWaterMark != "1") ? `` : '' : ''}`; let swiperSliderEle = appendElementInHtml(swiperSlider); document.querySelector('main').insertAdjacentElement('beforeend', swiperSliderEle); } } else if (page == 'product') { if (document.querySelector('#epr-product-reviews')) { document.querySelector('#epr-product-reviews').innerHTML = html; } sortingReviews(); } else if (page == 'customstore') { if (document.querySelector('.mag-all-reviews')) { document.querySelector('.mag-all-reviews').innerHTML = html; } } if (__st.a == '80656499020') { document.querySelector('.mag-logo-image').style.display = 'none'; } var swiper = new Swiper(".mySwiper", { slidesPerView: 1, spaceBetween: 10, autoplay: { delay: window.myappgurus.prm.slider_duration * 1000, disableOnInteraction: false, }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, breakpoints: { 640: { slidesPerView: 1, }, 768: { slidesPerView: 3, }, 1024: { slidesPerView: 3, }, }, }); if (document.querySelector('.see-all-reviews') && !document.querySelector('.see-all-reviews').classList.contains('hide')) { document.querySelector('.see-all-reviews').addEventListener('click', function handleClick() { document.querySelector('.see-all-reviews').classList.add('hide'); showAllReviews(proId, proHandle); document.querySelector('#epr-product-reviews').scrollIntoView({ behavior: 'smooth', block: 'start' }); document.querySelector('.see-all-reviews').removeEventListener('click', handleClick); }); } showWholeReviewDescription(); } var showSocialMedia = () => { let shareReview = document.querySelectorAll('[data-toggle="collapse"]'); if (shareReview) { shareReview.forEach(curr => { curr.addEventListener('click', () => { let id = curr.getAttribute('data-id'); document.querySelector(`#collapseExample_${id}`).classList.toggle('hide') }); }); } } var sortingReviews = () => { let sortingType = document.querySelector('.mag-select-menu'), targetClass = document.querySelector('#mag-product-review'), sortingTypeOptions = document.querySelectorAll('.mag-select-menu .options .option'), proId = targetClass?.getAttribute('data-product'), proHandle = targetClass?.getAttribute('data-product-handle'); if (sortingType) { sortingType.addEventListener('click', () => { sortingType.classList.toggle('active'); sortingType.querySelector('ul.options').removeAttribute('style'); }); } if (sortingTypeOptions) { sortingTypeOptions.forEach(curr => { curr.addEventListener('click', () => { let sortingTypeValue = curr.getAttribute('data-id'); if (customArrayData.reviewListingPattern[0] == 'slider') { fetch(`${domain}getSortingReviewDataSlider`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, sortingTypeValue: sortingTypeValue, }), }) .then(res => res.json()) .then(response => { showReviewsOnFrontInSlider(response.getData, 'product'); }); } else { fetch(`${domain}getSortingReviewData`, { method: "POST", headers: { 'Accept': 'application/json', 'Content-type': 'application/json', 'Authorization': `Bearer ${window.sessionToken}` }, body: JSON.stringify({ proId: proId, proHandle: proHandle, shopId: shopId, shopName: shopName, sortingTypeValue: sortingTypeValue, }), }) .then(res => res.json()) .then(response => { switch (customArrayData.reviewListingPattern[0]) { case 'list': showReviewsOnFrontInList(response, sortingTypeValue, null, null); break; case 'grid': showReviewsOnFrontInGrid(response, sortingTypeValue, null, null); break; default: break; } }); } }); }); } } authenticate(); });