var churchPharmacy = {
userAccountURL: "user/myaccount",
notificationURL: "user/notifications",
apiURL: "https://fd-store-api.churchpharmacy.co.uk/",
carriageService: "WebServices/CarriageService.asmx",
};
churchPharmacy.common = (function () {
var user = { isAuthenticated: false, id: 0, authToken: "" };
var customer = { customerId: 0, hasDigitRx: undefined };
function initialize(isUserLoggedIn, token) {
if (isUserLoggedIn) {
user.authToken = JSON.parse(unescape(token));
}
user.isAuthenticated = isUserLoggedIn;
getCurrentUser();
getCarriageCuttOffTime();
// check token and refresh the page if any change
setInterval(function () {
var tokenCookie = getCookie("apiToken");
if (tokenCookie && !user.isAuthenticated) {
window.location.reload();
} else if (!tokenCookie && user.isAuthenticated) {
window.location.reload();
}
}, 1000);
}
function getCookie(c_name) {
var i,
x,
y,
ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setDigitRxLink(isUserLoggedIn) {
var linksignupfordigitrx = $(
".banner-component a[href$='#digitrx-button']"
);
if (isUserLoggedIn === "True") {
$(linksignupfordigitrx)
.html("DIGITRx")
.attr("href", "/shop/shop?mode=digitrx&view=grid");
} else {
$(linksignupfordigitrx).attr(
"onclick",
"churchPharmacy.common.dialog.openDigitRxSignUp(); return false;"
);
}
}
async function getCurrentUser() {
if (user.isAuthenticated) {
var url = `${churchPharmacy.apiURL}${churchPharmacy.userAccountURL}`;
var data = await service.get(url);
if (data.status === "failed" || data.Id === 0) {
user.isAuthenticated = false;
user.firstName = "";
user.lastName = "";
user.email = "";
user.freshChatId = "";
user.isAllowDigitalPrescription = false;
user.isPrescriber = false;
user.id = 0;
user.profession = '';
} else {
user.isAuthenticated = true;
user.displayName = `${data.userTitle}. ${data.surName}`;
user.isAdmin = false;
user.id = data.userId;
user.firstName = user.firstName;
user.lastName = user.surName;
user.email = user.emailId;
user.freshChatId = user.freshChatRestoreId;
user.isAllowDigitalPrescription = data.isAllowDigitalPrescription;
user.isPrescriber = data.isPrescriber;
user.profession = data.profession;
$(".lblDisplayName").text(user.displayName);
if(window.location.href.indexOf('bonus-rewards') > -1 ){
SaveBannerTrack('bonus-reward','');
}
}
} else {
user.isAuthenticated = false;
user.firstName = "";
user.lastName = "";
user.email = "";
user.freshChatId = "";
user.id = 0;
user.isAllowDigitalPrescription = false;
user.isPrescriber = false;
user.profession = '';
}
$(".alert-notify").css("display", "");
getNotifications();
freshChat();
if(window.location.href.toLowerCase().indexOf('/digitrx') > -1){
digitRxButton();
}
}
function digitRxButton(){
var linksignupfordigitrx= $(".banner-component a[href$='#signupfordigitrx']");
var linkupgradetodigitrx= $(".banner-component a[href$='#upgradetodigitrx']");
var linkviewdigitrxpad= $(".banner-component a[href$='#viewdigitrxpad']");
var linkshopnow= $(".banner-component a[href$='#shopnow']");
var linkupgradetopartnerprescriber= $(".banner-component a[href$='#upgradetopartnerprescriber']");
$(linksignupfordigitrx).attr('href','https://store.churchpharmacy.co.uk/login');
$(linkupgradetodigitrx).attr('href','https://store.churchpharmacy.co.uk/shop?key=upgrade');
$(linkviewdigitrxpad).attr('href','https://store.churchpharmacy.co.uk/digitrx');
$(linkshopnow).attr('href','https://store.churchpharmacy.co.uk/shop');
$(linkupgradetopartnerprescriber).attr('href','https://store.churchpharmacy.co.uk/shop?key=upgrade');
var professions = ['Radiographer','Operating Dept Practitioner','Dental Nurse','Pharmacist','Paramedic','Nurse Midwife','Pharmacist Prescriber','Nurse',
'Dentist','Doctor','Doctor IMC','Nurse Prescriber','Physiotherapist'];
if(churchPharmacy.common.user.isAuthenticated){
$(linksignupfordigitrx).remove();
if(churchPharmacy.common.user.isPrescriber){
$(linkupgradetopartnerprescriber).remove();
if(churchPharmacy.common.user.isAllowDigitalPrescription){
$(linkupgradetodigitrx).remove();
}else{
$(linkviewdigitrxpad).remove();
}
}else{
$(linkupgradetodigitrx).remove();
$(linkviewdigitrxpad).remove();
if(churchPharmacy.common.user.isAllowDigitalPrescription || !professions.includes(churchPharmacy.common.user.profession)){
$(linkupgradetopartnerprescriber).remove();
}
}
}else{
$(linkupgradetodigitrx).remove();
$(linkviewdigitrxpad).remove();
$(linkshopnow).remove();
$(linkupgradetopartnerprescriber).remove();
}
}
function freshChat() {
var externalId = user.email;
var freshChatRestoreId = user.freshChatId;
var userId = user.id;
InitiateFreshChat(false, 'a995f08a-1189-4f18-85d8-2ccd152595e4', 'https://wchat.eu.freshchat.com', externalId, freshChatRestoreId, userId);
//Create FreshChat user if its not created
var firstName = user.firstName;
var lastName = user.lastName;
var email = user.email;
CreateUserForFreshChat(firstName, lastName, email, userId, freshChatRestoreId);
}
function InitiateFreshChat(
shouldOpen,
token,
host,
externalId,
freshChatRestoreId,
userId
) {
if (shouldOpen == true && window.fcWidget.isOpen() != true) {
window.fcWidget.open({
name: "General Enquiries",
replyText: "Thank you for the help.",
});
return;
}
window.fcWidget.init({
token: token,
host: host,
externalId: externalId,
restoreId: freshChatRestoreId ? freshChatRestoreId : null,
userId: userId,
});
}
function CreateUserForFreshChat(
firstName,
lastName,
email,
userId,
freshChatRestoreId
) {
window.fcWidget.user.get(function (resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status !== 200) {
window.fcWidget.user
.setProperties({
firstName: firstName,
lastName: lastName,
email: email,
userId: userId,
})
.then(function (resp) {})
.catch((e) => {
console.log(e);
});
if (status == 401) {
window.fcWidget.user
.create()
.then(
function () {
firstName: firstName;
lastName: lastName;
email: email;
userId: userId;
},
function () {}
)
.catch((e) => {
console.log(e);
});
}
window.fcWidget.on("user:created", function (resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
var url = `${churchPharmacy.shopUrl}${churchPharmacy.carriageService}/UpdateFreshChatRestoreId`;
churchPharmacy.common.service
.post(url, {
userId: user.id,
freshChatRestoreId: freshChatRestoreId,
})
.then((data) => {
if (data.status !== "failed") {
if (data.length > 0) {
dialog.openCarriageNotificationDialog(data);
}
}
});
}
window.fcWidget.user
.update({
meta: {
userId: userId,
},
})
.then(function (resp) {})
.catch((e) => {
console.log(e);
});
} else {
alert(status);
}
});
} else if (status == 200) {
window.fcWidget.user
.setProperties({
firstName: firstName,
lastName: lastName,
email: email,
userId: userId,
})
.then(function (resp) {})
.catch((e) => {
console.log(e);
});
}
});
}
async function getCarriageCuttOffTime() {
var url = `${churchPharmacy.shopUrl}${churchPharmacy.carriageService}/GetCarriageCutOffTime`;
churchPharmacy.common.service.get(url).then((data) => {
if (data.status !== "failed") {
if (data.length > 0) {
dialog.openCarriageNotificationDialog(data);
}
}
});
}
function togglePassword(show) {
if (show) {
$("#security-eye").hide();
$("#security-eyeoff").show();
$("#txtSecurityCode").attr("type", "text");
} else {
$("#security-eye").show();
$("#security-eyeoff").hide();
$("#txtSecurityCode").attr("type", "password");
}
}
function textLength(target, length) {
$(target).next("span").show();
if ($(target).val().length > length) {
$(target).val($(target).val().substr(0, length));
}
$(target)
.next("span")
.find("strong")
.html(length - $(target).val().length);
}
async function getUpvotyJWTToken() {
var hdnShopUrl = $("#hdnShopUrl").val();
var url = `${hdnShopUrl}${churchPharmacy.userService}/ValidateUpvotyDetails`;
var data = await service.get(url);
return data;
}
var service = {
get: async function (url) {
var response = await fetch(url, {
//credentials: "include",
headers: new Headers({
"Content-Type": "application/json",
Authorization: `Bearer ${user.authToken.apiToken}`,
}),
xhrFields: { withCredentials: true },
});
if (response.ok) {
var data = await response.json();
if (data === null) {
return {};
}
return data;
} else {
dialog.openAlertDialog(
"There is some technical issue. Please try again later."
);
return { status: "failed" };
}
},
post: async function (url, body) {
var response = await fetch(url, {
method: "post",
//credentials: 'include',
headers: new Headers({
"Content-Type": "application/json",
Authorization: `Bearer ${user.authToken.apiToken}`,
}),
body: JSON.stringify(body),
//xhrFields: { withCredentials: true }
});
if (response.ok) {
var data = await response.json();
if (data == null) {
return {};
}
return data;
} else {
dialog.openAlertDialog(
"There is some technical issue. Please try again later."
);
return { status: "failed" };
}
},
};
var dialog = {
openDigitRxSignUp: function () {
dialog.show("signupDialog");
},
openMobileDialog: function () {
dialog.show("mobileDialog");
},
openAlertDialog: function (dialogContent) {
$("#alertMessage").html(dialogContent);
dialog.show("alertDialog");
},
openInfoDialog: function (title, dialogContent) {
$("#infordialogTitle").html(title);
$("#infoMessage").html(dialogContent);
dialog.show("infoDialog");
},
showLoading: function () {
$("#loadingspinner").show();
},
hideLoading: function () {
$("#loadingspinner").hide();
},
show: function (dialogId) {
$(`#${dialogId}`).modal("show");
},
hide: function (dialogId) {
$(`#${dialogId}`).modal("hide");
},
};
function log(message) {
console.log(message);
}
async function SaveBannerTrack(bannerTitle, hurl) {
if (user.isAuthenticated) {
var url = `${churchPharmacy.apiURL}master/bannertracking/${bannerTitle}`;
var data = await service.get(url);
if (data.status != "failed") {
if(hurl != ""){
location.href = hurl;
}
}
}else{
if(hurl != ""){
location.href = hurl;
}
}
}
async function OpenFreshChatDialog(){
window.fcWidget.open({
name: "General Enquiries",
replyText: "Thank you for the help.",
});
return;
}
return {
user: user,
customer: customer,
initialize: initialize,
setDigitRxLink: setDigitRxLink,
service: service,
dialog: dialog,
log: log,
togglePassword: togglePassword,
textLength: textLength,
SaveBannerTrack: SaveBannerTrack,
getUpvotyJWTToken: getUpvotyJWTToken,
OpenFreshChatDialog: OpenFreshChatDialog
};
})();
// Notification -- Start
var notificationId = 0;
var recordFlag = false;
var isNotificationLoded = false;
var notifications = {};
if (screen.availWidth < 836) {
$(".secondary .alert-notify").remove();
} else {
$(".alert-notify-mob .alert-notify").remove();
}
//function to change new notification count and remove unread class from read notification.
function OnSuccessRead(response) {
if (response.success === true) {
notifications.forEach((notification) => {
if (notification.id == notificationId) {
notification.isNew = false;
}
});
}
}
$(".alert-notify").click(function () {
setTimeout(function(){
bindNotifications(notifications);
},500)
});
$("#alert-notification").on("click", ".notify-read-more-btn", function () {
var currentContent = $(this).closest(".content");
$("#alert-notification").find(".content").addClass("d-none");
$("#alert-notification").find(".loadingnotification").removeClass("d-none");
setTimeout(function () {
currentContent.removeClass("d-none");
$("#alert-notification").find(".loadingnotification").addClass("d-none");
}, 300);
$("#alert-notification")
.find(".left-content, .right-content")
.addClass("d-none");
currentContent.find(".readmoreinfo").removeClass("d-none");
notificationId = currentContent.attr("id");
$("#RecordFound").html("Your notification");
//if user is logged in call web service method to set isread true.
if (churchPharmacy.common.user.id !== 0) {
var url = `${churchPharmacy.apiURL}/user/notification/archive?notificationId=${notificationId}`;
churchPharmacy.common.service
.post(url, {
notificationId: notificationId,
userId: churchPharmacy.common.user.id,
})
.then((data) => {
if (data.status !== "failed") {
OnSuccessRead(data);
}
});
}
return true;
});
$("#alert-notification").on("click", ".notify-back-btn", function () {
$("#alert-notification").find(".loadingnotification").removeClass("d-none");
setTimeout(function () {
$("#alert-notification").find(".content").removeClass("d-none");
$("#alert-notification").find(".loadingnotification").addClass("d-none");
}, 100);
$("#alert-notification")
.find(".left-content, .right-content")
.removeClass("d-none");
//if user is logged in call web service method to set isread true.
if (churchPharmacy.common.user.id !== 0) {
$(".readmoreinfo").addClass("d-none");
} else {
$(this).closest(".readmoreinfo").addClass("d-none");
}
notifications = notifications.filter(
(notification) => notification.isNew == true || notification.isNew == 1
);
bindNotifications(notifications);
showHideNotificationCount(notifications.length);
return true;
});
function getNotifications() {
if (churchPharmacy.common.user.id !== 0) {
var url = `${churchPharmacy.apiURL}${churchPharmacy.notificationURL}`;
churchPharmacy.common.service
.post(url, { notificationLocation: 1 })
.then((data) => {
if (data.status !== "failed" && data) {
notifications = data;
showHideNotificationCount(notifications.length);
}
});
} else {
//bind data for not logged in user.
var url = `${churchPharmacy.apiURL}/user/notification/without-login`;
churchPharmacy.common.service.get(url).then((data) => {
if (data.status !== "failed" && data) {
notifications = data;
showHideNotificationCount(notifications.length);
}
});
}
}
function bindNotifications(data) {
$("#RecordFound").removeClass("d-none");
$("#RecordNotFound").addClass("d-none");
//recordflag false means notification UI is set to show new notifications. filter array to get only new items if this condition is true.
if (recordFlag === false) {
data = $.grep(data, function (objResult) {
return objResult.isNew === true || objResult.isNew === 1;
});
}
var table = $("#alert-notification .content").eq(0).clone(true);
$("#alert-notification .content").eq(0).remove();
for (i = 0; i < data.length; i++) {
if (
!data[i].hasOwnProperty("id") ||
!data[i].hasOwnProperty("title") ||
!data[i].hasOwnProperty("description") ||
!data[i].hasOwnProperty("duration") ||
!data[i].hasOwnProperty("notificationMonth") ||
!data[i].hasOwnProperty("notificationDate") ||
!data[i].hasOwnProperty("notificationYear") ||
!data[i].hasOwnProperty("notificationDayName") ||
!data[i].hasOwnProperty("isNew")
) {
//SetNoNotificationWindow();
return;
}
}
if (data) {
$(data).each(function () {
table.attr("id", this.id);
$(".NIsNew", table).html(this.isNew.toString());
$(".NIsHigh", table).html(this.highPriority.toString());
$(".date", table).html(
`${this.notificationDayName},
${this.notificationDate} ${this.notificationMonth} ${this.notificationYear}`
);
$(".notice-title", table).html(this.title);
$(".desc", table).html(this.description);
$(".timeago", table).html(this.duration);
$("#alert-notification .cp-aln-wrpaper").append(table);
//add unread class for new notification.
$("#alert-notification")
.find(".content")
.each(function () {
if ($(this).find(".NIsNew").html() == "true") {
$(this).addClass("unread");
} else {
$(this).removeClass("unread");
}
});
$("#alert-notification")
.find(".content")
.each(function () {
if ($(this).find(".NIsHigh").html() == "true") {
$(this).addClass("important");
} else {
$(this).removeClass("important");
}
});
table = $("#alert-notification .content").eq(0).clone(true);
});
}
$(".alert-loadwrap").fadeOut();
showHideNotificationCount(data.length);
}
function showHideNotificationCount(notificationCount) {
//condition to show/hide new notification count based on 0 count/ if user logged in or not.
if (notificationCount > 0 && churchPharmacy.common.user.id !== 0) {
$("#notificationCount").html(notificationCount).removeClass("d-none");
} else if (notificationCount === 0) {
$("#RecordFound").addClass("d-none");
$("#RecordNotFound").removeClass("d-none");
$("#notificationCount").addClass("d-none");
$("#dvNotification").addClass("d-none");
} else {
$("#notificationCount").addClass("d-none");
}
}
function ShowAllNotification() {
$('#RecordFound').html("ALL NOTIFICATIONS");
if (notificationId != null && notificationId > 0) {
$("#alert-notification div#" + notificationId).find("span.NIsNew").html(true)
}
$('#alert-notification').hasClass('readmoreinfo')
{
$('.readmoreinfo').addClass('d-none');
$('#alert-notification').find('.loadingnotification').addClass('d-none');
setTimeout(function () {
$('#alert-notification').find('.loadingnotification').addClass('d-none');
$('#alert-notification').find('.content').removeClass('d-none');
}, 100);
$('#alert-notification').find('.left-content , .right-content').removeClass('d-none');
}
if (churchPharmacy.common.user.id !== 0) {
var url = `${churchPharmacy.apiURL}${churchPharmacy.notificationURL}`;
churchPharmacy.common.service.post(url, { notificationLocation: 1 })
.then((data) => {
if (data.status !== 'failed' && data && data !== null) {
if (data.length > 0) {
OnSuccessAllNotification(data);
}
}
});
}
else {
//bind data for not logged in user.
var url = `${churchPharmacy.apiURL}user/notification/without-login`;
churchPharmacy.common.service.get(url)
.then((data) => {
if (data.status !== 'failed' && data && data !== null) {
if (data.length > 0) {
OnSuccessAllNotification(data);
}
}
});
}
$('#dvShowAllNotification').removeClass('disabled');
$('#dvNewNotification').addClass('disabled');
}
function ShowNewNotification() {
$('#RecordFound').html("YOUR NOTIFICATION");
$('#alert-notification').hasClass('readmoreinfo')
{
$('.readmoreinfo').addClass('d-none');
$('#alert-notification').find('.loadingnotification').addClass('d-none');
setTimeout(function () {
$('#alert-notification').find('.loadingnotification').addClass('d-none');
$('#alert-notification').find('.content').removeClass('d-none');
}, 100);
$('#alert-notification').find('.left-content , .right-content').removeClass('d-none');
}
if (notificationId != null && notificationId > 0) {
$("#alert-notification div#" + notificationId).find("span.NIsNew").html(false)
}
if (!$('ShowNew').hasClass('IsAdded')) {
}
if (churchPharmacy.common.user.id !== 0) {
var url = `${churchPharmacy.apiURL}${churchPharmacy.notificationURL}`;
churchPharmacy.common.service.post(url, { notificationLocation: 1 })
.then((data) => {
if (data.status !== 'failed' && data && data !== null) {
if (data.length > 0) {
OnSuccessNewNotification(data);
}
}
});
}
else {
//bind data for not logged in user.
var url = `${churchPharmacy.apiURL}user/notification/without-login`;
churchPharmacy.common.service.get(url)
.then((data) => {
if (data.status !== 'failed' && data && data !== null) {
if (data.length > 0) {
OnSuccessNewNotification(data);
}
}
});
}
$('#dvShowAllNotification').addClass('disabled');
$('#dvNewNotification').removeClass('disabled');
}
function OnSuccessAllNotification(data) {
$("#RecordFound").removeClass("d-none");
$("#RecordNotFound").addClass("d-none");
$('.content').prepend('