Free javascript Hosting


popups.js

Uploaded on Nov 24 2021 11:34 by kunjan.nshah1

var indexOfwww = location.hostname.indexOf("www");
var fbLoggedInStatus = "unknown";
var shopDomainStripped = (indexOfwww === -1) ? "." + location.hostname : location.hostname.substr(indexOfwww + 3);
var globalShopUrl = (indexOfwww === -1) ? location.hostname : location.hostname.substr(indexOfwww + 4);
(function () {
try {
function loadScript(url, callback, async = true, defer = false, id = "") {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = async;
script.defer = defer;
script.id = id;
if (script.readyState) {
// IE
script.onreadystatechange = function () {
if (
script.readyState == "loaded" ||
script.readyState == "complete"
) {
script.onreadystatechange = null;

callback();
}
};
} else {
// Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
statusChangeCallback = async (response) => {
if (response.status === "connected") {
//Do real shit
fbLoggedInStatus = true;
// this.testAPI();
} else if (response.status === "not_authorized") {
fbLoggedInStatus = true;
//Show Login Button
// console.log("Please log into this app.");
} else {
fbLoggedInStatus = false;
//Show login button
}
};
function checkLoginState() {
window.FB.getLoginStatus(
function (response) {
if (response.status === "connected") {
//Do real shit
fbLoggedInStatus = true;
// this.testAPI();
} else if (response.status === "not_authorized") {
fbLoggedInStatus = true;
//Show Login Button
// console.log("Please log into this app.");
} else {
fbLoggedInStatus = false;
//Show login button
}
}.bind(this),
true
);
}
// Load the script
function appendAll($) {
$(async() => {
var tempDisplayedPopups = getCookie("displayedPopups");

if (tempDisplayedPopups) {
try {
noRepeat = JSON.parse(tempDisplayedPopups);
} catch (err) {
noRepeat = tempDisplayedPopups;
}
}
console.log("IN APPEND ALLL");
appendCSS();
await renderPopups();
});
}
if (typeof jQuery === "undefined" || parseFloat(jQuery.fn.jquery) < 1.7) {
console.log("1111");
loadScript(
"https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js",
() => {
console.log("1111-1111");
var jQuery191 = jQuery.noConflict(true);
if (typeof FB === "undefined") {
loadScript(
"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js",
() => {
console.log("1111-1111-1111");
window.fbAsyncInit = function () {
console.log("FB INIT CALLED");
FB.init({
appId: "2616438408370023",
autoLogAppEvents: true,
status: true,
cookie: true,
xfbml: true,
version: "v4.0",
});
};
window.FB.Event.subscribe(
"auth.authResponseChange",
statusChangeCallback
);
checkLoginState();
// (function(d, s, id) {
// var js,
// fjs = d.getElementsByTagName(s)[0];
// if (d.getElementById(id)) return;
// js = d.createElement(s);
// js.id = id;
// js.src =
// "https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
// fjs.parentNode.insertBefore(js, fjs);
// })(document, "script", "facebook-jssdk");

appendAll(jQuery191);
},
true,
true,
"facebook-jssdk"
);
} else {
console.log("1111-2222");
window.fbAsyncInit = function () {
console.log("FB INIT CALLED", typeof FB, "typeof FB");
FB.init({
appId: "2616438408370023",
autoLogAppEvents: true,
status: true,
cookie: true,
xfbml: true,
version: "v4.0",
});
};
(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src =
"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
fjs.parentNode.insertBefore(js, fjs);
})(document, "script", "facebook-jssdk");
window.FB.Event.subscribe(
"auth.authResponseChange",
statusChangeCallback
);
checkLoginState();
appendAll(jQuery191);
}
}
);

//WHATSAPP
loadScript('https://cdn.bitespeed.co/whatsapp-snippets/intlTelInput.min.js', () => { console.log('intlTell loaded') });
loadScript('https://cdn.bitespeed.co/whatsapp-snippets/utils.js', () => { console.log('util.js loaded') });
} else {
console.log("2222");
if (typeof FB === "undefined") {
// console.log("IN 3");
// loadScript(
// "https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js",
// () => {
// console.log("IN 3 really");
// $(document).ready(function() {
// function facebookReady() {
// console.log("FACEBOOK READY");
// FB.init({
// appId: "2616438408370023",
// status: true,
// cookie: true,
// xfbml: false,
// version: "v4.0"
// });
// appendAll(jQuery);
// }
// if (window.FB) {
// console.log("CASE 1");
// facebookReady();
// } else {
// console.log("CASE 2");
// window.fbAsyncInit = facebookReady;
// }
// });
// console.log("IM HERE 3");
// },
// true,
// true
// );
console.log("2222-1111");
loadScript(
"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js",
() => {
console.log("FB INIT, below else");
window.fbAsyncInit = function () {
FB.init({
appId: "2616438408370023",
autoLogAppEvents: true,
xfbml: true,
status: true,
cookie: true,
version: "v4.0",
});
};
window.FB.Event.subscribe(
"auth.authResponseChange",
statusChangeCallback
);
checkLoginState();
appendAll(jQuery);
},
true,
true,
"facebook-jssdk"
);
} else {
console.log("2222-2222");
$(document).ready(function () {
console.log("FB INIT, below else, else");
function facebookReady() {
FB.init({
appId: "2616438408370023",
status: true,
cookie: true,
xfbml: true,
version: "v4.0",
});
(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src =
"https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
fjs.parentNode.insertBefore(js, fjs);
})(document, "script", "facebook-jssdk");
window.FB.Event.subscribe(
"auth.authResponseChange",
statusChangeCallback
);
checkLoginState();
appendAll(jQuery);
}

if (window.FB) {
facebookReady();
} else {
window.fbAsyncInit = facebookReady;
}
});
// window.fbAsyncInit = function() {
// console.log("INITING FB 4");
// FB.init({
// appId: "2616438408370023",
// autoLogAppEvents: true,
// xfbml: true,
// version: "v4.0"
// });
// };
}
//WHATSAPP
loadScript('https://cdn.bitespeed.co/whatsapp-snippets/intlTelInput.min.js', () => { console.log('intlTell loaded') });
loadScript('https://cdn.bitespeed.co/whatsapp-snippets/utils.js', () => { console.log('util.js loaded') });
}
} catch (err) {
console.log("ERROR");
console.log(err);
}
})();
let globalPopups;
let globalWAPageId;
let globalPhoneNoObjs = {};
const closedPopups = [];
let globalFinalHtml;
let globalPageId;
var noRepeat = "";
let spaceReplacedDiscountCode;
let discountCode;
let discountText;
let globalDegree;
const popups = {};
function create_UUID() {
var e = (new Date).getTime();
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(t) {
var o = (e + 16 * Math.random()) % 16 | 0;
return e = Math.floor(e / 16), ("x" == t ? o : 3 & o | 8).toString(16)
})
}

function appendCSS() {
console.log("IN APPEND CSS");
var links;
if (window.innerWidth < 768) {
links =
'<link rel="stylesheet" href="https://cdn.bitespeed.co/snippets/bitespeed-popup-mob-min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">';
}
else {
links =
'<link rel="stylesheet" href="https://cdn.bitespeed.co/snippets/bitespeed-popup-min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">';
}
//WHATSAPP
links += ' <link rel="stylesheet" href="https://cdn.bitespeed.co/whatsapp-snippets/demo.css">';
links += ' <link rel="stylesheet" href="https://cdn.bitespeed.co/whatsapp-snippets/intlTelInput.min.css">'
links += ' <link rel="stylesheet" href="https://cdn.bitespeed.co/whatsapp-snippets/bitespeed-wa.css">';
try {
$("head").append(links);
console.log("SUCCESSFULLY APPENDED CSS");
} catch (err) {
console.log("Error while appending CSS ", err);
}
}

function isValidObj(obj) {
if(obj === null || obj === "null" || obj === "" || obj === undefined || obj === "undefined") return false;
return true;
}

function setCookie(name, value) {
document.cookie =
name + "=" + value + ";domain=" + shopDomainStripped + "; path=/";
}

function setCookieWithExpiry(name, value, days) {
let currDate = new Date;
currDate.setTime(currDate.getTime() + 24 * days * 60 * 60 * 1000);
document.cookie =
name + "=" + value + ";expires=" + currDate.toUTCString();
}

function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length == 2) return parts.pop().split(";").shift();
}

function makeid(len) {
var id = [];
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var n = letters.length;
for (let i = 0; i < len; i++) {
id.push(letters.charAt(Math.floor(Math.random() * n)));
}
return id.join("")
}

// generates unique user ID and sets "refb" cookie; Returns uuid
function createRef() {
let uuid = create_UUID();
document.cookie =
"refb=" +
uuid +
";expires=" +
new Date(new Date().setFullYear(new Date().getFullYear() + 10)) +
";domain=" +
shopDomainStripped +
"; path=/";
return uuid;
}

// sends impression to db, updates noRepeat, sets "displayedPopups" cookie
async function sendImpression(impression, id) {
if(!noRepeat.includes(impression)) {
try {
await axios.post("https://app.bitespeed.co/database/api/optinTools/impressions",
{
id,
}
);

noRepeat = noRepeat + "+" + impression;
setCookie("displayedPopups", noRepeat);
//TODO: remove after testing
console.log("IMPRESSION SENT", impression, noRepeat);
} catch (err) {
console.log("Error while sending impression", err);
throw err;
}
}
}

// sends WA text based on shopUrl(language) and display width
function sendWAText(id) {
let text = encodeURIComponent("https://"+window.location.hostname+window.location.pathname + "\n\n"+ globalPopups[id].generalSettings.defaultText);
// handle text in other languages
switch(globalWAPageId) {
case 'dogal-koy-sepetim.myshopify.com': text = encodeURIComponent("Ürünleriniz hakkında detaylı bilgi alabilir miyim ?");
break;
case '2b-eco.myshopify.com': text = encodeURIComponent("Pode me ajudar?");
break;
case 'leginfi.myshopify.com': text = encodeURIComponent("Estoy interesado en este producto y tengo algunas preguntas. ¿Pueden ayudarme?");
break;
}
console.log("Text to be sent ", text);
if (window.innerWidth < 768) {
window.open('https://api.whatsapp.com/send?phone=' + globalPopups[id].generalSettings.supportNumber + "&text=" + text);
console.log("SENT WA TEXT", " device=mobile");
}
else {
window.open('https://web.whatsapp.com/send?phone=' + globalPopups[id].generalSettings.supportNumber + "&text=" + text);
console.log("SENT WA TEXT", " device=desktop");
}
}

// Called when 'send' button of any Opt-in tools is clicked
// collects phoneNo and data, and dispatches new 'message' event
function waHandler(data, id, isChatWidget = false) {
if (isChatWidget) {
console.log("SENDING WA TEXT");
sendWAText(id);
}

let phoneNo = globalPhoneNoObjs[id].getNumber();
phoneNo = phoneNo.replace('+', '');
console.log('THIS IS PHONE NUMBER', phoneNo);

let dataStr = JSON.stringify(data.split('.'));
// TODO: remove after testing
console.log("THIS IS DATA", dataStr);

let event = new CustomEvent("message", {
"detail": {
isWA: true,
data: dataStr,
phoneNo: phoneNo
}
});
window.dispatchEvent(event);
}

function showWAChatWidget(id) {
if(globalPopups[id].generalSettings.collectPhone) {
if ($("#wa-chat-bubble").length) {
$("#wa-chat-bubble").show();
$("#wa-chat-bubble").removeClass("bounceDown");
$("#wa-chat-bubble").addClass("bounceUp");
$("#wa-chat-btn-root").hide();
return;
}
}
else {
sendWAText(id);
}
}

function hideWAChatWidget() {
if($("#wa-chat-btn-root").length) {
$("#wa-chat-btn-root").show();
$("#wa-chat-bubble").addClass("bounceDown");
$("#wa-chat-bubble").removeClass("bounceUp");
$("#wa-chat-bubble").hide();
return;
}
}

// calls the 'popupHtml' lambda function and initializes values of global variable
async function getFinalHtml() {
let uuid = getCookie("refb");
if (isValidObj(uuid)) {
uuid = createRef();
}
// initializes globalDegree variables
globalDegree = 900 + Math.random() * 1080;
// let res = await fetch(
// // `http://localhost:3000/dev/getPopupHtml?shopUrl=${globalShopUrl}&uuid=${uuid}&screenWidth=${window.innerWidth}&spinDegree=${globalDegree}`
// `https://f4sxp72b65.execute-api.us-east-1.amazonaws.com/dev/getPopupHtml?shopUrl=${globalShopUrl}&uuid=${uuid}&screenWidth=${window.innerWidth}&spinDegree=${globalDegree}`,
// {headers: {
// 'Access-Control-Allow-Origin': '*',
// 'Access-Control-Allow-Methods': 'POST',
// 'Access-Control-Allow-Headers': 'Content-Type, Authorization'
// }}
// );

let res = await axios({
method: 'get',
url: 'https://f4sxp72b65.execute-api.us-east-1.amazonaws.com/dev/getPopupHtml',
params: {
shopUrl: globalShopUrl,
uuid: uuid,
screenWidth: window.innerWidth,
spinDegree: globalDegree
},
headers: {
'Access-Control-Allow-Origin': 'https://bitespeed-kunjan.myshopify.com',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}
});
res = await res.json();

// initialize global variables
globalFinalHtml = res.finalHtml;
globalPopups = res.activePopups.popups;
globalWAPageId = res.activePopups.shopUrl[0];
globalPageId = res.activePopups.pageId[0];
if(res.spinTheWheelObj) {
discountCode = res.spinTheWheelObj.code;
spaceReplacedDiscountCode = discountCode.split(" ").join("bsp");
discountText = res.spinTheWheelObj.text;
}
}

function appendHtml(finalHtml) {
console.log("IN APPEND HTML");
for(let i = 0; i < finalHtml.length; i++) {
finalHtml[i] = unescape(finalHtml[i]);
finalHtml[i] = finalHtml[i].replace(/\\n/g, "");
finalHtml[i] = finalHtml[i].replace(/\`/g, "");
console.log(finalHtml[i]);
if(finalHtml[i]) $("body").append(finalHtml[i]);
}
}

async function popupDisplayDecider(popup, id, popupType) {
try {
if (popup.behaviour.when.showAt == "exit") {
await displayOnExit(popupType , id);
console.log("RENDERING " + popupType + " showAt="+popup.behaviour.when.showAt);
}
if (
popup.behaviour.when.showAt == "time" ||
popup.behaviour.when.showAt == "welcome"
) {
await displayWithTime(
popupType,
popup.behaviour.when.value,
id
);
console.log("RENDERING " + popupType + " showAt="+popup.behaviour.when.showAt);
}
if (popup.behaviour.when.showAt == "scroll") {
await displayOnScroll(
popupType,
popup.behaviour.when.value,
id
);
console.log("RENDERING " + popupType + " showAt="+popup.behaviour.when.showAt);
}
} catch(err) {
throw err;
}
}

async function renderPopups() {
let userId = getCookie("BS_UNIQUE_USER_ID");
if (!isValidObj(userId)) {
let currDate = new Date;
setCookieWithExpiry("BS_UNIQUE_USER_ID", userId = String(currDate.getTime()) + makeid(10), 15);
}
// handle special case
try {
if (window.location.href.includes('https://www.beachdazetowel.com') && !window.location.href.includes('https://www.beachdazetowel.com/pages/wholesale')) {
return;
}
} catch (err) {
console.error(err);
}

try {
// initialize global variables
await getFinalHtml();

console.log("THIS IS GLOBALFINALHTML", globalFinalHtml);
console.log("THIS IS GLOBALPOPUPS", globalPopups);

keys = Object.keys(globalPopups);
// let optedIn = String(getCookie("bitespeedOptedIn"));
let optedInWA = String(getCookie("bitespeedOptedInWA"));
if(keys[0]) {
if ((isValidObj(optedInWA) && globalPopups[keys[0]].behaviour.who.showAt == "unOpted") || globalPopups[keys[0]].behaviour.who.showAt != "unOpted") {
//RENDERING WHATSAPP POPUPS
console.log("RENDERING WHATSAPP POPUPS");
// append all the html strings
appendHtml(globalFinalHtml);

// iterate over each active popup
keys.forEach(async(popupId) => {
await renderPopup(globalPopups, globalPopups[popupId], popupId);
});
}
}
} catch(err) {
console.log(err);
}
}

async function renderPopup(popups, popup, id) {
if ("collapsed" in popup) {
if (!noRepeat.includes(id)) {
await sendImpression("pillImpressionSent", id);
console.log("RENDERING PERSISTENT DISCOUNT WIDGET");
}
}
else if(popup.type == "customerChatWidget" || popup.type == "customerChatWidgetWA") {
await sendImpression("widgetImpressionSent", id);
console.log("RENDERING CUSTOMER CHAT WIDGET");
}
else if(popup.type == "orderUpdates") {
try {
var options = {
method: "POST",
body: JSON.stringify({
id: id,
}),
headers: {
"Content-Type": "application/json",
},
};
await fetch("https://app.bitespeed.co/database/api/optinTools/impressions", options);
console.log("SUCCESFULLY SENT ORDER UPDATE");
} catch (err) {
console.log("Error while sending order updates ", err);
// throw err;
}
}
else if (popup.open) {
try {
switch (popup.open.type) {
case "modalImageAtTop":
await popupDisplayDecider(popup, id, "visualPopupImageAtTop");
break;
case "modalImageBehind":
await popupDisplayDecider(popup, id, "visualPopupImageBehind");
break;
case "modalImageAtRight":
await popupDisplayDecider(popup, id, "visualPopupImageAtRight");
break;
case "spinTheWheel":
case "spinTheWheelWA":
wheelLoad(popups, popup.id);
await popupDisplayDecider(popup, id, "wheelContainer");
break;
default:
break;
}
} catch(err) {

}
}

//WHATSAPP
try {
if(globalPopups[id].channel == 'WA') {
console.log("IN intlTelInput handler");
let input = document.querySelector("#bitespeed-phone-" + id);
let telClassName = ''
if(popup.type == "customerChatWidget") {
telClassName = "bitespeed-phone-customer-chat-widget";
}
console.log("input = " + input + "telClassName = " + telClassName);

// TODO: check if promises are handled correctly
let iti = await window.intlTelInput(input, {
geoIpLookup: async function (callback) {
const data = await axios.get('https://get.geojs.io/v1/ip/country.json');
if(data && data.country) callback(data.country);
else callback('IN');
},
initialCountry: "auto",
separateDialCode: true,
customContainer: telClassName
});
if(popup.type == "customerChatWidget") {
$("#wa-chat-bubble").css('display', 'none');
$("#wa-chat-bubble").css('visibility', 'initial');
}
// globalPhoneNoObjs initialized here
globalPhoneNoObjs[id] = iti;
console.log("intlTelInput HANDLED SUCCESSFULLY");
}
} catch(err) {
console.error("Error while handling intlTelInput", err);
throw err;
}
}

function setClass(popupPosition, id) {
const keys = Object.keys(globalPopups);
let type;
let classLayout;
for (let i = 0; i < keys.length; i++) {
if("collapsed" in globalPopups[keys[i]]) {
type = globalPopups[keys[i]].open.type;
break;
}
}
if(type == "modalImageAtTop") classLayout = "popupImageAtPillClick";
else classLayout = "popupImageAtPillClickBehind";

document.getElementById(
classLayout
).className = `popup onPillClick p${popupPosition}`;
document.getElementById("pillPopup").style.display = "flex";
document.getElementById("permanentPill").style.display = "none";
}

function showPopup() {
document.getElementById("popupImageAtTopDiv").style.display = "flex";
document.getElementById("permanentPill").style.display = "none";
}

async function displayOnExit(popupType, id) {
document.addEventListener(
"mouseleave",
async(e) => {
if(e.y <= 0 && !closedPopups.includes(popupType)) {
if(!noRepeat.includes(id)) {
if(popupType == "wheelContainer") {
document.getElementById("wheelContainer").style.transform =
"translate(100%, 0)";
}
else {
$(`#${popupType}`).fadeIn();
}
try {
await sendImpression(id, id);
} catch(err) {
throw err;
}
}
}
},
false
);
}

async function displayOnScroll(popupType, percentage, id) {
window.addEventListener("scroll", async() => {
const scrollTop = $(window).scrollTop();
const docHeight = $(document).height();
const winHeight = $(window).height();
const scrollPercent = scrollTop / (docHeight - winHeight);
const scrollPercentRounded = Math.round(scrollPercent * 100);
if (scrollPercentRounded > percentage && !closedPopups.includes(popupType)) {
if (!noRepeat.includes(id)) {
if (popupType == "wheelContainer") {
document.getElementById("wheelContainer").style.transform =
"translate(100%, 0)";
}
else {
$(`#${popupType}`).fadeIn();
}
try {
await sendImpression(id, id);
} catch(err) {
throw err;
}
}
}
});
}

async function displayWithTime(popupType, time, id) {
setTimeout(async() => {
if (!noRepeat.includes(id)) {
if (popupType == "wheelContainer") {
document.getElementById("wheelContainer").style.transform =
"translate(100%, 0)";
}
else {
$(`#${popupType}`).fadeIn();
}
try {
await sendImpression(id, id);
} catch(err) {
throw err;
}
}
}, time * 1000);
}

function hidePopup(popupType) {
$(`#${popupType}`).css("display", "none");
if (popupType === "permanentPill") {
document.getElementById("pillPopup").style.display = "none";
}
// initializes and modifies closedPopups
closedPopups.push(popupType);
}

function closeWheel() {
document.getElementById("wheelContainer").style.transform =
"translate(0%, 0)";
}

function spin(degree) {
const finalAngles = [];
let winningValue;
const dash1 = `${degree + 15}deg`;
finalAngles.push((degree + 15) % 360);
const dash2 = `${degree + 45}deg`;
finalAngles.push((degree + 45) % 360);
const dash3 = `${degree + 75}deg`;
finalAngles.push((degree + 75) % 360);
const dash4 = `${degree + 105}deg`;
finalAngles.push((degree + 105) % 360);
const dash5 = `${degree + 135}deg`;
finalAngles.push((degree + 135) % 360);
const dash6 = `${degree + 165}deg`;
finalAngles.push((degree + 165) % 360);
const dash7 = `${degree + 195}deg`;
finalAngles.push((degree + 195) % 360);
const dash8 = `${degree + 225}deg`;
finalAngles.push((degree + 225) % 360);
const dash9 = `${degree + 255}deg`;
finalAngles.push((degree + 255) % 360);
const dash10 = `${degree + 285}deg`;
finalAngles.push((degree + 285) % 360);
const dash11 = `${degree + 315}deg`;
finalAngles.push((degree + 315) % 360);
const dash12 = `${degree + 345}deg`;
finalAngles.push((degree + 345) % 360);
const spinAngle = `${degree}deg`;
for (let i = 0; i < 12; i++) {
if (finalAngles[i] > 300 && finalAngles[i] < 330) {
const num = String(6);
setTimeout(() => {
console.log("unknown popups ", popups);
// document.getElementById("offerMessage").innerHTML = "";
// popups[num].props.data[i].discountCode;
}, 3000);
winningValue = i + 1;
}
}
document.getElementById("dash-1").style.transform = `rotateZ(${dash1})`;
document.getElementById("dash-2").style.transform = `rotateZ(${dash2})`;
document.getElementById("dash-3").style.transform = `rotateZ(${dash3})`;
document.getElementById("dash-4").style.transform = `rotateZ(${dash4})`;
document.getElementById("dash-5").style.transform = `rotateZ(${dash5})`;
document.getElementById("dash-6").style.transform = `rotateZ(${dash6})`;
document.getElementById("dash-7").style.transform = `rotateZ(${dash7})`;
document.getElementById("dash-8").style.transform = `rotateZ(${dash8})`;
document.getElementById("dash-9").style.transform = `rotateZ(${dash9})`;
document.getElementById("dash-10").style.transform = `rotateZ(${dash10})`;
document.getElementById("dash-11").style.transform = `rotateZ(${dash11})`;
document.getElementById("dash-12").style.transform = `rotateZ(${dash12})`;
document.getElementById("dash-act").style.transform = `rotateZ(${spinAngle})`;
document.getElementById("wheelLogo").style.transform = `rotateZ(${spinAngle})`;
console.log("SPINNING THE WHEEL");
}

function wheelLoad(popups, id) {
const { length } = popups[id].data;
console.log("length ", length);
let dataIndex = 0;
for (let i = 0; i < 12; i++) {
if (dataIndex === length) {
dataIndex = 0;
}

const div = document.createElement("div");
div.className = `dash dash${i + 1}`;
const currentDiv = `dash-${i + 1}`;
div.id = currentDiv;
document.getElementById("wheelContainer").appendChild(div);
document.getElementById(currentDiv).style.fontFamily =
popups[id].open.props.offerFont;
if (popups[id].dashColorLight) {
if ((i + 1) % 2 === 0) {
document.getElementById(currentDiv).style.color =
popups[id].dashColorLight;
} else {
document.getElementById(currentDiv).style.color =
popups[id].dashColorDark;
}
}
const innerDiv = document.createElement("div");
innerDiv.innerHTML = `${popups[id].data[dataIndex].text}`;
innerDiv.className = "dashInner";
document.getElementById(currentDiv).appendChild(innerDiv);
if (window.innerWidth < 767) {
document.getElementById(currentDiv).style.top = "85%";
document.getElementById(currentDiv).style.left = "12.5vh";
} else {
document.getElementById(currentDiv).style.top = "80%";
document.getElementById(currentDiv).style.left = "19vh";
}

dataIndex += 1;
}
}

window.addEventListener("message", async (message) => {
try {
let res;
if (message.detail && message.detail.EUCustomer) {
res = JSON.parse(message.detail.data);
}
else if (message.detail && message.detail.isWA) {
res = JSON.parse(message.detail.data);
console.log("******res is = ", res);
await axios.post('https://app.bitespeed.co/fbWebhook', {
"object": "page",
"channel": "WA",
"entry": [
{
"id": globalWAPageId[0],
"time": new Date().getTime(),
"messaging": [
{
"recipient": {
"id": globalWAPageId[0]
},
"timestamp": new Date().getTime(),
"sender": {
"id": message.detail.phoneNo
},
"optin": {
"ref": res.join('.')
}
}
]
}
]
});
await axios.post('https://app.bitespeed.co/database/api/optinTools/conversions', {
id: res[0]
});
console.log("SUCCESSFULLY SENT USER INFO");
}
else {
res = JSON.parse(message.data);
console.log("IN ELSE PART WITH res = ", res);
}

// make phone no container transparent
try {
let intlPhoneNoContainer = $(`.${res[1]}`).find("#intlPhoneNoContainer");
intlPhoneNoContainer && intlPhoneNoContainer.css({
opacity: 0
});
} catch (e) {}


if (res[0] && globalPopups[res[0]] && res[1] != "customerChatWidget") {
console.log("ENTERS WITH", globalPopups[res[0]]);
var CookieDate = new Date();
CookieDate.setFullYear(CookieDate.getFullYear() + 1);
if (message.detail && message.detail.isWA) {
document.cookie =
"bitespeedOptedInWA=true" +
";expires=" +
CookieDate.toUTCString() +
";domain=" +
shopDomainStripped +
";path=/";

console.log("COOKIE SET");
} else {
document.cookie =
"bitespeedOptedIn=true" +
";expires=" +
CookieDate.toUTCString() +
";domain=" +
shopDomainStripped +
";path=/";
}
if (
res[1] == "masterContainerImageAtTopPhill" ||
res[1] == "masterContainerImageBehindPhill"
) {
noRepeat = noRepeat + "+" + res[0];
setCookie("displayedPopups", noRepeat);
}
if (res[1] == "spinTheWheelContainer") {
let tempTitle = globalPopups[res[0]].completed.props.title.text;
if (tempTitle.indexOf("{OFFER WON}") !== -1) {
setTimeout(() => {
let completedTitle =
tempTitle.substr(0, tempTitle.indexOf("{OFFER WON}")) +
discountText +
tempTitle.substr(tempTitle.indexOf("{OFFER WON}") + 11);
$(`#${res[1]}title`).html(completedTitle);
$(`#${res[1]}title`).css({
color: globalPopups[res[0]].completed.props.title.color,
"font-family":
globalPopups[res[0]].completed.props.title.fontFamily,
});
}, 3000);
} else {
$(`#${res[1]}title`).html(
globalPopups[res[0]].completed.props.title.text
);
$(`#${res[1]}title`).css({
color: globalPopups[res[0]].completed.props.title.color,
"font-family": globalPopups[res[0]].completed.props.title.fontFamily,
});
}

setTimeout(() => {
// $(`#${res[1]}text`).html(discountText + "-" + discountCode);
$(`#${res[1]}text`).html("Discount Code - " + discountCode);
}, 3000);
$(`#${res[1]}text`).css({
color: globalPopups[res[0]].completed.props.text.color,
"font-family": globalPopups[res[0]].completed.props.text.fontFamily,
});
$(`#${res[1]}wheelLogo`).attr(
"src",
globalPopups[res[0]].completed.props.wheelLogoUrl
);
$(`#${res[1]}heroLogo`).attr(
"src",
globalPopups[res[0]].completed.props.heroLogo
);
spin(globalDegree);
}
else {
console.log("Line 1");
$(`#${res[1]}title`).html(
globalPopups[res[0]].completed.props.title.text
);
$(`#${res[1]}title`).css({
color: globalPopups[res[0]].completed.props.title.color,
"font-family": globalPopups[res[0]].completed.props.title.fontFamily,
});
if (globalPopups[res[0]].discountOption == "Yes") {
$(`#${res[1]}subtitle`).html(
globalPopups[res[0]].generalSettings.discountCode
);

$(`#${res[1]}subtitle`).css({
"font-size":
globalPopups[res[0]].completed.props.subtitle.fontSize + "vh",
});
} else {
console.log("Line 2");
$(`#${res[1]}subtitle`).html(
globalPopups[res[0]].completed.props.subtitle.text
);
}
console.log("Line 3");
$(`#${res[1]}subtitle`).css({
color: globalPopups[res[0]].completed.props.subtitle.color,
"font-family":
globalPopups[res[0]].completed.props.subtitle.fontFamily,
});
console.log("BEFORE CHANGING COMPLETED TEXT", globalPopups[res[0]].completed.props.text.text);
$(`#${res[1]}text`).html(globalPopups[res[0]].completed.props.text.text);
$(`#${res[1]}text`).css({
color: globalPopups[res[0]].completed.props.text.color,
"font-family": globalPopups[res[0]].completed.props.text.fontFamily,
"font-size": globalPopups[res[0]].completed.props.text.fontSize + "vh",
});
console.log("AFTER CHANGING COMPLETED TEXT");
$(`#${res[1]}mainImage`).css({
"background-image": `url(${globalPopups[res[0]].completed.props.imageUrl
})`,
});
$(`#${res[1]}popupDiv`).css({
"background-image": `url(${globalPopups[res[0]].completed.props.imageUrl
})`,
});
if (res[1] == "masterContainerImageBehindPhill") {
$("#popupImageAtPillClick").css({
"background-image": `url(${globalPopups[res[0]].completed.props.imageUrl
})`,
});
}
$(`#${res[1]}textContainer`).css({
"background-color":
globalPopups[res[0]].completed.props.content.backgroundColor,
});
}
try {
// await axios.post("https://app.bitespeed.co/redis/conversionFBStatus", {
// fbLoggedInStatus,
// headers: {'Access-Control-Allow-Origin': '*'}
// });
await axios({
method: 'post',
url: 'https://app.bitespeed.co/redis/conversionFBStatus',
data: {fbLoggedInStatus: fbLoggedInStatus},
headers: {'Access-Control-Allow-Origin': '*'}
});
} catch (err) {
console.log("Error posting FB status on s");
}
}
} catch (err) {
// error
console.log("Error occured", err);
}
});

Back to list