`;
contentContainer.appendChild(contentHeader);
contentContainer.appendChild(contentTitle);
contentContainer.appendChild(numberContainer);
d.appendChild(contentContainer);
f.insertBefore(d, f.childNodes[3]);
$splmn_jQuery("#wa-optin-widget-thankyou-confirm-btn").on(
"click",
function () {
var phone = $splmn_jQuery("#wa-optin-widget-thankyou-phone").val();
const countryCode = $splmn_jQuery(
"#wa-optin-widget-thankyou-countryCode"
).val();
if (!phone || phone.replace(/ /g, "").length < 6) {
alert("Please enter a valid phone number");
return;
}
if (!countryCode) {
alert("Please enter a valid country code");
return;
}
if (phone && countryCode && Shopify.checkout.order_id) {
customOptinFromThankYouPage([phone, countryCode], widgetLanguage);
}
}
);
if (Shopify.checkout && Shopify.checkout.phone) {
$splmn_jQuery("#wa-optin-widget-thankyou-phone").val(
Shopify.checkout.phone
);
} else {
getCountryCodeFromCheckout(function (cc) {
var phone = getPhoneFromShipping(cc);
$splmn_jQuery("#wa-optin-widget-thankyou-countryCode").val(
"+" + phone
);
});
}
}
}
}
function getOrderUpdatesOnText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "WhatsApp notifications";
case "PORTUGUESE":
return "Notificações do WhatsApp";
case "SPANISH":
return "Notificaciones de WhatsApp";
case "ITALIAN":
return "Notifiche di WhatsApp";
case "FRENCH":
return "Notifications WhatsApp";
case "INDONESIAN":
return "Pemberitahuan WhatsApp";
case "GERMAN":
return "WhatsApp-Benachrichtigungen";
case "ARABIC":
return "إشعارات WhatsApp";
case "TURKISH":
return "WhatsApp bildirimleri";
case "HEBREW":
return "התראות WhatsApp";
case "DUTCH":
return "WhatsApp-meldingen";
}
}
function getThankyouPageOptinText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Receive order and delivery updates via WhatsApp.";
case "PORTUGUESE":
return "Receba atualizações de pedidos e entregas via WhatsApp.";
case "SPANISH":
return "Reciba actualizaciones de pedidos y entregas a través de WhatsApp.";
case "ITALIAN":
return "Ricevi aggiornamenti su ordini e consegne tramite WhatsApp.";
case "FRENCH":
return "Recevez les mises à jour de commande et de livraison via WhatsApp.";
case "INDONESIAN":
return "Terima informasi rincian pesanan dan informasi pengiriman di Whatsapp.";
case "GERMAN":
return "Du erhältst Bestell- und Lieferaktualisierungen";
case "ARABIC":
return "تلقي تحديثات الطلب والتسليم عبر WhatsApp.";
case "TURKISH":
return "Sipariş ve gönderim güncellemelerini WhatsApp üzerinden al.";
case "HEBREW":
return "קבלו הזמנות ועדכוני משלוח דרך הוואטסאפ";
case "DUTCH":
return "Ontvang order- en leveringsupdates op Whatsapp";
}
}
function getConfirmBtnText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "CONFIRM";
case "PORTUGUESE":
return "CONFIRME";
case "SPANISH":
return "CONFIRMAR";
case "ITALIAN":
return "CONFERMARE";
case "FRENCH":
return "CONFIRMER";
case "INDONESIAN":
return "KONFIRMASI";
case "GERMAN":
return "BESTÄTIGEN";
case "ARABIC":
return "إرسال";
case "TURKISH":
return "ONAYLAMAK";
case "HEBREW":
return "אישור";
case "DUTCH":
return "BEVESTIGEN";
}
}
function getOptInButtonText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Opt-in";
case "PORTUGUESE":
return "Opt-in";
case "SPANISH":
return "Optar en";
case "ITALIAN":
return "Opt-in";
case "FRENCH":
return "Opt-in";
case "INDONESIAN":
return "Opt-in";
case "GERMAN":
return "Opt-in";
case "ARABIC":
return "إرسال";
case "TURKISH":
return "Opt-in";
case "HEBREW":
return "Opt-in";
case "DUTCH":
return "Opt-in";
default:
return "Opt-in";
}
}
function getCountryCodeFromCheckout(success) {
if (
Shopify.checkout &&
Shopify.checkout.shipping_address &&
Shopify.checkout.shipping_address.country_code
) {
$splmn_jQuery.getJSON(
"https://cdn.shopify.com/s/files/1/0070/3666/5911/files/iso_code.json?1203",
function (data) {
success(data[Shopify.checkout.shipping_address.country_code] || "");
}
);
}
return "";
}
function getPhoneFromShipping(countryCode) {
var rawPhone = "";
if (
Shopify.checkout &&
Shopify.checkout.shipping_address &&
Shopify.checkout.shipping_address.phone
) {
rawPhone = Shopify.checkout.shipping_address.phone;
switch (countryCode) {
case "91":
if (rawPhone.startsWith(countryCode) && rawPhone.length == 12) {
return rawPhone;
} else if (rawPhone.startsWith(countryCode) && rawPhone.length < 12) {
return countryCode + rawPhone;
} else if (!rawPhone.startsWith(countryCode)) {
return countryCode + rawPhone;
}
default:
if (!rawPhone.startsWith(countryCode)) {
return countryCode + rawPhone;
} else {
return rawPhone;
}
}
}
return countryCode;
}
function loadOptinWidgetOnCheckout(settings, originalViewportSize) {
var secondClick = false;
document.body.addEventListener(
"click",
function (e) {
const checkout_btn = getTargetButtonFromEvent(e.target);
const checkout_ahref = getTargetAhrefFromEvent(e.target);
const closest_form =
checkout_btn && checkout_btn.getAttribute("type") == "submit"
? $splmn_jQuery(checkout_btn).closest("form")
: null;
if (
(checkout_btn &&
(checkout_btn.getAttribute("name") == "checkout" ||
checkout_btn.getAttribute("onclick") ==
"window.location='/checkout'")) ||
(e.target &&
e.target.name == "checkout" &&
e.target.tagName == "INPUT") ||
(checkout_ahref &&
checkout_ahref.getAttribute("href") == "/checkout") ||
(closest_form && closest_form.attr("action") == "/checkout")
) {
if (!secondClick) {
e.stopPropagation();
e.preventDefault();
loadOptinWidget(settings, originalViewportSize, function () {
secondClick = true;
e.target.click();
});
} else {
secondClick = false;
}
}
},
true
);
}
function getTargetButtonFromEvent(target) {
if (!target) {
return null;
} else if (target.tagName == "BUTTON") {
return target;
} else if ($splmn_jQuery(target).closest("button")) {
return $splmn_jQuery(target).closest("button")[0];
} else {
return null;
}
}
function getTargetAhrefFromEvent(target) {
if (!target) {
return null;
} else if (target.tagName == "A") {
return target;
} else if ($splmn_jQuery(target).closest("a")) {
return $splmn_jQuery(target).closest("a")[0];
}
}
function loadOptinWidgetOnBuyNow(settings, originalViewportSize) {
var secondClick = false;
document.body.addEventListener(
"click",
function (e) {
const buy_now_target = getTargetButtonFromEvent(e.target);
if (
buy_now_target &&
buy_now_target.getAttribute("data-testid") &&
buy_now_target.getAttribute("data-testid") == "Checkout-button"
) {
if (!secondClick) {
e.preventDefault();
e.stopPropagation();
loadOptinWidget(settings, originalViewportSize, function () {
secondClick = true;
buy_now_target.click();
});
} else {
secondClick = false;
}
}
},
true
);
}
function loadOptinWidgetOnAddToCart(settings, originalViewportSize) {
var secondClick = false;
document.body.addEventListener(
"click",
function (e) {
const add_to_cart_target = getTargetButtonFromEvent(e.target);
const closest_form = $splmn_jQuery(add_to_cart_target).closest("form");
if (
add_to_cart_target &&
add_to_cart_target.getAttribute("data-testid") != "Checkout-button" &&
closest_form &&
closest_form.attr("action") == "/cart/add"
) {
if (!secondClick) {
e.stopPropagation();
e.preventDefault();
loadOptinWidget(settings, originalViewportSize, function () {
secondClick = true;
if (e.target.click) {
e.target.click();
} else if (e.target["tagName"] === "svg") {
e.target.parentNode.click();
} else if (e.target["tagName"] === "path") {
e.target.closest("svg").parentNode.click();
}
});
} else {
secondClick = false;
}
}
},
true
);
}
function closePopup() {
$splmn_jQuery(`#wa-greeting-bubble`).removeClass("bounceUp");
$splmn_jQuery(`#wa-greeting-bubble`).addClass("bounceDown");
$splmn_jQuery(`#wa-chatOptin-bubble`).removeClass("bounceUp");
$splmn_jQuery(`#wa-chatOptin-bubble`).addClass("bounceDown");
$splmn_jQuery("#wa-chat-btn-root").show();
}
function initChat(settings, redirect) {
let agentDetails = JSON.parse(localStorage.getItem("agent_details"));
if (redirect) {
openInNewTab(agentDetails.link);
}
onChatInitiated(
settings,
agentDetails.agent_id ? agentDetails.agent_id : null
);
localStorage.setItem("agent_details", JSON.stringify({}));
localStorage.setItem("from_greetings", 0);
closePopup();
}
try {
function loadOptinWidget(settings, originalViewportSize, onDismiss) {
logWithBadge("Optin Widget : Initializing");
$splmn_jQuery("body").removeClass("wa-optin-widget-stop-scrolling");
$splmn_jQuery("#wa-optin-widget-main").remove();
let current_device_type = deviceType();
if (
(((current_device_type == 1) &
settings.optin.devices.includes("mobile")) |
((current_device_type == 2) &
settings.optin.devices.includes("desktop"))) ===
0
) {
logWithBadge("Optin Widget : Disabled for current device type", true);
setTimeout(onDismiss, 200);
return;
}
if (localStorage.getItem("opted_in_phone_v2")) {
logWithBadge("Optin Widget : Already opted in");
setTimeout(onDismiss, 200);
return;
}
if (
Date.now() -
JSON.parse(localStorage.getItem("optin_widget_last_shown")) <
settings.optin.delayBetweenEachOptinWidgetShow * 1000
) {
logWithBadge("Optin Widget : Shown recently", true);
setTimeout(onDismiss, 200);
return;
}
if (
localStorage.getItem("dismiss_count") > 1 &&
Date.now() -
JSON.parse(localStorage.getItem("optin_widget_last_dismissed")) <
settings.optin.delayAfterOptinWidgetDismissed * 1000
) {
logWithBadge("Optin Widget : Was closed by user previously", true);
setTimeout(onDismiss, 200);
return;
} else if (
localStorage.getItem("dismiss_count") > 1 &&
Date.now() -
JSON.parse(localStorage.getItem("optin_widget_last_dismissed")) >=
settings.optin.delayAfterOptinWidgetDismissed * 1000
) {
localStorage.removeItem("dismiss_count");
}
var widgetContainer = document.createElement("div");
var blurContainer = document.createElement("div");
blurContainer.className = "wa-blur-container wa-optin-widget-z-index";
blurContainer.id = "wa-optin-widget-main";
document.body.appendChild(blurContainer);
$splmn_jQuery(blurContainer).hide();
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".wa-optin-widget-z-index { z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.optin
: settings.devices.desktop.zindex.optin) +
";}";
document.head.appendChild(style);
widgetContainer.className =
"wa-optin-widget-container wa-optin-widget-z-index";
if (
window.getComputedStyle(document.body).direction == "rtl" &&
mobileCheck()
) {
widgetContainer.style.transform = "translate(-50%, -50%)";
} else if (window.getComputedStyle(document.body).direction == "rtl") {
widgetContainer.style.transform = "translate(-25%, -50%)";
}
var closeBtn = document.createElement("div");
closeBtn.className = "wa-optin-widget-close-btn";
var closeImg = document.createElement("img");
closeImg.className = "wa-optin-widget-close-img";
closeImg.src =
"https://cdn.shopify.com/s/files/1/0272/5983/0365/files/Vector_4.png?36";
closeBtn.appendChild(closeImg);
closeBtn.onclick = function (e) {
var dismiss_count = localStorage.getItem("dismiss_count");
localStorage.setItem(
"dismiss_count",
parseInt(dismiss_count) ? parseInt(dismiss_count) + 1 : 1
);
localStorage.setItem(
"optin_widget_last_dismissed",
JSON.stringify(Date.now())
);
removeOptinWidget();
onDismiss();
};
var contentContainer = document.createElement("div");
contentContainer.className = "wa-optin-widget-content-container";
var leftSec = document.createElement("div");
var rightSec = document.createElement("div");
var title = document.createElement("div");
title.className = "wa-optin-widget-title-container";
title.innerHTML = getOptinWidgetTitleText(
settings.optin.lang,
settings.shopName
);
var subTitle = document.createElement("div");
subTitle.className = "wa-optin-widget-title-container";
subTitle.innerHTML = getSubTitleText(settings.optin.lang);
var ulContainer = document.createElement("div");
ulContainer.className = "wa-optin-widget-ul-container";
ulContainer.innerHTML = `
${getOrderText(settings.optin.lang)}
${getDeliveryText(settings.optin.lang)}
${getCustomerSupportText(
settings.optin.lang
)}
${getDiscountCodesText(settings.optin.lang)}
`;
var noSpamText = document.createElement("div");
noSpamText.classList = "wa-optin-widget-spam-msg";
noSpamText.innerHTML = getNoSpamText(settings.optin.lang);
leftSec.appendChild(title);
leftSec.appendChild(subTitle);
leftSec.appendChild(ulContainer);
leftSec.appendChild(noSpamText);
var rightSecTxtCont = document.createElement("div");
rightSecTxtCont.className = "wa-optin-widget-right-sec-content-container";
var countryLogo = document.createElement("span");
countryLogo.className = "wa-optin-widget-country-flag";
countryLogo.id = "wa-splmn-country-flag-logo";
var buttonConfirm = document.createElement("button");
buttonConfirm.innerText = getConfirmBtnText(settings.optin.lang);
buttonConfirm.className = "wa-optin-widget-confirm-btn";
buttonConfirm.id = "wa-optin-widget-confirm-btn";
var bgContainer = document.createElement("div");
bgContainer.className = "wa-optin-widget-title-bg-container";
leftSec.className = "wa-optin-widget-left-sec";
rightSec.className = "wa-optin-widget-right-sec";
var textContent = document.createElement("div");
var inputContainer = document.createElement("div");
inputContainer.className = "wa-input-container";
var numberInput = document.createElement("input");
numberInput.className = "splmn-phone-storefront";
numberInput.type = "tel";
numberInput.addEventListener("keydown", (e) => {
var confirmBtn = document.getElementById("wa-optin-widget-confirm-btn");
if (e.target.value.length >= 6) {
if (confirmBtn) {
confirmBtn.classList.add("wa-optin-widget-confirm-btn-active");
}
} else if (!e.target.value.trim()) {
if (confirmBtn) {
confirmBtn.classList.remove("wa-optin-widget-confirm-btn-active");
}
}
});
rightSecTxtCont.appendChild(numberInput);
rightSecTxtCont.appendChild(buttonConfirm);
rightSec.appendChild(rightSecTxtCont);
contentContainer.appendChild(closeBtn);
contentContainer.appendChild(bgContainer);
contentContainer.appendChild(leftSec);
contentContainer.appendChild(rightSec);
contentContainer.appendChild(textContent);
widgetContainer.appendChild(contentContainer);
$splmn_jQuery("body").addClass("wa-optin-widget-stop-scrolling");
blurContainer.appendChild(widgetContainer);
$splmn_jQuery(blurContainer).fadeIn();
var iti = window.intlTelInput(numberInput, {
// utilsScript: "utils.js",
separateDialCode: true,
initialCountry: currentCountryCode.code,
});
numberInput.onblur = () => {
if (mobileCheck()) {
setTimeout(function () {
restoreMobileOptinWidgetSize();
}, 200);
}
};
window.onresize = function () {
if (mobileCheck()) {
var updatedSize =
$splmn_jQuery(window).width() + $splmn_jQuery(window).height();
if (updatedSize == originalViewportSize) {
// this means keyboard is not visible
restoreMobileOptinWidgetSize();
} else {
// this means keyboard is visible
shrinkMobileOptinWidget();
}
}
};
buttonConfirm.onclick = function () {
var phone = numberInput.value;
var countryCode = iti.getSelectedCountryData().dialCode;
logWithBadge("Entered Phone Number : " + phone);
logWithBadge("Entered Country Code : " + countryCode);
if (!countryCode) {
alert("Please enter a country code");
return;
}
if (!phone || phone.replace(/ /g, "").length < 6) {
alert("Please enter a valid phone number");
return;
}
if (phone && countryCode) {
buttonConfirm.setAttribute("disabled", true);
$splmn_jQuery.ajax({
url:
SERVER_BASE_URL_MESSAGING +
"/api/v1/account/user/subscribe/widget",
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded",
data: {
url: getShopId(),
number: phone,
countryCode: countryCode,
},
success: function (e) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
onDismiss();
logWithBadge("Optin Widget : Optin successful");
},
error: function (e) {
if (e && e.status === 202) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
onDismiss();
logWithBadge("Optin Widget : Optin successful");
} else {
console.log("Error : ", e);
if (e.responseText) {
let error = JSON.parse(e.responseText);
alert(error.message);
logWithBadge("Optin Widget : Optin failed", true);
}
}
},
});
}
};
localStorage.setItem(
"optin_widget_last_shown",
JSON.stringify(Date.now())
);
// document.getElementById("wa-optin-country-code").addEventListener('focus', (e) => {
// if (e.relatedTarget) {
// e.relatedTarget.removeAttribute('tabindex');
// e.target.focus();
// }
// return false;
// })
// document
// .getElementById("wa-optin-country-code")
// .addEventListener("focus", (e) => {
// if (e.relatedTarget) {
// setTimeout(() => {
// e.relatedTarget.removeAttribute("tabindex");
// e.target.focus();
// }, 100);
// }
// return false;
// });
// document
// .getElementById("wa-optin-phone-number")
// .addEventListener("focus", (e) => {
// if (e.relatedTarget) {
// setTimeout(() => {
// e.relatedTarget.removeAttribute("tabindex");
// e.target.focus();
// }, 100);
// }
// return false;
// });
// if (!mobileCheck()) {
// $splmn_jQuery("#wa-optin-country-code").focus();
// }
}
} catch (e) {}
try {
function loadOptinWidgetViaChat(settings, originalViewportSize, onDismiss) {
logWithBadge("Optin Via Chat : Initializing");
if (!settings?.chatWidget?.optinEnabled) {
logWithBadge("Optin Via Chat : Redirecting as OVC is disabled");
initChat(settings, true);
return;
}
$splmn_jQuery("body").removeClass("wa-optin-widget-stop-scrolling");
$splmn_jQuery("#wa-optin-widget-main").remove();
let type = "chatOptin";
if ($splmn_jQuery(`#wa-${type}-bubble`).length) {
$splmn_jQuery(`#wa-${type}-bubble`).remove();
$splmn_jQuery(`#wa-greeting-bubble`).hide();
$splmn_jQuery("#wa-chat-btn-root").hide();
}
let { chat, avatarStyleStr, root, header } = createOptinChatbox(
settings,
type
);
var widgetContainerWrapper = document.createElement("div");
widgetContainerWrapper.className =
deviceType() == 1
? "splmn-optin-via-chat-wrapper-mobile"
: "splmn-optin-via-chat-wrapper";
let current_device_type = deviceType();
if (
(((current_device_type == 1) &
settings.optin.devices.includes("mobile")) |
((current_device_type == 2) &
settings.optin.devices.includes("desktop"))) ===
0
) {
logWithBadge(
"Optin Via Chat : Not enabled for current device type",
true
);
setTimeout(onDismiss, 200);
return;
}
var widgetContainer = document.createElement("div");
widgetContainer.id = "wa-chat-optin";
widgetContainer.className = "splmn-optin-via-chat";
if (
window.getComputedStyle(document.body).direction == "rtl" &&
mobileCheck()
) {
widgetContainer.style.transform = "translate(-50%, -50%)";
} else if (window.getComputedStyle(document.body).direction == "rtl") {
widgetContainer.style.transform = "translate(-25%, -50%)";
}
var inputBox = document.createElement("div");
inputBox.className = "splmn-optin-via-chat-input-box";
// inputBox.style.gap = "1rem";
// TODO add direction:rtl
var buttonContainer = document.createElement("div");
buttonContainer.className = "splmn-whatsapp-send";
var buttonConfirm = document.createElement("img");
buttonConfirm.alt = "";
buttonConfirm.src =
"https://cdn.shopify.com/s/files/1/0449/7794/6790/files/Optin-ChatWidget-Send_30_12_22.svg?v=1669788356";
buttonConfirm.className = "wa-optin-clickButton";
buttonConfirm.id = "wa-optin-clickButton";
buttonConfirm.height = "40";
buttonConfirm.width = "40";
// var flagContainer = document.createElement('div');
// flagContainer.className = 'splmn-flag-container';
// var countryCodeInput;
var numberInput = document.createElement("input");
numberInput.className = "splmn-phone";
numberInput.type = "tel";
inputBox.appendChild(numberInput);
buttonContainer.appendChild(buttonConfirm);
widgetContainer.appendChild(inputBox);
widgetContainer.appendChild(buttonContainer);
widgetContainerWrapper.appendChild(widgetContainer);
chat.appendChild(widgetContainerWrapper);
root.appendChild(header);
root.appendChild(chat);
document.body.appendChild(root);
var iti = window.intlTelInput(numberInput, {
// utilsScript: "utils.js",
separateDialCode: true,
initialCountry: currentCountryCode.code,
});
if (!$splmn_jQuery("#wa-greeting-bubble").length) {
$splmn_jQuery("#wa-chat-btn-root").hide();
$splmn_jQuery(`#wa-${type}-bubble`).addClass("bounceUp");
}
$splmn_jQuery(`#wa-greeting-bubble`).remove();
window.onresize = function () {
if (mobileCheck()) {
var updatedSize =
$splmn_jQuery(window).width() + $splmn_jQuery(window).height();
if (updatedSize == originalViewportSize) {
// this means keyboard is not visible
restoreMobileOptinWidgetSize();
} else {
// this means keyboard is visible
shrinkMobileOptinWidget();
}
}
};
buttonConfirm.onclick = function () {
var phone = numberInput.value;
var countryCode = iti.getSelectedCountryData().dialCode;
logWithBadge("Entered Phone Number : " + phone);
logWithBadge("Entered Country Code : " + countryCode);
if (!countryCode) {
alert("Please enter a country code");
return;
}
if (!phone || phone.replace(/ /g, "").length < 6) {
alert("Please enter a valid phone number");
return;
}
if (phone && countryCode) {
buttonConfirm.setAttribute("disabled", true);
let agentDetails = JSON.parse(localStorage.getItem("agent_details"));
openInNewTab(agentDetails.link);
$splmn_jQuery.ajax({
url:
SERVER_BASE_URL_MESSAGING +
"/api/v1/account/user/subscribe/chatWidget",
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded",
data: {
url: getShopId(),
number: phone,
countryCode: countryCode,
},
success: function (e) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
if (localStorage.getItem("from_greetings")) {
initChat(settings);
} else {
onDismiss();
}
logWithBadge("Optin Via Chat : Optin successfull");
},
error: function (e) {
if (e && e.status === 202) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
if (localStorage.getItem("from_greetings")) {
initChat(settings);
} else {
onDismiss();
}
logWithBadge("Optin Via Chat : Optin successfull");
} else {
if (e.responseText) {
let error = JSON.parse(e.responseText);
alert(error.message);
logWithBadge("Optin Via Chat : Optin failed", true);
}
}
},
});
}
};
// Focus opens keyboard automatically but doesnt shift content up
// setTimeout(function() {
// $splmn_jQuery('#wa-optin-phone-number').focus();
// });
}
} catch (e) {}
function removeOptinWidget() {
$splmn_jQuery("#wa-optin-widget-main").fadeOut(600, "linear");
setTimeout(function () {
$splmn_jQuery("body").removeClass("wa-optin-widget-stop-scrolling");
$splmn_jQuery("#wa-optin-widget-main").remove();
}, 200);
}
function getOptinWidgetTitleText(widgetLanguage, shop_name) {
switch (widgetLanguage) {
case "ENGLISH":
return `
Welcome to ${shop_name}!
`;
case "PORTUGUESE":
return `
Bem-vindo ao ${shop_name}!
`;
case "SPANISH":
return `
Bienvenido a ${shop_name}!
`;
case "ITALIAN":
return `
Benvenuto a ${shop_name}!
`;
case "FRENCH":
return `
Bienvenue à ${shop_name}!
`;
case "INDONESIAN":
return `
Selamat Datang di ${shop_name}!
`;
case "GERMAN":
return `
Willkommen zu ${shop_name}!
`;
case "ARABIC":
return `
مرحبا بك في ${shop_name}!
`;
case "TURKISH":
return `
Hoşgeldiniz ${shop_name}!
`;
case "HEBREW":
return `
ברוך הבא ל ${shop_name}!
`;
case "DUTCH":
return `
Welkom bij ${shop_name}!
`;
default:
return `
Welcome to ${shop_name}!
`;
}
}
function getOrderText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Order details";
case "PORTUGUESE":
return "Detalhes do pedido";
case "SPANISH":
return "Detalles del pedido";
case "ITALIAN":
return "Dettagli dell'ordine";
case "FRENCH":
return "Détails de la commande";
case "INDONESIAN":
return "Rincian pesanan";
case "GERMAN":
return "Bestelldetails";
case "ARABIC":
return "تفاصيل الطلب";
case "TURKISH":
return "Sipariş detayları";
case "HEBREW":
return "פרטי הזמנה";
case "DUTCH":
return "Bestel Details";
default:
return "";
}
}
function getDeliveryText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Delivery updates";
case "PORTUGUESE":
return "Atualizações de entrega";
case "SPANISH":
return "Actualizaciones de entrega";
case "ITALIAN":
return "Aggiornamenti di consegna";
case "FRENCH":
return "Mises à jour de livraison";
case "INDONESIAN":
return "Pembaruan pengiriman";
case "GERMAN":
return "Aktualisierungen der Lieferung";
case "ARABIC":
return "تحديثات التسليم";
case "TURKISH":
return "Teslimat güncellemeleri";
case "HEBREW":
return "עדכוני משלוח";
case "DUTCH":
return "Levering updates";
default:
return "";
}
}
function getCustomerSupportText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Customer Support";
case "PORTUGUESE":
return "Suporte ao cliente";
case "SPANISH":
return "Apoyo al cliente";
case "ITALIAN":
return "Assistenza clienti";
case "FRENCH":
return "Soutien à la clientèle";
case "INDONESIAN":
return "Dukungan pelanggan";
case "GERMAN":
return "Kundenbetreuung";
case "ARABIC":
return "دعم العملاء";
case "TURKISH":
return "Müşteri Desteği";
case "HEBREW":
return "שירות לקוחות";
case "DUTCH":
return "Klantenondersteuning";
default:
return "";
}
}
function getDiscountCodesText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "Discount Codes";
case "PORTUGUESE":
return "Códigos de desconto";
case "SPANISH":
return "Códigos de descuento";
case "ITALIAN":
return "Codici Sconto";
case "FRENCH":
return "Codes de réduction";
case "INDONESIAN":
return "Kode Diskon";
case "GERMAN":
return "Rabatt-Codes";
case "ARABIC":
return "رموز الخصم";
case "TURKISH":
return "İndirim Kodları";
case "HEBREW":
return "קודי הנחה";
case "DUTCH":
return "Kortingscodes";
default:
return "";
}
}
function getSubTitleText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return `
Subscribe to important Whatsapp notifications from us
`;
case "PORTUGUESE":
return `
Assine nossas notificações importantes do Whatsapp
`;
case "SPANISH":
return `
Suscríbase a nuestras notificaciones importantes de Whatsapp
`;
case "ITALIAN":
return `
Iscriviti per ricevere importanti notifiche Whatsapp da noi
`;
case "FRENCH":
return `
Abonnez-vous aux notifications Whatsapp importantes de notre part
`;
case "INDONESIAN":
return `
Berlangganan notifikasi Whatsapp penting dari kami
`;
case "GERMAN":
return `
Abonnieren Sie wichtige WhatsApp-Benachrichtigungen von uns
`;
case "ARABIC":
return `
اشترك في إشعارات Whatsapp المهمة منا
`;
case "TURKISH":
return `
Bizden önemli Whatsapp bildirimlerine abone olun
`;
case "HEBREW":
return `
הירשמו להתראות ווטסאפ חשובות מאיתנו
`;
case "DUTCH":
return `
Abonneer u op belangrijke Whatsapp-meldingen van ons
`;
default:
return ``;
}
}
function getNoSpamText(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
return "We promise not to spam you!";
case "PORTUGUESE":
return "Prometemos não enviar spam para você!";
case "SPANISH":
return "¡Prometemos no enviarte spam!";
case "ITALIAN":
return "Promettiamo di non inviarti spam!";
case "FRENCH":
return "Nous promettons de ne pas vous spammer!";
case "INDONESIAN":
return "Kami berjanji untuk tidak mengirim spam kepada Anda!";
case "GERMAN":
return "Wir versprechen, Sie nicht zu spammen!";
case "ARABIC":
return "نحن نعدك بعدم إرسال بريد عشوائي إليك!";
case "TURKISH":
return "Size spam göndermeyeceğimize söz veriyoruz!";
case "HEBREW":
return "אנו מבטיחים לא לשלוח לך דואר זבל!";
case "DUTCH":
return "We beloven je niet te spammen!";
default:
return "";
}
}
function restoreMobileOptinWidgetSize() {
if (document.querySelector(".wa-optin-widget-ul-container")) {
document.querySelector(".wa-optin-widget-ul-container").style.display =
"flex";
document.querySelector(".wa-optin-widget-right-sec").style.marginTop =
"0";
document
.querySelector(".wa-optin-widget-right-sec")
.classList.remove(
"wa-optin-widget-virtual-keyboard-right-sec-margin-top"
);
document
.querySelector(".wa-optin-widget-confirm-btn")
.classList.remove(
"wa-optin-widget-virtual-keyboard-confirm-btn-margin"
);
document
.querySelector(".wa-optin-clickButton")
.classList.remove(
"wa-optin-widget-virtual-keyboard-confirm-btn-margin"
);
}
}
function shrinkMobileOptinWidget() {
if (document.querySelector(".wa-optin-widget-ul-container")) {
document.querySelector(".wa-optin-widget-ul-container").style.display =
"none";
document
.querySelector(".wa-optin-widget-right-sec")
.classList.add("wa-optin-widget-virtual-keyboard-right-sec-margin-top");
document
.querySelector(".wa-optin-widget-confirm-btn")
.classList.add("wa-optin-widget-virtual-keyboard-confirm-btn-margin");
document
.querySelector(".wa-optin-clickButton")
.classList.remove(
"wa-optin-widget-virtual-keyboard-confirm-btn-margin"
);
}
}
function createOldOptinWidget(settings) {
if (settings.optin.enable) {
if (isThankYouPage()) {
if (localStorage.getItem("opted_in_phone_v2")) {
if (Shopify.checkout.order_id) {
$splmn_jQuery.ajax({
url: SERVER_BASE_URL + "/shop/order/optin/v2",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
shop_id: getShopId(),
phone: localStorage.getItem("opted_in_phone_v2"),
order_id: Shopify.checkout.order_id,
}),
});
}
loadOptinConfirmed(settings.optin.lang);
} else {
thankYouPageOptinWidget(settings.optin.lang);
}
} else {
$splmn_jQuery("form[action^='/cart']").on("submit", function () {
loadOldOptinWidget(settings);
});
$splmn_jQuery("form[action^='/cart']")
.find("button")
.on("click", function () {
loadOldOptinWidget(settings);
});
$splmn_jQuery("form[action^='/cart/add']")
.find("button")
.on("click", function () {
loadOldOptinWidget(settings);
});
$splmn_jQuery("#add-to-cart").on("click", function () {
loadOldOptinWidget(settings);
});
if (top.location.href.indexOf("/cart") > 0) {
loadOldOptinWidget(settings);
}
}
}
}
function loadOldOptinWidget(settings) {
$splmn_jQuery("#wa-optin-widget-root-old").remove();
if (localStorage.getItem("opted_in_phone_v2")) {
return;
}
if (localStorage.getItem("dismiss_count") > 1) {
return;
}
let current_device_type = deviceType();
var widgetContainer = document.createElement("div");
widgetContainer.id = "wa-optin-widget-root-old";
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".wa-optin-widget-z-index-old { z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.optin
: settings.devices.desktop.zindex.optin) +
";}";
document.head.appendChild(style);
widgetContainer.className =
"wa-optin-widget-container-old wa-optin-widget-z-index-old";
var closeBtn = document.createElement("div");
closeBtn.className = "wa-optin-widget-close-btn-old";
closeBtn.onclick = function () {
var dismiss_count = localStorage.getItem("dismiss_count");
localStorage.setItem(
"dismiss_count",
parseInt(dismiss_count) ? parseInt(dismiss_count) + 1 : 1
);
$splmn_jQuery("#wa-optin-widget-root-old").remove();
};
var closeImg = document.createElement("img");
closeImg.className = "wa-optin-widget-close-img-old";
closeImg.src =
"https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Group_2.png?1194";
closeBtn.appendChild(closeImg);
var contentContainer = document.createElement("div");
contentContainer.className = "wa-optin-widget-content-container-old";
var logoImg = document.createElement("img");
logoImg.className = "wa-optin-widget-logo-img-old";
logoImg.src = getOptinWidgetLogoImg(settings.optin.lang);
var numberContainer = document.createElement("div");
numberContainer.style = "text-align: center";
var countryCodeInput = document.createElement("input");
countryCodeInput.className =
"wa-optin-widget-number-input-old input-country-code";
countryCodeInput.placeholder = "+91";
countryCodeInput.id = "wa-optin-country-code-old";
countryCodeInput.autocomplete = "off";
var numberInput = document.createElement("input");
numberInput.className = "wa-optin-widget-number-input-old";
numberInput.placeholder = "XXXXXXXXXX";
numberInput.id = "wa-optin-phone-number-old";
numberInput.type = "tel";
var confirmButton = document.createElement("button");
confirmButton.className = "wa-optin-widget-confirm-button-old";
confirmButton.innerHTML = getConfirmBtnText(settings.optin.lang);
buttonConfirm.onclick = function () {
// console.log("button clicked");
buttonConfirm.setAttribute("disabled", true);
var phone = $splmn_jQuery("#wa-optin-phone-number").val();
var countryCode = $splmn_jQuery("#wa-optin-country-code").val();
if (!countryCode) {
buttonConfirm.setAttribute("disabled", true);
alert("Please enter a country code");
buttonConfirm.setAttribute("disabled", false);
return;
}
if (!phone || phone.replace(/ /g, "").length < 6) {
alert("Please enter a valid phone number");
buttonConfirm.setAttribute("disabled", false);
return;
}
if (phone && countryCode) {
$splmn_jQuery.ajax({
url:
SERVER_BASE_URL_MESSAGING + "/api/v1/account/user/subscribe/widget",
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded",
data: {
url: getShopId(),
number: phone,
countryCode: countryCode,
},
success: function (e) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
onDismiss();
},
error: function (e) {
if (e && e.status === 202) {
localStorage.setItem("opted_in_phone_v2", phone);
localStorage.setItem("opted_in_country_code_v2", countryCode);
removeOptinWidget();
onDismiss();
} else {
console.log("Error : ", e);
if (e.responseText) {
let error = JSON.parse(e.responseText);
alert(error.message);
}
}
},
});
}
};
numberContainer.appendChild(countryCodeInput);
numberContainer.appendChild(numberInput);
numberContainer.appendChild(confirmButton);
contentContainer.appendChild(logoImg);
contentContainer.appendChild(numberContainer);
widgetContainer.appendChild(closeBtn);
widgetContainer.appendChild(contentContainer);
document.body.appendChild(widgetContainer);
document
.getElementById("wa-optin-country-code-old")
.addEventListener("focus", (e) => {
if (e.relatedTarget) {
e.relatedTarget.removeAttribute("tabindex");
e.target.focus();
}
return false;
});
$splmn_jQuery("#wa-optin-country-code-old").focus();
}
function getOptinWidgetLogoImg(widgetLanguage) {
switch (widgetLanguage) {
case "ENGLISH":
if (mobileCheck()) {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-eng-mobile.png";
} else {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-eng-desktop.png";
}
case "PORTUGUESE":
if (mobileCheck()) {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-por-mobile.png";
} else {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-por-desktop-s.png?1306";
}
case "SPANISH":
if (mobileCheck()) {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-spa-mobile.png";
} else {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-spa-desktop-s.png?1306";
}
case "ITALIAN":
if (mobileCheck()) {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-ita-mobile.png?1538";
} else {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-ita-desktop.png?1538";
}
default:
if (mobileCheck()) {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-eng-mobile.png";
} else {
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/optin-eng-desktop.png";
}
}
}
/*======================*/
/* WhatsApp Chat Button */
/*======================*/
function createWhatsappBtn(settings) {
var current_device_type = deviceType();
var settingsDeviceType = getDeviceTypeFromSettings(settings);
if (
settings.chatButton.enabled &&
(settingsDeviceType & current_device_type) != 0 &&
settings.agents.length > 0 &&
settings.agents[0].phone &&
(settings.store.showButtonWhenOffline ||
(settings.store.open && isAtleastOneAgentAvailable(settings))) &&
isWhatsAppBtnVisible(settings)
) {
var style = document.createElement("style");
style.type = "text/css";
var chatButton = settings.chatButton;
//zindex from settings
style.innerHTML =
".wa-splmn-chat-btn-offset {" +
getButtonAlignment(settings) +
": " +
getHeightOffset(current_device_type, settings) +
"px;" +
getButtonPosition(current_device_type, settings, "chat") +
":" +
getHorizontalOffset(current_device_type, settings) +
"px;" +
"z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.chat
: settings.devices.desktop.zindex.chat) +
";}";
document.head.appendChild(style);
var d = document.createElement("div");
d.id = "wa-chat-btn-root";
d.className = "wa-chat-btn-fixed wa-splmn-chat-btn-offset";
var icon_url = chatButton.iconUrl;
if (!icon_url) {
icon_url =
"https://cdn.shopify.com/s/files/1/0265/2572/8803/files/wa.svg?v=1586952948";
}
var is_chat_btn_solid_background = settings.chatButton.colors.solidBg;
var bgColor1 = settings.chatButton.colors.bg[0] || "#20802C";
var bgColor2 = settings.chatButton.colors.bg[1] || "#30BF42";
var iconColor = settings.chatButton.colors.icon || "#ffffff";
var chat_btn_text_color = settings.chatButton.colors.text || "#ffffff";
var mainStyleStr = "";
var imgStyleStr = "";
var textStyleStr = "";
var iconStyleStr = "";
var iconClass = "";
if (chatButton.colors.custom) {
d.className += " wa-custom-chat-btn";
textStyleStr = `color: ${chat_btn_text_color}`;
iconStyleStr = `background: ${iconColor}; -webkit-mask-image: url(${icon_url}); -webkit-mask-size: cover; -webkit-mask-position: center;`;
if (
chatButton.cssClasses.btn.includes("wa-chat-btn-base-cta-with-icon")
) {
if (is_chat_btn_solid_background) {
imgStyleStr = `background: ${bgColor1};`;
} else {
imgStyleStr = `background-image: linear-gradient(112.42deg, ${bgColor1} 0%, ${bgColor1} 0.01%, ${bgColor2} 100%);`;
}
if (chatButton.cssClasses.icon.includes("no-box-shadow")) {
iconClass += " " + "no-box-shadow";
}
} else {
if (is_chat_btn_solid_background) {
mainStyleStr = `background: ${bgColor1};`;
} else {
mainStyleStr = `background-image: linear-gradient(112.42deg, ${bgColor1} 0%, ${bgColor1} 0.01%, ${bgColor2} 100%);`;
}
imgStyleStr += iconStyleStr;
if (chatButton.cssClasses.icon.includes("no-box-shadow")) {
d.className += " " + "no-box-shadow";
iconClass += " " + "no-box-shadow";
}
}
if (chatButton.cssClasses.btn.includes("bordered")) {
mainStyleStr += " " + "border: 1px solid " + iconColor;
}
d.style = mainStyleStr;
}
if (chatButton && chatButton.cssClasses.btn) {
d.className += " " + chatButton.cssClasses.btn;
} else {
d.className += " wa-chat-btn-default";
}
var btn_position = getButtonPosition(
current_device_type,
settings,
"chat"
);
var defaultTextMarkUp = `
${chatButton.cta}
`;
var defaultImageMarkUp = chatButton.colors.custom
? ``
: ``;
if (
chatButton &&
chatButton.cssClasses.btn.includes("wa-chat-btn-base-cta-with-icon") &&
chatButton.ctaEnabled
) {
if (chatButton.colors.custom) {
defaultImageMarkUp = `
";
}
d.onclick = onClick(settings, current_device_type);
document.body.appendChild(d);
}
}
function getDeviceTypeFromSettings(settings, type = "chat") {
let deviceType = 3; // By default for both mobile and desktop
const positionType =
type === "chat"
? "chatPos"
: type === "share"
? "sharePos"
: "spinWheelPos";
let isMobile =
settings.devices &&
settings.devices.mobile &&
settings.devices.mobile[positionType];
let isDesktop =
settings.devices &&
settings.devices.desktop &&
settings.devices.desktop[positionType];
if (isMobile && isDesktop) deviceType = 3;
else if (isMobile) deviceType = 1;
else if (isDesktop) deviceType = 2;
return deviceType;
}
function isAtleastOneAgentAvailable(settings) {
for (var i = 0; i < settings.agents.length; i++) {
if (
isAgentCurrentlyAvailable(settings.agents[i], settings.store.timezone)
) {
return true;
}
}
return false;
}
const weekday = {
Sun: 6,
Mon: 0,
Tue: 1,
Wed: 2,
Thu: 3,
Fri: 4,
Sat: 5,
};
function isAgentCurrentlyAvailable(agent, store_timezone = "UTC") {
// options for intl object
let options = {
weekday: "short",
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone: store_timezone,
hourCycle: "h23",
};
// get intl string with options
const intlObj = new Intl.DateTimeFormat("en-US", options)
.format(new Date())
.trim();
// get weekday name and time from intlObj
const dateObjSplit = intlObj.split(" ");
// get week day index
const currentDayIndex = weekday[dateObjSplit[0]];
// get current hours and minutes
const time = dateObjSplit[1].split(":");
const hours = parseInt(time[0]);
const minutes = parseInt(time[1]);
var currentHourMinutes = hours * 60 + minutes;
var startHourMinutes =
parseInt(agent.timings[currentDayIndex].start_time.substring(0, 2)) * 60 +
parseInt(agent.timings[currentDayIndex].start_time.substring(2, 4));
var endHourMinutes =
parseInt(agent.timings[currentDayIndex].end_time.substring(0, 2)) * 60 +
parseInt(agent.timings[currentDayIndex].end_time.substring(2, 4));
return (
startHourMinutes <= currentHourMinutes &&
endHourMinutes >= currentHourMinutes
);
}
function isWhatsAppBtnVisible(settings) {
let showOnPages = settings.chatButton.showOnPages;
if (
(window.ShopifyAnalytics &&
window.ShopifyAnalytics.meta &&
window.ShopifyAnalytics.meta.page &&
window.ShopifyAnalytics.meta.page.pageType !== undefined
? window.ShopifyAnalytics &&
window.ShopifyAnalytics.meta &&
window.ShopifyAnalytics.meta.page &&
window.ShopifyAnalytics.meta.page.pageType === "home"
: window.location.pathname === "/") &&
showOnPages &&
!showOnPages.includes("HOME")
) {
return false;
} else if (
isCollectionsPage() &&
showOnPages &&
!showOnPages.includes("COLLECTION")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/products/(.*)") ||
window.location.pathname.match("(.*)/products")) &&
showOnPages &&
!showOnPages.includes("PRODUCT")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/cart/(.*)") ||
window.location.pathname.match("(.*)/cart")) &&
!(
(deviceType() === 2 &&
showOnPages &&
showOnPages.includes("CART_DESKTOP")) ||
(deviceType() === 1 && showOnPages.includes("CART_MOBILE"))
)
) {
return false;
} else if (
(window.location.pathname.match("(.*)/orders/(.*)") ||
window.location.pathname.match("(.*)/orders") ||
window.location.pathname.match("(.*)/checkouts/(.*)")) &&
showOnPages &&
!showOnPages.includes("THANKYOU")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/blogs/(.*)") ||
window.location.pathname.match("(.*)/blogs")) &&
showOnPages &&
!showOnPages.includes("BLOGPOST")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/pages/(.*)") ||
window.location.pathname.match("(.*)/pages")) &&
showOnPages &&
!showOnPages.includes("PAGE")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/account/(.*)") ||
window.location.pathname.match("(.*)/account")) &&
showOnPages &&
!showOnPages.includes("ACCOUNT")
) {
return false;
} else {
return true;
}
}
function isCollectionsPage() {
if (
(window.location.pathname.match("(.*)/collections/(.*)") ||
window.location.pathname.match("(.*)/collections")) &&
!(
window.location.pathname.match("(.*)/products/(.*)") ||
window.location.pathname.match("(.*)/products")
)
) {
return true;
} else {
return false;
}
}
function getButtonAlignment(settings) {
if (settings.chatButton.chatAlign == 2) {
return "top";
} else {
return "bottom";
}
}
function getHeightOffset(current_device_type, settings) {
if (current_device_type == 1) {
return settings.devices.mobile.pages.product.differentHeight &&
isProductPage()
? settings.devices.mobile.pages.product.offset
: settings.devices.mobile.verticalOffset;
} else if (current_device_type == 2) {
return settings.devices.desktop.pages.product.differentHeight &&
isProductPage()
? settings.devices.desktop.pages.product.offset
: settings.devices.desktop.verticalOffset;
}
}
function isProductPage() {
if (window.location.pathname.match("(.*)/products/(.*)")) {
return true;
} else {
return false;
}
}
function getButtonPosition(current_device_type, settings, type) {
var pos = "right";
if (current_device_type == 1) {
if (settings && settings.devices && settings.devices.mobile) {
switch (type) {
case "share":
pos = settings.devices.mobile.sharePos;
break;
case "spinWheel":
pos = settings.devices.mobile.spinWheelPos;
break;
default:
pos = settings.devices.mobile.chatPos;
break;
}
}
} else if (current_device_type == 2) {
if (settings && settings.devices && settings.devices.desktop) {
switch (type) {
case "share":
pos = settings.devices.desktop.sharePos;
break;
case "spinWheel":
pos = settings.devices.desktop.spinWheelPos;
break;
default:
pos = settings.devices.desktop.chatPos;
break;
}
}
}
return pos;
}
function getHorizontalOffset(current_device_type, settings) {
if (current_device_type == 1) {
return settings.devices.mobile.horizontalOffset;
} else if (current_device_type == 2) {
return settings.devices.desktop.horizontalOffset;
}
}
/*=======================*/
/* Callout/Greeting Card */
/*=======================*/
function loadCalloutCard(settings, current_device_type) {
var current_device_type = deviceType();
var settingsDeviceType = getDeviceTypeFromSettings(settings);
if (
settings.chatButton.enabled &&
(settingsDeviceType & current_device_type) != 0 &&
settings.agents.length > 0 &&
settings.agents[0].phone &&
settings.store.open &&
settings.callout.enabled &&
settings.callout.text
) {
let closeBtn = document.createElement("div");
closeBtn.className =
"wa-callout-card-close-btn wa-callout-card-close-btn-" +
getButtonPosition(current_device_type, settings);
closeBtn.innerHTML +=
'';
var calloutCard = document.createElement("div");
var callout = document.createElement("div");
calloutCard.id = "wa-callout-card";
callout.className = "callout-text-container";
callout.appendChild(closeBtn);
var p = document.createElement("p");
p.innerText = settings.callout.text;
callout.appendChild(p);
calloutCard.appendChild(callout);
var style = document.createElement("style");
style.type = "text/css";
//zindex from settings
style.innerHTML =
".wa-callout-card-offset { bottom: " +
getHeightOffset(current_device_type, settings) +
"px;" +
getButtonPosition(current_device_type, settings) +
":" +
getHorizontalOffset(current_device_type, settings) +
"px;" +
"z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.callout
: settings.devices.desktop.zindex.callout) +
";}";
document.head.appendChild(style);
calloutCard.className = "wa-callout-card-fixed wa-callout-card-offset";
calloutCard.onclick = function (e) {
handleCalloutCard(e, settings, current_device_type);
};
let audioUrl =
"https://cdn.shopify.com/s/files/1/0272/5983/0365/files/whatsapp_message-_AudioTrimmer.com.mp3?21";
checkCalloutCardVisibilityTiming(
settings,
current_device_type,
calloutCard,
style,
audioUrl
);
}
}
function handleCalloutCard(e, settings, current_device_type) {
if (
e.target.classList.contains("wa-callout-card-close-btn") ||
e.target.parentNode.classList.contains("wa-callout-card-close-btn")
) {
hideCalloutCard();
} else {
onClick(settings, current_device_type)();
$splmn_jQuery("#wa-callout-card").hide();
}
}
function hideCalloutCard() {
var isCalloutCard = document.getElementById("wa-callout-card");
if (isCalloutCard) {
document
.getElementById("wa-callout-card")
.classList.remove("animate-callout-card");
document
.getElementById("wa-callout-card")
.classList.add("hide-callout-card");
setTimeout(function () {
$splmn_jQuery("#wa-callout-card").hide();
}, 500);
}
}
function onClick(settings, current_device_type) {
return function () {
hideCalloutCard();
if (settings.store.multiAgentEnabled || settings.agents.length > 1) {
loadGreetingWidget(settings, current_device_type);
} else {
if (!settings.store.open) {
var message = getStoreClosedMessage(settings);
alert(message);
} else if (!getOnlineAgentsCount(settings)) {
var message = settings.greeting.offlineMessages.agent
? settings.greeting.offlineMessages.agent
: "Apologies for the inconvenience but none of our agents are online at this time. Please check after sometime.";
alert(message);
} else {
var message = getFinalWhatsappMsg(settings);
var available_agent = getFirstAvailableAgent(settings);
var link = getWhatsappLink(
available_agent.phone,
message,
current_device_type
);
OptinViaChatWidget(settings, link)();
}
}
};
}
function createChatbox(settings, type) {
let root_id = `wa-type-bubble`;
if ($splmn_jQuery(root_id.replace("type", type)).length) {
$splmn_jQuery(root_id).show();
$splmn_jQuery(
root_id.replace("type", type != "chatOptin" ? type : "greeting")
).hide();
return;
}
var root = document.createElement("div");
root.id = root_id.replace("type", type);
type = "greeting";
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".wa-greeting-widget-z-index { z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex[type]
: settings.devices.desktop.zindex[type]) +
";}";
document.head.appendChild(style);
var greetingTemplateId = settings[type].templateId;
var greetingColors = settings[type].colors;
root.className =
"wa-chat-bubble-floating-popup wa_animated wa-greeting-widget-z-index wa-chat-bubble-pos-" +
getButtonPosition(current_device_type, settings, "greeting") +
(greetingTemplateId > 200 && greetingTemplateId < 300
? " wa-intercom"
: "");
var header = document.createElement("div");
header.className =
"wa-chat-bubble-header-common wa-chat-bubble-header-" +
greetingTemplateId +
(greetingTemplateId > 100 && greetingTemplateId < 200 ? " wavy" : "");
var avatarStyleStr = "";
var headerStyleStr = "";
var horizontalGradient = true;
var bgColor1 = greetingColors.bg[0] || "#20802C";
var bgColor2 = greetingColors.bg[1] || "#30BF42";
var headTextStyle = "";
var descTextStyle = "";
if (settings[type].colors.custom) {
switch (greetingTemplateId) {
case 301:
break;
case 302:
header.className += " wavy";
break;
case 303:
horizontalGradient = false;
root.className += " wa-intercom";
break;
}
headerStyleStr = greetingColors.solidBg
? `background: ${bgColor1}`
: horizontalGradient
? `background-image: linear-gradient(110.56deg, ${bgColor1} 0%, ${bgColor2} 100%)`
: `background-image: linear-gradient(164.25deg, ${bgColor1} 18.04%, ${bgColor2} 81.96%)`;
header.style = headerStyleStr;
avatarStyleStr = `background: ${bgColor1};`;
headTextStyle = `color: ${greetingColors.head || "#ffffff"}`;
descTextStyle = `color: ${greetingColors.desc || "#ffffff"}`;
}
header.appendChild(getCloseButton());
header.appendChild(getHeaderTitle(settings, headTextStyle, type));
header.appendChild(getHeaderDesc(settings, descTextStyle, type));
// change the background then, set the agent background.
var chat = document.createElement("div");
chat.className = "wa-chat-bubble-chat";
chat.id = "wa-chat-bubble-chat";
let enablePoweredBy;
if (settings[type].disablePoweredBy == null) {
enablePoweredBy = true;
} else {
enablePoweredBy = !settings[type].disablePoweredBy;
}
if (enablePoweredBy) {
var footer = document.createElement("div");
footer.className = "wa-chat-widget-footer";
footer.innerHTML =
'Powered by SuperLemon';
footer.onclick = function () {
openInNewTab(
"https://apps.shopify.com/whatsapp-chat-button?utm_source=poweredby"
);
};
root.appendChild(footer);
}
return { chat, avatarStyleStr, root, header };
}
function createOptinChatbox(settings, type) {
let root_id = `wa-type-bubble`;
if (jQuery(root_id.replace("type", type)).length) {
jQuery(root_id).show();
jQuery(
root_id.replace("type", type != "chatOptin" ? type : "greeting")
).hide();
return;
}
var root = document.createElement("div");
root.id = root_id.replace("type", type);
type = "chatWidget";
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".wa-greeting-widget-z-index { z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex["optin"]
: settings.devices.desktop.zindex["optin"]) +
";}";
document.head.appendChild(style);
var optinWidgetTemplateId = settings[type].optin_template;
var optinWidgetColors = {
bg: [
settings[type].optin_template_bg_color_1,
settings[type].optin_template_bg_color_2,
],
custom: settings[type].is_optin_template_color_custom,
desc: settings[type].optin_template_desc_text_color,
head: settings[type].optin_template_head_text_color,
solidBg: settings[type].is_optin_template_solid_background,
};
root.className =
"wa-chat-bubble-floating-popup wa_animated wa-greeting-widget-z-index wa-chat-bubble-pos-" +
getButtonPosition(current_device_type, settings, "greeting") +
(optinWidgetTemplateId > 200 && optinWidgetTemplateId < 300
? " wa-intercom"
: "");
var header = document.createElement("div");
header.className =
"wa-chat-bubble-header-common wa-chat-bubble-header-" +
optinWidgetTemplateId +
(optinWidgetTemplateId > 100 && optinWidgetTemplateId < 200
? " wavy"
: "");
var avatarStyleStr = "";
var headerStyleStr = "";
var horizontalGradient = true;
var bgColor1 = optinWidgetColors.bg[0] || "#20802C";
var bgColor2 = optinWidgetColors.bg[1] || "#30BF42";
var headTextStyle = "";
var descTextStyle = "";
if (optinWidgetColors.custom) {
switch (optinWidgetTemplateId) {
case 301:
break;
case 302:
header.className += " wavy";
break;
case 303:
horizontalGradient = false;
root.className += " wa-intercom";
break;
}
headerStyleStr = optinWidgetColors.solidBg
? `background: ${bgColor1}`
: horizontalGradient
? `background-image: linear-gradient(110.56deg, ${bgColor1} 0%, ${bgColor2} 100%)`
: `background-image: linear-gradient(164.25deg, ${bgColor1} 18.04%, ${bgColor2} 81.96%)`;
header.style = headerStyleStr;
avatarStyleStr = `background: ${bgColor1};`;
headTextStyle = `color: ${optinWidgetColors.head || "#ffffff"}`;
descTextStyle = `color: ${optinWidgetColors.desc || "#ffffff"}`;
}
header.appendChild(getCloseButton());
header.appendChild(getHeaderTitle(settings, headTextStyle, type));
header.appendChild(getHeaderDesc(settings, descTextStyle, type));
// change the background then, set the agent background.
var chat = document.createElement("div");
chat.className = "wa-chat-bubble-chat";
chat.id = "wa-chat-bubble-chat";
let enablePoweredBy;
if (settings["greeting"].disablePoweredBy == null) {
enablePoweredBy = true;
} else {
enablePoweredBy = !settings["greeting"].disablePoweredBy;
}
if (enablePoweredBy) {
var footer = document.createElement("div");
footer.className = "wa-chat-widget-footer";
footer.innerHTML =
'Powered by SuperLemon';
footer.onclick = function () {
openInNewTab(
"https://apps.shopify.com/whatsapp-chat-button?utm_source=poweredby"
);
};
root.appendChild(footer);
}
return { chat, avatarStyleStr, root, header };
}
function loadGreetingWidget(settings, current_device_type) {
let type = "greeting";
if ($splmn_jQuery(`#wa-${type}-bubble`).length) {
$splmn_jQuery(`#wa-${type}-bubble`).show();
$splmn_jQuery(`#wa-${type}-bubble`).removeClass("bounceDown");
$splmn_jQuery(`#wa-${type}-bubble`).addClass("bounceUp");
$splmn_jQuery("#wa-chat-btn-root").hide();
return;
}
let { chat, avatarStyleStr, root, header } = createChatbox(settings, type);
if (!settings.store.open) {
var message = getStoreClosedMessage(settings);
var div = document.createElement("div");
div.className = "wa-chat-multiple-cs";
div.id = "wa-chat-multiple-cs";
var agent = document.createElement("div");
agent.className = "list-cs";
var agentProfile = document.createElement("div");
agentProfile.className = "wa-chat-bubble-cs-profile";
agentProfile.innerHTML =
'
' + message + "
";
agent.appendChild(agentProfile);
div.appendChild(agent);
chat.appendChild(div);
root.appendChild(header);
root.appendChild(chat);
} else if (!getOnlineAgentsCount(settings)) {
var message =
settings.greeting.offlineMessages.agent ||
"Apologies for the inconvenience but none of our agents are online at this time. Please check after sometime.";
var div = document.createElement("div");
div.className = "wa-chat-multiple-cs";
div.id = "wa-chat-multiple-cs";
var agent = document.createElement("div");
agent.className = "list-cs";
var agentProfile = document.createElement("div");
agentProfile.className = "wa-chat-bubble-cs-profile";
agentProfile.innerHTML =
'
' + message + "
";
agent.appendChild(agentProfile);
div.appendChild(agent);
chat.appendChild(div);
root.appendChild(header);
root.appendChild(chat);
} else {
chat.appendChild(
getMultipleAgents(settings, current_device_type, avatarStyleStr)
);
root.appendChild(header);
root.appendChild(chat);
}
document.body.appendChild(root);
$splmn_jQuery("#wa-greeting-bubble").addClass("bounceUp");
$splmn_jQuery("#wa-chat-btn-root").hide();
$splmn_jQuery("#wa-chat-optin").hide();
return;
}
function getCloseButton(type) {
var closeBtn = document.createElement("div");
closeBtn.className = "wa-chat-bubble-close-btn";
closeBtn.innerHTML =
'';
closeBtn.onclick = function () {
// new bouncedown greeting widget animation
$splmn_jQuery(`#wa-greeting-bubble`).removeClass("bounceUp");
$splmn_jQuery(`#wa-greeting-bubble`).addClass("bounceDown");
$splmn_jQuery(`#wa-chatOptin-bubble`).removeClass("bounceUp");
$splmn_jQuery(`#wa-chatOptin-bubble`).addClass("bounceDown");
$splmn_jQuery("#wa-chat-btn-root").show();
};
return closeBtn;
}
function getHeaderTitle(settings, customStyle = "", type) {
var headerTitle = document.createElement("div");
headerTitle.className = "wa-chat-bubble-header-title";
headerTitle.innerHTML =
type === "greeting"
? settings.greeting.multiAgentTitle
: settings.chatWidget.optin_title;
headerTitle.style = customStyle;
return headerTitle;
}
function getHeaderDesc(settings, customStyle = "", type) {
var headerDesc = document.createElement("div");
headerDesc.className = "wa-chat-bubble-header-desc";
headerDesc.innerHTML =
type === "greeting"
? settings.greeting.multiAgentMsg
: settings.chatWidget.optin_helpText;
headerDesc.style = customStyle;
return headerDesc;
}
function getOnlineAgentsCount(settings) {
var count = 0;
for (var i = 0; i < settings.agents.length; i++) {
if (!settings.agents[i].enabled) {
continue;
}
if (
!isAgentCurrentlyAvailable(settings.agents[i], settings.store.timezone)
) {
continue;
}
count += 1;
}
return count;
}
function getStoreClosedMessage(settings) {
const today = getDay() - 1;
let start_time, end_time;
// get today's shop time
for (const obj of settings.store.timings) {
if (obj.day === today) {
start_time = obj.start_time;
end_time = obj.end_time;
}
}
start_time = start_time.substring(0, 2) + ":" + start_time.substring(2, 4);
end_time = end_time.substring(0, 2) + ":" + end_time.substring(2, 4);
var message =
settings.greeting.offlineMessages.store ||
"Hi, our working hours are to , request you to reach us at the same time. Apologies for the inconvenience.";
message = message.replace("", start_time);
message = message.replace("", end_time);
return message;
}
function getDay() {
return new Date().getDay();
}
function getFinalWhatsappMsg(settings) {
if (settings.chatButton.productLink) {
return (
encodeURIComponent(window.location.href.split("?")[0]) +
"%0A%0A" +
encodeURIComponent(settings.chatButton.chatMessage)
);
} else {
return encodeURIComponent(settings.chatButton.chatMessage);
}
}
function getFirstAvailableAgent(settings) {
for (var i = 0; i < settings.agents.length; i++) {
if (
isAgentCurrentlyAvailable(
settings.agents[i],
settings.store.timezone
) &&
settings.agents[i].enabled
) {
return settings.agents[i];
}
}
return null;
}
function getAgentAvatarUrl(agent) {
switch (agent.avatarId) {
case 1:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Male-1.png?770";
case 2:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Male-2.png?770";
case 3:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Female-1.png?770";
case 4:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Female-2.png?770";
case 5:
return agent.avatarUrl;
default:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Male-1.png?770";
}
}
function getMultipleAgents(settings, current_device_type, customStyle = "") {
var multiplecs = document.createElement("div");
multiplecs.className = "wa-chat-multiple-cs";
multiplecs.id = "wa-chat-multiple-cs";
if (settings.greeting.shuffleAgents) {
settings.agents = shuffle(settings.agents);
}
for (var i = 0; i < settings.agents.length; i++) {
if (!settings.agents[i].enabled) {
continue;
}
if (
!isAgentCurrentlyAvailable(settings.agents[i], settings.store.timezone)
) {
continue;
}
var agent = document.createElement("div");
agent.className = "list-cs";
var agentAvatar = document.createElement("div");
agentAvatar.innerHTML = `
";
agent.appendChild(agentProfile);
var message = getFinalWhatsappMsg(settings);
var link = getWhatsappLink(
settings.agents[i].phone,
message,
current_device_type
);
agent.onclick = OptinViaChatWidget(settings, link, settings.agents[i].id);
multiplecs.appendChild(agent);
}
return multiplecs;
}
function shuffle(array) {
var currentIndex = array.length,
temporaryValue,
randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function OptinViaChatWidget(settings, link, agent_id) {
var _originalSize =
$splmn_jQuery(window).width() + $splmn_jQuery(window).height();
return function () {
localStorage.setItem("from_greetings", 1);
localStorage.setItem(
"agent_details",
JSON.stringify({
agent_id: agent_id ? agent_id : null,
link: link,
})
);
loadOptinWidgetViaChat(settings, _originalSize);
};
}
function getWhatsappLink(phone, message, current_device_type) {
var link = "";
var IOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (current_device_type == 2) {
link = "https://web.whatsapp.com/send?text=" + message;
} else if (current_device_type == 1 && !IOS) {
link = "whatsapp://send?text=" + message;
} else if (current_device_type == 1 && IOS) {
link = "https://api.whatsapp.com/send?text=" + message;
}
if (phone) {
link += "&phone=" + phone;
}
return link;
}
function onChatInitiated(settings, agent_id) {
const shop_id = getShopId();
$splmn_jQuery.ajax({
url: SERVER_BASE_URL_ANALYTICS + "/chat",
type: "POST",
data: {
url: shop_id,
},
});
var ga = window.ga;
// fire the GA event.
if (
settings.is_google_analytics_enabled &&
ga &&
typeof ga === "function"
) {
ga("send", {
hitType: "event",
eventCategory: settings.google_analytics_event_category,
eventAction: settings.google_analytics_event_action,
eventLabel: settings.google_analytics_event_label,
});
}
var fbq = window.fbq;
// fire the Fb pixel event.
if (settings.is_facebook_pixel_enabled && fbq) {
fbq("track", settings.fb_pixel_event_name, {});
}
}
function openInNewTab(href) {
logWithBadge("Open In New Tab Attempted");
Object.assign(document.createElement("a"), {
target: "_blank",
href: href,
}).click();
}
function checkCalloutCardVisibilityTiming(
settings,
current_device_type,
calloutCard,
style,
url
) {
if (localStorage.callout_card_last_shown) {
if (
Date.now() -
JSON.parse(localStorage.getItem("callout_card_last_shown")) >=
settings.callout.timeDelay * 1000
) {
showCalloutCard(settings, current_device_type, calloutCard, style, url);
}
} else {
showCalloutCard(settings, current_device_type, calloutCard, style, url);
}
}
function showCalloutCard(
settings,
current_device_type,
calloutCard,
style,
url
) {
setTimeout(function () {
if ($splmn_jQuery("#wa-chat-btn-root").is(":visible")) {
document.body.appendChild(calloutCard);
if (settings.callout.notification) {
playSound(url);
}
let whatsAppBtnHeigth = document.getElementById("wa-chat-btn-root")
? document.getElementById("wa-chat-btn-root").clientHeight
: 0;
let bottomOffset =
Number(getHeightOffset(current_device_type, settings)) +
whatsAppBtnHeigth +
12;
setTimeout(function () {
style.innerHTML +=
".animate-callout-card { bottom: " + bottomOffset + "px;}";
document.head.appendChild(style);
calloutCard.classList.add("animate-callout-card");
}, 400);
}
localStorage.setItem(
"callout_card_last_shown",
JSON.stringify(Date.now())
);
}, settings.callout.delay * 1000);
}
function playSound(url) {
if (!document.getElementById("superlemon-iframe")) {
var i = document.createElement("iframe");
i.src =
"https://cdn.shopify.com/s/files/1/0070/3666/5911/files/silence.mp3?1304";
i.allow = "autoplay";
i.id = "audio";
i.style = "display:none";
i.id = "superlemon-iframe";
document.body.appendChild(i);
}
var a = document.createElement("audio");
a.setAttribute("autoplay", "");
a.innerHTML = '';
}
/*=======================*/
/* WhatsApp Share Button */
/*=======================*/
function createWhatsappShareBtn(settings) {
var current_device_type = deviceType();
var settingsDeviceType = getDeviceTypeFromSettings(settings, "share");
if (
settings.shareButton.enabled &&
(settingsDeviceType & current_device_type) != 0 &&
isShareBtnVisible(settings)
) {
var d = document.createElement("div");
d.className = "wa-share-btn-container";
let shareButton = settings.shareButton;
var textColorStr = "";
var bgColor1 = shareButton.colors.bg[0];
var bgColor2 = shareButton.colors.bg[1];
var iconColor = shareButton.colors.icon || "#ffffff";
if (shareButton.colors.custom) {
if (shareButton.colors.solidBg) {
d.style = `background: ${bgColor1 || "#22ce5b"}`;
} else {
d.style = `background-image: linear-gradient(90deg, ${bgColor1} 0%, ${bgColor2} 100%);`;
}
textColorStr = `color: ${shareButton.colors.text || "#ffffff"}`;
}
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".wa-share-btn-z-index { z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.share
: settings.devices.desktop.zindex.share) +
";}";
var verticalOffsetShare =
current_device_type === 1
? settings.devices.mobile.verticalOffsetShare
: settings.devices.desktop.verticalOffsetShare;
style.innerHTML += ` .wa-splmn-share-btn-offset {${
verticalOffsetShare > 88
? `top: calc(100% - ${verticalOffsetShare}%); bottom: unset;`
: `bottom: ${verticalOffsetShare}%;`
} }`;
document.head.appendChild(style);
d.className +=
" wa-share-btn-pos-" +
getButtonPosition(current_device_type, settings, "share");
d.className +=
" " +
getShareButtonTheme(shareButton.buttonId) +
" " +
"wa-share-btn-z-index" +
" " +
"wa-share-btn-theme-" +
shareButton.buttonId;
d.className += " wa-splmn-share-btn-offset";
var img_url = getShareButtonImg(shareButton.buttonId);
var imgStr = ``;
if (shareButton.colors.custom) {
imgStr = ``;
}
d.innerHTML +=
'
' +
shareButton.cta +
"
" +
imgStr;
var message = getFinalWhatsappShareMsg(settings);
var link = getWhatsappLink(null, message, current_device_type);
d.onclick = onShareBtnClick(link);
document.body.appendChild(d);
}
}
function isShareBtnVisible(settings) {
let showOnPages = settings.shareButton.showOnPages;
if (
(window.ShopifyAnalytics &&
window.ShopifyAnalytics.meta &&
window.ShopifyAnalytics.meta.page &&
window.ShopifyAnalytics.meta.page.pageType !== undefined
? window.ShopifyAnalytics &&
window.ShopifyAnalytics.meta &&
window.ShopifyAnalytics.meta.page &&
window.ShopifyAnalytics.meta.page.pageType === "home"
: window.location.pathname === "/") &&
showOnPages &&
!showOnPages.includes("HOME")
) {
return false;
} else if (
isCollectionsPage() &&
showOnPages &&
!showOnPages.includes("COLLECTION")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/products/(.*)") ||
window.location.pathname.match("(.*)/products")) &&
showOnPages &&
!showOnPages.includes("PRODUCT")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/cart/(.*)") ||
window.location.pathname.match("(.*)/cart")) &&
!(
(deviceType() === 2 &&
showOnPages &&
showOnPages.includes("CART_DESKTOP")) ||
(deviceType() === 1 && showOnPages.includes("CART_MOBILE"))
)
) {
return false;
} else if (
(window.location.pathname.match("(.*)/orders/(.*)") ||
window.location.pathname.match("(.*)/orders") ||
window.location.pathname.match("(.*)/checkouts/(.*)")) &&
showOnPages &&
!showOnPages.includes("THANKYOU")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/blogs/(.*)") ||
window.location.pathname.match("(.*)/blogs")) &&
showOnPages &&
!showOnPages.includes("BLOGPOST")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/pages/(.*)") ||
window.location.pathname.match("(.*)/pages")) &&
showOnPages &&
!showOnPages.includes("PAGE")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/account/(.*)") ||
window.location.pathname.match("(.*)/account")) &&
showOnPages &&
!showOnPages.includes("ACCOUNT")
) {
return false;
} else {
return true;
}
}
function getShareButtonTheme(template_id) {
switch (template_id) {
case 1:
return "wa-share-btn-tmpl-regular";
case 2:
return "wa-share-btn-tmpl-inverted";
case 3:
return "wa-share-btn-tmpl-black-regular";
case 4:
return "wa-share-btn-tmpl-black-inverted";
case 5:
return "wa-share-btn-tmpl-old";
}
}
function getShareButtonImg(template_id) {
switch (template_id) {
case 1:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/new_logo_1_0226a498-7303-4b41-a78c-cc5d9c1db062.png?463";
case 2:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/image_2.6.png?463";
case 3:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/112_2.png?825";
case 4:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/113.png?819";
case 5:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/image_6.4.png?816";
default:
return "https://cdn.shopify.com/s/files/1/0070/3666/5911/files/Group.svg?v=1583716483";
}
}
function getFinalWhatsappShareMsg(settings) {
return (
encodeURIComponent(window.location.href.split("?")[0]) +
"%0A%0A" +
encodeURIComponent(settings.shareButton.shareMessage)
);
}
function onShareBtnClick(link) {
return function () {
const shop_id = getShopId();
$splmn_jQuery.ajax({
url: SERVER_BASE_URL_ANALYTICS + "/share",
type: "POST",
data: {
url: shop_id,
},
});
openInNewTab(link);
};
}
/*=======================*/
/* Spin The Wheel Button */
/*=======================*/
function getSpinSpecialDiscountUnlocked(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Special discount unlocked";
case "ARABIC":
return "خصم خاص مفتوح";
case "DUTCH":
return "Speciale korting ontgrendeld";
case "FRENCH":
return "Remise spéciale débloqué";
case "GERMAN":
return "Sonderrabatt freigeschaltet";
case "HEBREW":
return "הנחה מיוחדת לא נעולה";
case "PORTUGUESE":
return "Desconto especial desbloqueado";
case "RUSSIAN":
return "Специальная скидка разблокирована";
case "SPANISH":
return "Descuento especial desbloqueado";
case "TURKISH":
return "Özel indirim kilidi açıldı";
case "INDONESIAN":
return "Diskon Khusus Tidak Terkunci";
case "ITALIAN":
return "Sconto speciale sbloccato";
default:
return "Special discount unlocked";
}
}
function getSpinTheWheel(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Spin the Wheel";
case "ARABIC":
return "تدور العجلة";
case "DUTCH":
return "Draai het wiel";
case "FRENCH":
return "Tourne la roue";
case "GERMAN":
return "Drehe das Rad";
case "HEBREW":
return "סובב את הגלגל";
case "PORTUGUESE":
return "Gire a roda";
case "RUSSIAN":
return "Поверните колесо";
case "SPANISH":
return "Gira la rueda";
case "TURKISH":
return "Tekerleği döndür";
case "INDONESIAN":
return "Putar rodanya";
case "ITALIAN":
return "Gira la ruota";
default:
return "Spin the Wheel";
}
}
function getSpinWheelGameRules(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return `
Rules:
You can spin the wheel only once
If you win, you can claim the coupon
`;
case "ARABIC":
return `
قواعد:
يمكنك تدوير العجلة مرة واحدة فقط
إذا فزت ، يمكنك المطالبة بالقسيمة
`;
case "DUTCH":
return `
Reglement:
U kunt het wiel slechts eenmaal draaien
Als u wint, kunt u de coupon claimen
`;
case "FRENCH":
return `
Règles:
Vous ne pouvez faire tourner la roue qu'une seule fois
Si vous gagnez, vous pouvez réclamer le coupon
`;
case "GERMAN":
return `
Regeln
Sie können das Rad nur einmal drehen
Wenn Sie gewinnen, können Sie den Gutschein beanspruchen
`;
case "HEBREW":
return `
כללים:
אתה יכול לסובב את הגלגל רק פעם אחת
אם אתה מנצח, אתה יכול לתבוע את הקופון
`;
case "PORTUGUESE":
return `
Regras:
Você pode girar a roda apenas uma vez
Se você vencer, você pode reivindicar o cupom
`;
case "RUSSIAN":
return `
Правила:
Вы можете крутить колесо только один раз
Если вы выиграете, вы можете требовать купона
`;
case "SPANISH":
return `
Normas:
Puedes girar la rueda solo una vez
Si gana, puede reclamar el cupón
`;
case "TURKISH":
return `
Tüzük:
Tekerleği yalnızca bir kez döndürebilirsiniz
Kazanırsanız, kuponu talep edebilirsiniz
`;
case "INDONESIAN":
return `
Aturan:
Anda hanya dapat memutar roda sekali
Jika Anda menang, Anda dapat mengklaim kuponnya
`;
case "ITALIAN":
return `
Regole:
Puoi girare la ruota solo una volta
Se vinci, puoi richiedere il coupon
`;
default:
return `
Rules:
You can spin the wheel only once
If you win, You can claim the coupon
`;
}
}
function getYayYouWillGet(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Yay!! you will get";
case "ARABIC":
return "ياي!! ستحصل";
case "DUTCH":
return "Ja !! je zult krijgen";
case "FRENCH":
return "Yay!! tu auras";
case "GERMAN":
return "Yay!! Sie erhalten";
case "HEBREW":
return "יש!! אתה תקבל";
case "PORTUGUESE":
return "Yay!! você vai ter";
case "RUSSIAN":
return "Ура!! ты получишь";
case "SPANISH":
return "¡¡Hurra!! conseguirás";
case "TURKISH":
return "Yay!! Alacaksın";
case "INDONESIAN":
return "Yay !! kamu akan mendapatkan";
case "ITALIAN":
return "Sìì!! otterrete";
default:
return "Yay!! you will get";
}
}
function getWeAllSendTheDiscountCode(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "We’ll send the discount code on your WhatsApp number";
case "ARABIC":
return "سنرسل رمز الخصم على رقم WhatsApp الخاص بك";
case "DUTCH":
return "We sturen de kortingscode op uw WhatsApp -nummer";
case "FRENCH":
return "Nous enverrons le code de réduction sur votre numéro WhatsApp";
case "GERMAN":
return "Wir senden den Rabattcode auf Ihre WhatsApp -Nummer";
case "HEBREW":
return "אנו נשלח את קוד ההנחה במספר WhatsApp שלך";
case "PORTUGUESE":
return "Enviaremos o código de desconto no seu número do WhatsApp";
case "RUSSIAN":
return "Мы отправим код скидки на ваш номер WhatsApp";
case "SPANISH":
return "Enviaremos el código de descuento en su número de WhatsApp";
case "TURKISH":
return "WhatsApp numaranızda indirim kodunu göndereceğiz";
case "INDONESIAN":
return "Kami akan mengirimkan kode diskon pada nomor whatsapp Anda";
case "ITALIAN":
return "Invieremo il codice di sconto sul tuo numero di whatsapp";
}
}
function getSpinGetTheDiscountCode(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Get the Discount Code";
case "ARABIC":
return "احصل على رمز الخصم";
case "DUTCH":
return "Ontvang de kortingscode";
case "FRENCH":
return "Obtenez le code de réduction";
case "GERMAN":
return "Holen Sie sich den Rabattcode";
case "HEBREW":
return "קבל את קוד ההנחה";
case "PORTUGUESE":
return "Obtenha o código de desconto";
case "RUSSIAN":
return "Получите код скидки";
case "SPANISH":
return "Obtenga el código de descuento";
case "TURKISH":
return "İndirim Kodunu Alın";
case "INDONESIAN":
return "Dapatkan Kode Diskon";
case "ITALIAN":
return "Ottieni il codice di sconto";
default:
return "Get the Discount Code";
}
}
function getSpinYouWin(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "You win!";
case "ARABIC":
return "فزت!";
case "DUTCH":
return "Jij wint!";
case "FRENCH":
return "Vous gagnez!";
case "GERMAN":
return "Du gewinnst!";
case "HEBREW":
return "ניצחת!";
case "PORTUGUESE":
return "Você ganha!";
case "RUSSIAN":
return "Ты победил!";
case "SPANISH":
return "¡Tú ganas!";
case "TURKISH":
return "Sen kazandın!";
case "INDONESIAN":
return "Kamu menang!";
case "ITALIAN":
return "Hai vinto!";
default:
return "You win!";
}
}
function getSpinYourCouponCodeIs(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Your Coupon code is:";
case "ARABIC":
return "رمز القسيمة الخاص بك هو:";
case "DUTCH":
return "Uw couponcode is:";
case "FRENCH":
return "Votre code de coupon est:";
case "GERMAN":
return "Ihr Gutscheincode lautet:";
case "HEBREW":
return "קוד הקופון שלך הוא:";
case "PORTUGUESE":
return "Seu código de cupom é:";
case "RUSSIAN":
return "Ваш код купона:";
case "SPANISH":
return "Su código de cupón es:";
case "TURKISH":
return "Kupon kodunuz:";
case "INDONESIAN":
return "Kode kupon Anda adalah:";
case "ITALIAN":
return "Il tuo codice coupon è:";
default:
return "Your Coupon code is:";
}
}
function getSpinCopyCouponCode(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Copy coupon code";
case "ARABIC":
return "نسخ رمز القسيمة";
case "DUTCH":
return "Kopieer couponcode";
case "FRENCH":
return "Copier le code de coupon";
case "GERMAN":
return "Couponcode kopieren";
case "HEBREW":
return "העתק קוד קופון";
case "PORTUGUESE":
return "Copie o código do cupom";
case "RUSSIAN":
return "Копировать код купона";
case "SPANISH":
return "Copiar código de cupón";
case "TURKISH":
return "Kupon Kodunu Kopyala";
case "INDONESIAN":
return "Salin kode kupon";
case "ITALIAN":
return "Copia il codice coupon";
default:
return "Copy coupon code";
}
}
function getSpinWeHaveAlsoSentTheCouponCodeOnYourNumber(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "We have also sent the coupon code on your number";
case "ARABIC":
return "لقد أرسلنا أيضًا رمز القسيمة على رقمك";
case "DUTCH":
return "We hebben ook de couponcode op uw nummer verzonden";
case "FRENCH":
return "Nous avons également envoyé le code de coupon sur votre numéro";
case "GERMAN":
return "Wir haben auch den Gutscheincode auf Ihre Nummer gesendet";
case "HEBREW":
return "שלחנו גם את קוד הקופון על המספר שלך";
case "PORTUGUESE":
return "Também enviamos o código do cupom em seu número";
case "RUSSIAN":
return "Мы также отправили код купона на ваш номер";
case "SPANISH":
return "También hemos enviado el código de cupón en su número";
case "TURKISH":
return "Numaranızda kupon kodunu da gönderdik";
case "INDONESIAN":
return "Kami juga telah mengirim kode kupon di nomor Anda";
case "ITALIAN":
return "Abbiamo anche inviato il codice coupon sul tuo numero";
default:
return "We have also sent the coupon code on your number";
}
}
function getSpinYouAlmostWin(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "You almost win!";
case "ARABIC":
return "لقد فزت تقريبا!";
case "DUTCH":
return "Je wint bijna!";
case "FRENCH":
return "Vous gagnez presque!";
case "GERMAN":
return "Sie gewinnen fast!";
case "HEBREW":
return "אתה כמעט מנצח!";
case "PORTUGUESE":
return "Você quase vence!";
case "RUSSIAN":
return "Вы почти выигрываете!";
case "SPANISH":
return "¡Casi ganas!";
case "TURKISH":
return "Neredeyse kazanıyorsun!";
case "INDONESIAN":
return "Anda hampir menang!";
case "ITALIAN":
return "Quasi vinci!";
default:
return "You almost win!";
}
}
function getSpinBetterLuckNextTime(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Better luck next time";
case "ARABIC":
return "حظ أوفر في المرة القادمة";
case "DUTCH":
return "Volgende keer beter";
case "FRENCH":
return "Plus de chance la prochaine fois";
case "GERMAN":
return "Mehr Glück beim nächsten Mal";
case "HEBREW":
return "בהצלחה בפעם הבאה";
case "PORTUGUESE":
return "Mais sorte da próxima vez";
case "RUSSIAN":
return "Повезет в следующий раз";
case "SPANISH":
return "Mejor suerte la próxima vez";
case "TURKISH":
return "Bir dahaki sefere daha iyi şanslar";
case "INDONESIAN":
return "Semoga lain kali lebih beruntung";
case "ITALIAN":
return "La prossima volta sarai più fortunato";
default:
return "Better luck next time";
}
}
function getSpinBtnClose(SpinWidgetLanguage) {
switch (SpinWidgetLanguage) {
case "ENGLISH":
return "Close";
case "ARABIC":
return "قريب";
case "DUTCH":
return "Dichtbij";
case "FRENCH":
return "proche";
case "GERMAN":
return "Nah dran";
case "HEBREW":
return "סגור";
case "PORTUGUESE":
return "Perto";
case "RUSSIAN":
return "Закрывать";
case "SPANISH":
return "Cerca";
case "TURKISH":
return "Kapat";
case "INDONESIAN":
return "Menutup";
case "ITALIAN":
return "Chiudere";
default:
return "Close";
}
}
function createSpinTheWheelBtn(settings) {
var current_device_type = deviceType();
var settingsDeviceType = getDeviceTypeFromSettings(settings, "spinWheel");
if (
settings &&
settings.spinWheel &&
settings.spinWheel.is_wheel_enabled &&
settings.spinWheel.wheelData &&
settings.spinWheel.wheelData.length > 0 &&
(settingsDeviceType & current_device_type) != 0 &&
isSpinBtnVisible(settings)
) {
spinWheelInitConfig.list = settings.spinWheel.wheelData;
spinWheelInitConfig.wheelId = settings.spinWheel.wheelId;
// spin-wheel-btn-container
var spinWheelBtnElement = document.createElement("div");
spinWheelBtnElement.id = "spinwheel-btn-root";
let spinWheelButton = settings.spinWheel;
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
var wheelVerticalOffset =
current_device_type === 1
? settings.devices.mobile.wheelVerticalOffset
: settings.devices.desktop.wheelVerticalOffset;
var wheelHorizontalOffset =
current_device_type === 1
? settings.devices.mobile.wheelHorizontalOffset
: settings.devices.desktop.wheelHorizontalOffset;
var spinWheelBtnPos = getButtonPosition(
current_device_type,
settings,
"spinWheel"
);
style.innerHTML =
".spin-wheel-splmn-btn-offset {" +
"bottom: " +
wheelVerticalOffset +
"px;" +
spinWheelBtnPos +
":" +
wheelHorizontalOffset +
"px;" +
"z-index:" +
(current_device_type === 1
? settings.devices.mobile.zindex.spinWheel
: settings.devices.desktop.zindex.spinWheel) +
";}";
document.head.appendChild(style);
spinWheelBtnElement.className +=
"spin-wheel-btn-fixed spin-wheel-splmn-btn-offset";
var img_url =
"https://cdn.shopify.com/s/files/1/0449/7794/6790/files/spin-wheel.svg?v=1658384655";
var imgStr = ``;
spinWheelBtnElement.innerHTML += imgStr;
spinWheelBtnElement.onclick = function () {
const shop_id = getShopId();
$splmn_jQuery.ajax({
url: SERVER_BASE_URL_ANALYTICS + "/spinwheel",
type: "POST",
data: {
url: shop_id,
},
});
loadSpinWheelWidget(settings, current_device_type);
};
document.body.appendChild(spinWheelBtnElement);
}
}
function isSpinBtnVisible(settings) {
let wheelPages = settings.spinWheel.wheelPages;
if (
window.location.pathname === "/" &&
wheelPages &&
!wheelPages.includes("HOME")
) {
return false;
} else if (
isCollectionsPage() &&
wheelPages &&
!wheelPages.includes("COLLECTION")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/products/(.*)") ||
window.location.pathname.match("(.*)/products")) &&
wheelPages &&
!wheelPages.includes("PRODUCT")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/cart/(.*)") ||
window.location.pathname.match("(.*)/cart")) &&
!(
(deviceType() === 2 &&
wheelPages &&
wheelPages.includes("CART_DESKTOP")) ||
(deviceType() === 1 && wheelPages.includes("CART_MOBILE"))
)
) {
return false;
} else if (
(window.location.pathname.match("(.*)/orders/(.*)") ||
window.location.pathname.match("(.*)/orders") ||
window.location.pathname.match("(.*)/checkouts/(.*)")) &&
wheelPages &&
!wheelPages.includes("THANKYOU")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/blogs/(.*)") ||
window.location.pathname.match("(.*)/blogs")) &&
wheelPages &&
!wheelPages.includes("BLOGPOST")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/pages/(.*)") ||
window.location.pathname.match("(.*)/pages")) &&
wheelPages &&
!wheelPages.includes("PAGE")
) {
return false;
} else if (
(window.location.pathname.match("(.*)/account/(.*)") ||
window.location.pathname.match("(.*)/account")) &&
wheelPages &&
!wheelPages.includes("ACCOUNT")
) {
return false;
} else {
return true;
}
}
function getSpinWheelCloseBtn() {
var closeBtn = document.createElement("div");
closeBtn.className = "spinwheel-bubble-close-btn";
closeBtn.innerHTML =
'';
closeBtn.onclick = function () {
// new bouncedown greeting widget animation
$splmn_jQuery("#spinwheel-bubble").removeClass("bounceUp");
$splmn_jQuery("#spinwheel-bubble").addClass("bounceDown");
$splmn_jQuery("#spinwheel-btn-root").show();
};
return closeBtn;
}
function loadSpinWheelWidget(settings, current_device_type) {
if ($splmn_jQuery("#spinwheel-bubble").length) {
$splmn_jQuery("#spinwheel-bubble").show();
$splmn_jQuery("#spinwheel-bubble").removeClass("bounceDown");
$splmn_jQuery("#spinwheel-bubble").addClass("bounceUp");
$splmn_jQuery("#spinwheel-btn-root").hide();
return;
}
// Spin Widget Language
var SpinWidgetLanguage =
settings && settings.spinWheel && settings.spinWheel.language
? settings.spinWheel.language
: "ENGLISH";
// bubble
var spinWheelBubbleElement = document.createElement("div");
spinWheelBubbleElement.id = "spinwheel-bubble";
if (deviceType() != 1) {
// spinWheelBubbleElement.style = `height: ${75 / 100 * screen.height}px`;
}
//zindex from settings
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".spinwheel-widget-z-index { z-index:" +
(current_device_type === 2
? "100000 !important"
: settings.devices.desktop.zindex.spinWheel) +
";}";
document.head.appendChild(style);
var spinWheelBtnPos = getButtonPosition(
current_device_type,
settings,
"spinWheel"
);
spinWheelBubbleElement.className =
"spinwheel-bubble-floating-popup wa_animated spinwheel-widget-z-index spinwheel-bubble-pos-" +
spinWheelBtnPos;
var header = document.createElement("div");
header.className = "spinwheel-bubble-header";
header.appendChild(getSpinWheelCloseBtn());
// spin wheel widget container
var spinWheelWidgetContainer = document.createElement("div");
spinWheelWidgetContainer.className = "spinwheel-bubble-widget-container";
// spin wheel left side starts
let canvasSize = spinWheelInitConfig.canvasSize;
var wheelOfFortuneDiv = document.createElement("div");
wheelOfFortuneDiv.id = "wheel-of-fortune";
if (deviceType() == 1) {
wheelOfFortuneDiv.classList = `spinWheelBottom`;
}
wheelOfFortuneDiv.appendChild(createSpinWheelCanvas(settings));
// spin wheel left side ends
// right side starts
var widgetInfoDiv = document.createElement("div");
widgetInfoDiv.id = "spin-wheel-info";
var gameStatusTxt = document.createElement("h1");
gameStatusTxt.className = "game-status-txt";
gameStatusTxt.innerHTML =
getSpinSpecialDiscountUnlocked(SpinWidgetLanguage);
var spinTheWheelBtn = document.createElement("button");
spinTheWheelBtn.innerHTML = getSpinTheWheel(SpinWidgetLanguage);
spinTheWheelBtn.onclick = () =>
onSpinWheelBtnClick(SpinWidgetLanguage, spinTheWheelBtn);
var gameRules = document.createElement("div");
gameRules.classList = "spin-wheel-game-rules";
gameRules.innerHTML = getSpinWheelGameRules(SpinWidgetLanguage);
widgetInfoDiv.append(gameStatusTxt, spinTheWheelBtn, gameRules);
spinWheelWidgetContainer.append(wheelOfFortuneDiv, widgetInfoDiv);
spinWheelBubbleElement.append(header, spinWheelWidgetContainer);
document.body.appendChild(spinWheelBubbleElement);
$splmn_jQuery("#spinwheel-bubble").addClass("bounceUp");
$splmn_jQuery("#spinwheel-btn-root").hide();
createSpinWheelSectors(settings);
}
function createSpinWheelCanvas(settings) {
var spinWheelWidget = document.createElement("div");
let canvasSize = spinWheelInitConfig.canvasSize;
// spinWheelWidget.style = `width: ${canvasSize}px; height: ${deviceType() === 1 ? "50%" : canvasSize + "px"}; position: relative;`;
var spinWheelSelectorImg =
"https://cdn.shopify.com/s/files/1/0449/7794/6790/files/location-pin.png?v=1658384655";
let top = canvasSize;
let tempStyle =
deviceType() !== 1 ? `style="top: ${top}px;right:-${50}%;"` : "";
spinWheelWidget.innerHTML = `
`;
return spinWheelWidget;
}
function createSpinWheelSectors(settings) {
// determine number/size of sectors that need to created
let numOptions = settings.spinWheel.wheelData.length;
let arcSize = (2 * Math.PI) / numOptions;
// save to config
spinWheelInitConfig.angle = arcSize;
// dynamically generate sectors from state list
let angle = 0;
for (var x = 0; x < numOptions; x++) {
let { text, color } = settings.spinWheel.wheelData[x];
renderSpinWheelSector(x + 1, text, angle, arcSize, color);
angle += arcSize;
}
renderSpinWheelCircle();
renderSpinWheelCenterCircle();
}
function renderSpinWheelCenterCircle() {
let c = document.getElementById("spin-wheel-canvas");
let ctx = c.getContext("2d");
ctx.beginPath();
let arcX_Y = spinWheelInitConfig.canvasSize / 2;
ctx.arc(
arcX_Y,
arcX_Y,
percentToPx(deviceType() == 1 ? 8 : 2),
0,
2 * Math.PI
);
ctx.lineWidth = deviceType() == 1 ? 40 : 20;
ctx.fillStyle = "white";
ctx.shadowBlur = 5;
ctx.shadowColor = "gray";
ctx.fill();
}
function renderSpinWheelCircle() {
let c = document.getElementById("spin-wheel-canvas");
let ctx = c.getContext("2d");
ctx.beginPath();
let arcX_Y = spinWheelInitConfig.canvasSize / 2;
ctx.arc(arcX_Y, arcX_Y, spinWheelInitConfig.radius * 2, 0, 2 * Math.PI);
ctx.lineWidth = 5;
ctx.strokeStyle = "white";
ctx.shadowBlur = 5;
ctx.shadowColor = "#A9A9A9";
ctx.strokeStyle = "white";
ctx.stroke();
}
function renderSpinWheelSector(index, text, start, arc, color) {
// create canvas arc for each list element
let canvas = document.getElementById("spin-wheel-canvas");
let ctx = canvas.getContext("2d");
let x = (y = canvas.width / 2);
let radius = spinWheelInitConfig.radius;
let startAngle = start;
let endAngle = start + arc;
let angle = index * arc;
let baseSize = radius * (deviceType() == 1 ? 2.05 : 2.1);
let textRadius = baseSize - radius;
ctx.beginPath();
ctx.arc(x, y, radius, startAngle, endAngle, false);
ctx.lineWidth = radius * 2;
ctx.strokeStyle = color;
ctx.fillStyle =
parseInt(spinWheelInitConfig.wheelId) === 9 || index % 2 === 0
? "black"
: "white";
ctx.shadowBlur = 1;
ctx.shadowColor =
parseInt(spinWheelInitConfig.wheelId) === 9 || index % 2 === 0
? "black"
: "white";
ctx.stroke();
ctx.save();
ctx.translate(
baseSize + Math.cos(angle - arc / 2) * textRadius,
baseSize + Math.sin(angle - arc / 2) * textRadius
);
ctx.rotate(angle - arc / 1.9);
let alignPosition = 90;
if (text.length <= 5) {
ctx.font = `700 ${parseInt(
spinWheelInitConfig.canvasSize * 0.042
)}px Arial `;
ctx.fillText(text, -parseInt(spinWheelInitConfig.canvasSize * 0.05), 0);
} else if (text.length > 20) {
ctx.font = `700 ${parseInt(
spinWheelInitConfig.canvasSize * 0.025
)}px Arial `;
ctx.fillText(text, -parseInt(spinWheelInitConfig.canvasSize * 0.16), 0);
} else if (text.length > 15) {
ctx.font = `700 ${parseInt(
spinWheelInitConfig.canvasSize * 0.032
)}px Arial `;
ctx.fillText(text, -parseInt(spinWheelInitConfig.canvasSize * 0.16), 0);
} else if (text.length > 10) {
ctx.font = `700 ${parseInt(
spinWheelInitConfig.canvasSize * 0.038
)}px Arial `;
ctx.fillText(text, -parseInt(spinWheelInitConfig.canvasSize * 0.15), 0);
} else if (text.length > 5) {
ctx.font = `700 ${parseInt(
spinWheelInitConfig.canvasSize * 0.04
)}px Arial `;
ctx.fillText(text, -parseInt(spinWheelInitConfig.canvasSize * 0.1), 0);
}
ctx.textAlign = "center";
ctx.restore();
}
function onSpinWheelBtnClick(SpinWidgetLanguage, spinTheWheelBtn) {
spinTheWheelBtn.disabled = true;
$splmn_jQuery(this).attr("disabled", true);
localStorage.setItem("spin_the_wheel", true);
const shop_id = getShopId();
$splmn_jQuery.ajax({
url: SERVER_BASE_URL_ANALYTICS + "/wheelspin",
type: "POST",
data: {
url: shop_id,
},
});
// set random spin degree and ease out time
// set state variables to initiate animation
let randomSpin =
Math.floor(Math.random() * 900) + 500 + spinWheelInitConfig.rotate;
spinWheelInitConfig["rotate"] = randomSpin;
spinWheelInitConfig["easeOut"] = 2;
spinWheelInitConfig["spinning"] = true;
$splmn_jQuery("#spin-wheel-canvas").css({
transform: `rotate(${randomSpin}deg)`,
transition: `-webkit-transform ${2}s ease-out 0s`,
});
// calcalute result after wheel stops spinning
setTimeout(() => {
getSpinWheelResult(randomSpin, SpinWidgetLanguage);
}, 2000);
}
function getSpinWheelResult(spin, SpinWidgetLanguage) {
const { list } = spinWheelInitConfig;
let num = list.length;
let toPassOne = 360 / list.length;
let actualPass = 0;
let isMobile = deviceType();
// add 90 degree if mobile
let degreeToAdd = isMobile === 1 ? 90 : 0;
if (spin > 360) {
actualPass = (spin + degreeToAdd) % 360;
} else {
actualPass = spin + degreeToAdd;
}
let temp = actualPass / toPassOne;
let ans = Math.floor(num + 1 - temp);
let result = ans - 1;
// set state variable to display result
spinWheelInitConfig["result"] = result;
handleSpinWheelResult(
list[result].code.length > 0 ? "WIN" : "LOOSE",
SpinWidgetLanguage
);
}
function renderNumberInputForm(SpinWidgetLanguage) {
let winResult = spinWheelInitConfig.list[spinWheelInitConfig.result];
$splmn_jQuery("#spin-wheel-info").html(`