var BigCommerceArtifi = BigCommerceArtifi || {};
BigCommerceArtifi.isEventIsAlreadyRegistered = false;
/*Personalize Button Template use for personalizeButton*/
var personalizeButton = '
');
$("body").append(div);
$("#tempCartDiv").load('/cart.php ' + cartTableContainer, function () {
var cartItemRows = $(cartTableContainer).find('> tbody').find('> tr');
if (BigCommerceArtifi.ProductPage.addToCartEventHandler) {
BigCommerceArtifi.ProductPage.addToCartEventHandler(cartItemRows);
}
});
};
function addMiniCartPopupHandler() {
if ($('[data-cart-preview]').is(':visible')) { //if the container is visible on the page
$('[data-cart-preview]').on("click", updateMiniCartPopupThumbnail);
clearTimeout();
} else {
setTimeout(addMiniCartPopupHandler, 50); //wait 50 ms, then try again
}
};
function updateMiniCartPopupThumbnail() {
if ($('[data-preview-design-id]').is(':visible')) {
$('[data-preview-design-id]').each(function (key, val) {
var imageParent = $(this);
var designId = $(this).attr('data-preview-design-id').trim();
if (designId > 0) {
var image = new Image();
image.src = BigCommerceArtifi.Application.getPreviewImageURL(designId);
image.onload = function () {
var miniCartImage = imageParent.find('img');
var width = miniCartImage.width();
var height = miniCartImage.height();
miniCartImage.attr('srcset', image.src);//.attr('src', image.src);//.attr('data-srcset', image.src);
miniCartImage.width(width);
miniCartImage.height(height);
};
}
});
clearTimeout();
} else {
setTimeout(updateMiniCartPopupThumbnail, 50); //wait 50 ms, then try again
}
};
function setPersonalizationButton() {
//GET Product ID Array
let productId = []; $('[data-art-selector="btn-personalise"]').each((index, element) => {
productId.push($(element).attr('data-product-id'));
});
//GET Product SKU Array
let productSKU = []; $('[data-art-selector="btn-personalise"]').each((index, element) => {
productSKU.push($(element).attr('data-product-sku'));
});
if (productId.length && productSKU.length) {
BigCommerceArtifi.Application.sendRequest(
'products/isPersonalizationEnabled',
'GET',
{ productId: productId, productSKU: productSKU },
function (data) {
if (data.length) {
for (var index = 0; index < data.length; index++) {
if (data[index]) {
$('[data-art-selector="btn-personalise"][data-product-sku="' + productSKU[index] + '"]').show();//hide perosnalization button if Personalization is not set
}
}
}
}
);
}
};
function isCustomizedProduct(productId, productSKU, callback) {
let productIds = [];
let productSKUs = [];
if (productId && productSKU) {
productIds.push(productId.toString());
productSKUs.push(productSKU.toString());
if (productIds.length && productSKUs.length) {
try {
BigCommerceArtifi.Application.sendRequest(
'/products/isPersonalizationEnabled',
'GET',
{ productId: productIds, productSKU: productSKUs },
function (data) {
if (data && data.length > 0 && data[0]) {
callback(true);
}
else {
callback(false);
}
},
function (error) {
console.log(error);
callback(false);
}
);
} catch (error) {
callback(false);
}
} else {
callback(false);
}
} else {
callback(false);
}
}
function getPreviewImageURL(designID, isThumbnail = true) {
if (!isNaN(parseInt(designID))) {
var randomString = Math.random().toString(36).substring(7);
var PreviewUrl = 'websiteId=' + BigCommerceArtifi.Application.getWebsiteId() +
'&webApiClientKey=' + BigCommerceArtifi.Application.getWebApiClientKey() +
'&customizedProductId=' + designID +
'&isthumbnail=' + isThumbnail + '&cache=' + randomString;
var pathArray = BigCommerceArtifi.Application.getIntegrationUrl().split('/');
var url = getArtifiBaseUrl();
return url + "/Designer/Services/GetPreviewImage?personalization=" + btoa(PreviewUrl);
}
};
function getPDFUrl(designID) {
if (!isNaN(parseInt(designID))) {
var parameters = 'websiteId=' + BigCommerceArtifi.Application.getWebsiteId() +
'&webApiClientKey=' + BigCommerceArtifi.Application.getWebApiClientKey() +
'&customizedProductId=' + designID;
var url = getFrontUrl();
//return url + "/Designer/Services/DownloadOutputFiles?personalization=" + btoa(parameters);
return applicationHost.replace('api', 'pdf')+ designID;
}
return "error";
};
function getXMLUrl(designID) {
if (!isNaN(parseInt(designID))) {
var parameters = 'websiteId=' + BigCommerceArtifi.Application.getWebsiteId() +
'&webApiClientKey=' + BigCommerceArtifi.Application.getWebApiClientKey() +
'&customizedProductId=' + designID;
var url = getFrontUrl();
//return url + "/Designer/Services/RegenerateXMLFile?personalization=" + btoa(parameters);
return applicationHost.replace('api', 'xml')+ designID;
}
return "error";
};
function updateCheckoutPage() {
var productListItems = $('.productList-item');
if (productListItems.is(':visible')) { //if the container is visible on the page
productListItems.each(function (element) {
updateCheckoutDesigns($(this));
});
$('.productList').on('DOMNodeInserted', 'li', function (e) {
updateCheckoutDesigns($(e.currentTarget));
});
clearTimeout();
} else {
setTimeout(updateCheckoutPage, 50); //wait 50 ms, then try again
}
};
function updateCheckoutDesigns(element) {
var ProductOptions = $(element).find('[data-test="cart-item-product-option"]');
var pattern = regexArtifiDesignId;
var pdfXmlRegex = regexDesignIdPdfXml;
ProductOptions.each(function () {
var label = $(this).html();
var result = pattern.exec(label);
var isPDFLinkPresent = pdfXmlRegex.exec(label);
if (result !== null) {
var designId = label.replace(/[^\d.]/g, '');
var image = new Image();
image.src = BigCommerceArtifi.Application.getPreviewImageURL(designId.trim());
image.onload = function () {
var checkoutCartImage = $(element).find('img[data-test="cart-item-image"]');
checkoutCartImage.attr('src', image.src);
};
if (checkoutPageName == 'orderconfirmation') {
UpdateCheckoutStatus(designId, merchantId);
}
$(this).hide();
};
if (isPDFLinkPresent != null) {
$(this).hide();
}
pattern.lastIndex = 0;
pdfXmlRegex.lastIndex = 0;
});
}
return {
init: function (config) {
return init(config);
},
sendRequest: function (endpoint, method, payload, callback, callbackData, errorCallback) {
return sendRequest(endpoint, method, payload, callback, callbackData, errorCallback);
},
getWebsiteId: function () {
return getWebsiteId();
},
getWebApiClientKey: function () {
return getWebApiClientKey();
},
getIntegrationUrl: function () {
return getIntegrationUrl();
},
getFrontUrl: function () {
return getFrontUrl();
},
getBaseIntergrationValues: function () {
return getBaseIntergrationValues();
},
getUrlParameter: function (searchedParameterName) {
return getUrlParameter(searchedParameterName);
},
generateUniqueIdentifier: function () {
return generateUniqueIdentifier();
},
setPersonalizationButton: function () {
return setPersonalizationButton();
},
getPreviewImageURL: function (designID, IsThumbnail) {
return getPreviewImageURL(designID, IsThumbnail);
},
getPDFUrl: function (designID) {
return getPDFUrl(designID);
},
getXMLUrl: function (designID) {
return getXMLUrl(designID);
},
updateCheckoutPage: function (pageName) {
checkoutPageName = pageName;
return updateCheckoutPage();
},
getIntegrationType: function () {
return getIntegrationType();
},
getArtifiBaseUrl: function () {
return getArtifiBaseUrl();
},
isCustomizedProduct: function (productId, productSKU, callback) {
isCustomizedProduct(productId, productSKU, callback);
},
};
})(window.jQuery);
BigCommerceArtifi.Customer = (function ($) {
'use strict';
var customerEmail,
customerId,
bigcommerceCustomerId,
sessionId,
fetchingInProgress = false;
function init(email) {
$(window).ready(handleCustomerLogout());
var interval = setInterval(function () {
if (typeof Cookies !== 'undefined') {
clearInterval(interval);
$(window)
.ready(fetchCustomer(email, handleCustomerInitResponse));
}
}, 100);
}
function handleCustomerInitResponse(email, response) {
customerId = response.customerId;
bigcommerceCustomerId = response.bigCommerceCustomerId;
var customer = {};
customer.email = email;
customer.customerId = customerId;
customer.bigCommerceCustomerId = bigcommerceCustomerId;
Cookies.set(BigCommerceArtifi.Constants.customerCookieName, JSON.stringify(customer));
BigCommerceArtifi.Customer.setFetchingInProgress(false);
}
function setFetchingInProgress(flag) {
fetchingInProgress = flag;
}
function fetchCustomer(email, callback) {
var interval = setInterval(function () {
if (typeof Cookies !== 'undefined' && fetchingInProgress !== true) {
clearInterval(interval);
fetchingInProgress = true;
var customer = Cookies.get(BigCommerceArtifi.Constants.customerCookieName);
if (customer) {
customer = JSON.parse(customer);
}
if (customer && (!email || email === customer.email)) {
return callback(customer.email, customer);
}
if (!email) {
email = BigCommerceArtifi.Application.generateUniqueIdentifier();
}
var endpoint = 'customer?email=' + email,
method = 'GET',
payload = '';
var headers = {}; // ✅ Declare before usage
if (customer) {
endpoint = 'customer?customerId=' + customer.customerId;
method = 'PUT';
payload = JSON.stringify({ 'email': email });
}
BigCommerceArtifi.Application.sendRequest(
endpoint,
method,
payload,
function (response) {
callback(email, response);
},
headers // 🔹 pass headers to sendRequest
);
}
}, 100);
}
// Fetch and update customer data using email and manage customer ID
function fetchAndUpdateCustomerData(email, callback) {
// Load js-cookie if not already available
if (typeof Cookies === 'undefined' || Cookies === null) {
var script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.min.js';
script.onload = function () {
initializeCustomerDataFlow();
};
(document.head || document.documentElement).appendChild(script);
} else {
initializeCustomerDataFlow();
}
function initializeCustomerDataFlow() {
var customer = Cookies.get(BigCommerceArtifi.Constants.customerCookieName);
if (customer) {
customer = JSON.parse(customer);
}
if (customer && (!email || email === customer.email)) {
setCustomerId(customer.email, customer);
return callback(customer.email, customer);
}
if (!email) {
email = BigCommerceArtifi.Application.generateUniqueIdentifier();
}
var endpoint = 'customer?email=' + email,
method = 'GET',
payload = '';
if (customer) {
endpoint = 'customer?customerId=' + customer.customerId;
method = 'PUT';
payload = JSON.stringify({ 'email': email });
}
BigCommerceArtifi.Application.sendRequest(
endpoint,
method,
payload,
function (response) {
setCustomerId(email, response);
callback(email, response);
}
);
}
}
// Store customer data on cookies and set customer ID
function setCustomerId(email, response) {
customerId = response.customerId;
bigcommerceCustomerId = response.bigCommerceCustomerId;
var customer = {};
customer.email = email;
customer.customerId = customerId;
customer.bigCommerceCustomerId = bigcommerceCustomerId;
Cookies.set(BigCommerceArtifi.Constants.customerCookieName, JSON.stringify(customer));
}
function handleCustomerLogout() {
var attempt = 1,
interval = setInterval(function() {
var linksCollection = $('a'),
pattern = /\/login.php\?action=logout/g;
linksCollection.each(function (index, element) {
var linkObject = $(element),
hrefValue = linkObject.attr('href');
if (!hrefValue) {
// Continue to next iteration.
return true;
}
var result = pattern.exec(hrefValue);
if (result !== null) {
linkObject.on('click', function () {
window.console.log('removing cookie');
Cookies.remove(BigCommerceArtifi.Constants.customerCookieName);
});
clearInterval(interval);
}
});
if (attempt >= 3) {
clearInterval(interval);
}
attempt += 1;
}, 100);
}
function getCustomerEmail() {
return customerEmail;
}
function getCustomerId() {
return customerId;
}
function getBigcommerceCustomerId() {
return bigcommerceCustomerId;
}
return {
init: function (email) {
return init(email);
},
fetchCustomer: function (email, callback) {
return fetchCustomer(email, callback);
},
getCustomerEmail: function () {
return getCustomerEmail();
},
getCustomerId: function () {
return getCustomerId();
},
getBigcommerceCustomerId: function () {
return getBigcommerceCustomerId();
},
setFetchingInProgress: function (flag) {
return setFetchingInProgress(flag);
},
fetchAndUpdateCustomerData: function (email, callback) {
return fetchAndUpdateCustomerData(email, callback);
}
};
})(window.jQuery);
BigCommerceArtifi.ProductPage = (function ($) {
'use strict';
var productId,
customerEmail,
productSku,
productOptions,
initResponse,
artifiReactAddToCartEventObject,
artifiAddToCartEventObject,
extraQueryStringOption;
function init(config) {
productId = config.productId;
customerEmail = config.customerEmail;
var extraQueryString = config.extraQueryString ? config.extraQueryString : "";
extraQueryStringOption = extraQueryString;
var designId = config.artifiDesignId ? config.artifiDesignId : "";
$(window)
.ready(checkIfProductIsCustomizable(extraQueryString, designId))
.ready(hideArtifiDesignIdPdfXmlFields());
}
/**This Function is Used to Hide Artifi Design Id, Artifi PDF and Artifi Xml Fileds on PDP page using "regexDesignIdPdfXml" regex
*/
function hideArtifiDesignIdPdfXmlFields() {
var pattern = regexDesignIdPdfXml;
$('#bigCommerceAddToCartForm').find('label').each(function () {
var html = $(this).html(),
result = pattern.exec(html);
if (result !== null) {
var field = $(this).siblings('input');
if (field.length === 1) {
$(field).val(0)
.hide();
$('label[for="' + field.attr('id') + '"]').hide();
$(field).siblings('label').hide();
}
}
pattern.lastIndex = 0;
});
}
function getArtifiDesignIdFieldObj() {
var fieldObj = false,
pattern = /Artifi\sDesign\sId/g;
$('#bigCommerceAddToCartForm').find('label').each(function () {
var html = $(this).html(),
result = pattern.exec(html);
if (result !== null) {
var fieldContainer = $(this).siblings('input');
if (fieldContainer.length === 1) {
fieldObj = fieldContainer;
}
}
});
return fieldObj;
}
/**
* The function returns the 'textarea' element if found, or 'false' if not.
* @returns
*/
function getArtifiPersonalizedDataFieldObj() {
var fieldObj = false,
pattern = /Artifi\sPersonalized\sData/g;
// First attempt: Check for label
$('#bigCommerceAddToCartForm').find('label').each(function () {
var html = $(this).html(),
result = pattern.exec(html);
if (result !== null) {
var fieldContainer = $(this).siblings('textarea');
if (fieldContainer.length === 1) {
fieldObj = fieldContainer;
}
}
});
// Second attempt: Check for data-label-name attribute if label not found
if (fieldObj === false) {
$('#bigCommerceAddToCartForm').find('div[data-label-name="artifi-personalized-data"]').each(function () {
var fieldContainer = $(this).find('textarea');
if (fieldContainer.length === 1) {
fieldObj = fieldContainer;
}
});
}
return fieldObj;
}
/**
* This Function returns "input" DOM object as per matching label from input "regex" else false if not found
* @param {any} regex
*/
function getFieldObjByRegex(regex) {
var fieldObj = false,
pattern = regex;
$('#bigCommerceAddToCartForm').find('label').each(function () {
var html = $(this).html(),
result = pattern.exec(html);
if (result !== null) {
var fieldContainer = $(this).siblings('input');
if (fieldContainer.length === 1) {
fieldObj = fieldContainer;
}
}
pattern.lastIndex = 0;
});
return fieldObj;
}
function addToCartEventHandler(cartItemRows) {
var cartItems = Cookies.get(BigCommerceArtifi.Constants.cartItemsCookieName);
var endpoint = 'cart';
if (cartItems) {
cartItems = JSON.parse(cartItems);
} else {
cartItems = [];
}
cartItemRows.each(function (key, val) {
var row = $(this),
cartItemId = row.attr('data-cart-item-id'),
productId = row.attr('data-product-id'),
productSku = row.attr('data-product-sku');
if (cartItems.indexOf(cartItemId) > -1) {
// Continue to next iteration.
return true;
}
cartItems.push(cartItemId);
if (!artifiAddToCartEventObject) {
return false;
}
if (!artifiAddToCartEventObject.data) {
return false;
}
var artifiProductSku = artifiAddToCartEventObject.data.sku;
if (artifiProductSku.toLowerCase() !== productSku.toLowerCase()) {
return true;
}
BigCommerceArtifi.Application.sendRequest(
endpoint,
'POST',
JSON.stringify({
'productId': productId,
'cartItemId': cartItemId,
'designId': artifiAddToCartEventObject.data.custmizeProductId,
'previewUrl': artifiAddToCartEventObject.data.savedDesignStandardImages[0],
'customerId': BigCommerceArtifi.Customer.getCustomerId()
}),
BigCommerceAddToCartSuccessHdl
);
// Break each loop.
return false;
});
Cookies.set(BigCommerceArtifi.Constants.cartItemsCookieName, JSON.stringify(cartItems));
}
function BigCommerceAddToCartSuccessHdl() {
var sku = $('.productView').find('[data-product-sku]').text().trim();
isArtifiInitialize = false;
insertArtifiDesigner(initResponse.ProductSku, sku, extraQueryStringOption);
var field = getArtifiDesignIdFieldObj();
$(field).val(0);
var fieldPDF = getFieldObjByRegex(regexArtifiPDF);
var fieldXML = getFieldObjByRegex(regexArtifiXML);
$(fieldPDF).val(0);
$(fieldXML).val(0);
artifiAddToCartEventObject = null;
artifiReactAddToCartEventObject = null;
}
function updatePreviewPopup(previewUrl) {
if (!previewUrl) {
if (artifiAddToCartEventObject && artifiAddToCartEventObject.data) {
previewUrl = artifiAddToCartEventObject.data.savedDesignStandardImages[0];
} else {
return false;
}
}
//HideArtifiDesignID,PDF&XML fields
var labelsCollectionSelector = $('.previewCart')
.find('.productView-details')
.find('.productView-info-name'),
pattern = regexDesignIdPdfXml;
labelsCollectionSelector.each(function () {
var html = $(this).html(),
result = pattern.exec(html);
if (result !== null) {
$(this)
.next('dd')
.hide();
$(this)
.hide();
}
pattern.lastIndex = 0;
});
//replace Preview Thumbnail
var imageElement = $('.previewCart').find('.productView-img-container');
var image = new Image();
image.src = previewUrl;
image.onload = function () {
imageElement
.find('img')
.attr('src', previewUrl)
.attr('srcset', previewUrl)
};
}
/**
* This function checks if a product is customizable by making a request to a specific endpoint.
* @param {any} extraQueryString
* @param {any} designId
*/
function checkIfProductIsCustomizable(extraQueryString, designId) {
if (productId) {
var endpoint = 'products/' + productId + '/iscustomized';
BigCommerceArtifi.Application.sendRequest(
endpoint,
'GET',
'',
function (response) {
prepareToInitArtifiDesigner(response, extraQueryString, designId);
},
'',
showAddToCartButton
);
}
}
/**
* Prepares to initialize the Artifi Designer by first fetching customer details.
* Fetches customer data using the 'customerEmail'. Once the customer data is fetched,
* it calls 'initArtifiDesigner' with the response, additional query string, and design ID.
* @param {any} response
* @param {any} extraQueryString
* @param {any} designId
*/
function prepareToInitArtifiDesigner(response, extraQueryString, designId) {
BigCommerceArtifi.Customer.fetchAndUpdateCustomerData(customerEmail, function (customer) {
initArtifiDesigner(response, extraQueryString, designId);
});
}
function showAddToCartButton() {
$(addToCartSelector).show();
}
function registerArtifiEventHandler() {
if (window.addEventListener) {
addEventListener("message", receiveMessage, false);
} else {
attachEvent("onmessage", receiveMessage);
}
}
window.addEventListener("artifi-initialized", function (e) {
console.log("artifi-initialized", e.detail.data
);
});
window.addEventListener("artifi-add-to-cart-success", function (e) {
console.log("artifi-add-to-cart-success", e.detail.data
);
reactArtifiAddToCartEventHandler(JSON.parse(e.detail.data));
});
/**
* Handles the Artifi "Add to Cart" event by setting up necessary fields and managing cart actions.
* Sets the event data, retrieves and updates various input fields with customization details (Design ID, PDF URL, XML URL, and personalized data).
* If in edit mode, it checks the cart for the existing item, removes it, and re-adds the updated item to the cart.
* If not in edit mode, it directly adds the customized product to the cart.
* @param {any} artifiReactEventData
*/
function reactArtifiAddToCartEventHandler(artifiReactEventData) {
artifiReactAddToCartEventObject = artifiReactEventData;
var customizedId = artifiReactEventData.designId;
var field = getArtifiDesignIdFieldObj();//Get input DOM objects
var fieldPDF = getFieldObjByRegex(regexArtifiPDF);
var fieldXML = getFieldObjByRegex(regexArtifiXML);
var personalizedDataField = getArtifiPersonalizedDataFieldObj();
if(field)
{
$(field).val(customizedId);
}
if (fieldPDF)
{
$(fieldPDF).val(BigCommerceArtifi.Application.getPDFUrl(customizedId)); // Insert PDF Link
}
if (fieldXML)
{
$(fieldXML).val(BigCommerceArtifi.Application.getXMLUrl(customizedId)); // Insert XML Link
}
if (personalizedDataField)
{
$(personalizedDataField).val(JSON.stringify(artifiReactEventData));
}
var designId = isInEditMode();
if (designId) {
function handleCart(cart) {
var cartId = cart.id;
var cartItemId = BigCommerceArtifi.Application.getUrlParameter('cartItemId');
var quantityInput = document.querySelector(`input#qty-${cartItemId}`);
var quantity = quantityInput ? parseInt(quantityInput.value) : 1;
var existingItem = cart.lineItems.physicalItems.find(item => item.id === cartItemId);
if (!existingItem)
{
existingItem = cart.lineItems.digitalItems.find(item => item.id === cartItemId);
}
if (existingItem) {
// Remove the specific item from the cart
$.ajax({
type: 'DELETE',
url: `/api/storefront/carts/${cartId}/items/${existingItem.id}`,
contentType: 'application/json',
success: function (response) {
console.log('Cart item deleted successfully:', response);
// Re-add the updated product to the cart
BigCommerceArtifi.Application.sendRequest(
'cart',
'POST',
JSON.stringify({
'productId': productId,
'designId': artifiReactEventData.designId,
'previewUrl': artifiReactEventData.previewUrl,
'customerId': BigCommerceArtifi.Customer.getCustomerId()
}),
BigCommerceAddToCartSuccessHdl
);
$(addToCartSelector).trigger('click');
},
error: function (xhr, status, error) {
console.error('Error deleting cart item:', status, error);
console.error('Response:', xhr.responseText);
}
});
}
}
function getCartId(callback) {
fetch('/api/storefront/cart', {
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.length > 0) {
callback(data[0]);
} else {
console.error('No cart found');
}
})
.catch(error => {
console.error('Error fetching cart:', error);
});
}
getCartId(handleCart);
} else {
var endpoint = 'cart';
BigCommerceArtifi.Application.sendRequest(
endpoint,
'POST',
JSON.stringify({
'productId': productId,
'designId': artifiReactEventData.designId,
'previewUrl': artifiReactEventData.previewUrl,
'customerId': BigCommerceArtifi.Customer.getCustomerId()
}),
BigCommerceAddToCartSuccessHdl
);
$(addToCartSelector).trigger('click');
}
}
function receiveMessage(eventObject) {
if (eventObject === null || typeof eventObject !== 'object') {
return false;
}
var eventData = {};
try {
eventData = JSON.parse(eventObject.data);
} catch (e) {
return false;
}
switch (eventData.action) {
case 'add-to-cart':
artifiAddToCartEventHandler(eventData);
break;
case 'sku-changed':
artifiSkuChangedEventHandler(eventData);
break;
}
}
function artifiAddToCartEventHandler(eventData) {
artifiAddToCartEventObject = eventData;
var customizedId = artifiAddToCartEventObject.data.custmizeProductId;
var field = getArtifiDesignIdFieldObj();//Get input DOM objects
var fieldPDF = getFieldObjByRegex(regexArtifiPDF);
var fieldXML = getFieldObjByRegex(regexArtifiXML);
$(field).val(customizedId);//Insert Artifi Design ID
$(fieldPDF).val(BigCommerceArtifi.Application.getPDFUrl(customizedId));//Insert PDF Link
$(fieldXML).val(BigCommerceArtifi.Application.getXMLUrl(customizedId));//Insert XML Link
var designId = isInEditMode();
// if (isNaN(designId)) {
// designId = eventData.data.custmizeProductId;
// }
if (designId) {
var endpoint = 'cart';
BigCommerceArtifi.Application.sendRequest(
endpoint,
'PUT',
JSON.stringify({
'designId': artifiAddToCartEventObject.data.custmizeProductId,
'previewUrl': artifiAddToCartEventObject.data.savedDesignStandardImages[0],
'customerId': BigCommerceArtifi.Customer.getCustomerId()
}),
function () {
var cartItemId = BigCommerceArtifi.Application.getUrlParameter('cart-item-id');
$('#SH-ProductOption input[name="action"]').val("EditProductFieldsInCart")
editModeHTML = editModeHTML.replace("{{cart-item-id}}", cartItemId)
$("#SH-ProductOption").append(editModeHTML);
var data = $("#SH-ProductOption").serializeArray();
$.post('/cart.php', data).done(function () {
document.location.href = '/cart.php';
});
}
);
} else {
toggleArtifiDesigner();
var endpoint = 'cart';
BigCommerceArtifi.Application.sendRequest(
endpoint,
'POST',
JSON.stringify({
'productId': productId,
'designId': artifiAddToCartEventObject.data.custmizeProductId,
'previewUrl': artifiAddToCartEventObject.data.previewUrl,
'customerId': BigCommerceArtifi.Customer.getCustomerId()
}),
BigCommerceAddToCartSuccessHdl
);
$(addToCartSelector).trigger('click');
}
}
/**
* This changes only for SSW (APD-22831). This code will reframe in future.
* @param {any} eventData
* @returns
*/
function artifiSkuChangedEventHandler(eventData) {
var newSku = eventData.data.sku;
if (!productOptions || productOptions === null) {
productOptions = [];
}
if (!productOptions[newSku]) {
return false;
}
/* THis will change According to the Client*/
$.each(productOptions[newSku], function (index, sku) {
if (!BigCommerceArtifi.isEventIsAlreadyRegistered) {
$(document).find('.productView-details input[type="radio"]').bind("change", function (e) { getSelectedSkuByOptionId(this.value) });
$(document).find('#ProductDetails .productOptionPickListSwatch input[type="radio"], .productOptionPickListDropDown select').bind("change", function (e) { getSelectedSkuByOptionId(this.value) });
$(document).find('#ProductDetails .productOptionPickListSwatch input[type="radio"], .productOptionPickListDropDown select').bind("change", function (e) { getSelectedSkuByOptionId(this.value) });
BigCommerceArtifi.isEventIsAlreadyRegistered = true;
}
$("#ProductDetails .form-field , #bigCommerceAddToCartForm .form-field").each(function (key) {
var listOfselectedComb = {}
var parent = sku.option_id;
var val = sku.id;
if ($(this).is('[data-product-attribute="swatch"]')) {
if (!$(this).find('input#attribute_swatch_' + parent + '_' + val + '[value="' + val + '"]').is(':checked')) {
$(this).find('input#attribute_swatch_' + parent + '_' + val + '[value="' + val + '"]').click();
}
}
if ($(this).is('[data-product-attribute="set-select"]')) {
if ($(this).find('select option[data-product-attribute-value="' + parent + '"][value="' + val + '"]').attr("selected", "selected")) {
$(this).find('select option[data-product-attribute-value="' + parent + '"][value="' + val + '"]').click();
}
}
if ($(this).is('[data-product-attribute="set-rectangle"]')) {
if (!$(this).find('input#attribute_rectangle_' + parent + '_' + val + '[name="attribute[' + parent + ']"][value="' + val + '"]').is(':checked')) {
$(this).find('input#attribute_rectangle_' + parent + '_' + val + '[name="attribute[' + parent + ']"][value="' + val + '"]').click();
}
}
if ($(this).is('[data-product-attribute="set-radio"]')) {
if (!$(this).find('input#attribute_radio__' + parent + '_' + val + '[value="' + val + '"]').is(':checked')) {
$(this).find('input#attribute_radio_' + parent + '_' + val + '[value="' + val + '"]').click();
}
}
})
});
}
/**
* Adds the "sku-changed" event handler.
*/
function attachArtifiSkuChangedEventHandler() {
if (!BigCommerceArtifi.isEventIsAlreadyRegistered) {
window.addEventListener("sku-changed", artifiSkuChangedEventHandler, false);
BigCommerceArtifi.isEventIsAlreadyRegistered = true;
}
}
/**
* Removes the "sku-changed" event handler.
*/
function detachArtifiSkuChangedEventHandler() {
if (BigCommerceArtifi.isEventIsAlreadyRegistered) {
window.removeEventListener("sku-changed", artifiSkuChangedEventHandler, false);
BigCommerceArtifi.isEventIsAlreadyRegistered = false;
}
}
function getSelectedSkuByOptionId(optionId) {
var selectedCombination = getSelectedOptionArray();
var isValidDetails = false;
var selectedSku;
$.each(productOptions, function (key, value) {
for (var i = 0; i < value.length; i++) {
if (getOptionValue(value[i].product_option_id, selectedCombination) == value[i].option_value_id) {
isValidDetails = true;
} else {
isValidDetails = false;
break;
}
}
if (value.length != selectedCombination.length) {
isValidDetails = false;
}
if (isValidDetails) {
selectedSku = key
}
});
initArtifiDesignerBySku(selectedSku);
}
function getOptionValue(product_option_id, selectedCombination) {
if (selectedCombination) {
for (var j = 0; j < selectedCombination.length; j++) {
if (selectedCombination[j].product_option_id == product_option_id) {
return selectedCombination[j].option_value_id
break;
}
}
}
return 0;
}
/*
Function for getting list of selected cobination
*/
function getSelectedOptionArray() {
var selectedCombination = [];
$("#bigCommerceAddToCartForm .form-field").each(function (key, val) {
var listOfselectedComb = {}
if ($(this).is('[data-product-attribute="swatch"]')) {
var parent = $(this).attr("data-art-parent");
var val = $(this).find('input[data-attr-parent="' + parent + '"]:checked').val()
listOfselectedComb["product_option_id"] = parent;
listOfselectedComb["option_value_id"] = val;
selectedCombination.push(listOfselectedComb)
}
if ($(this).is('[data-product-attribute="set-select"]')) {
var parent = $(this).attr("data-art-parent");
var val = $(this).find('select option[data-attr-parent="' + parent + '"]:selected').val()
listOfselectedComb["product_option_id"] = parent;
listOfselectedComb["option_value_id"] = val;
selectedCombination.push(listOfselectedComb)
}
if ($(this).is('[data-product-attribute="set-rectangle"]')) {
var parent = parseInt($(this).find('input:checked').attr("name").match(/\d+/));
var val = $(this).find('input:checked').val();
listOfselectedComb["product_option_id"] = parent;
listOfselectedComb["option_value_id"] = val;
selectedCombination.push(listOfselectedComb)
}
})
return selectedCombination;
}
function compareTwoObj(obj1, obj2) {
//Loop through properties in object 1
for (var p in obj1) {
//Check property exists on both objects
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
switch (typeof (obj1[p])) {
//Deep compare objects
case 'object':
if (!compareTwoObj(obj1[p], obj2[p])) return false;
break;
//Compare function code
case 'function':
if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;
break;
//Compare values
default:
if (obj1[p] != obj2[p]) return false;
}
}
//Check object 2 for any extra properties
for (var p in obj2) {
if (typeof (obj1[p]) == 'undefined') return false;
}
return true;
};
function initArtifiDesignerBySku(selectedskU) {
insertArtifiDesigner('', selectedskU);
}
function fetchProductOptions(callback) {
var endpoint = 'products/' + productId + '/skus';
BigCommerceArtifi.Application.sendRequest(
endpoint,
'GET',
'',
function (response) {
productOptions = response;
callback();
}
);
}
/**
* Initializes Artifi Designer based on response:
* - If response.Result is 1:
* - Sets initResponse and productSku.
* - Handles integrationType:
* - 'false' (iframe): Inserts customize button and Artifi designer.
* - 'true' (React): Hides product images, adds customize button, and initializes Artifi.
* @param {any} response
* @param {any} extraQueryString
* @param {any} designId
*/
function initArtifiDesigner(response, extraQueryString, designId) {
if (response.Result === 1) {
initResponse = response;
productSku = response.ProductSku;
var sku = $('.productView').find('[data-product-sku]').text().trim();
var integrationType = BigCommerceArtifi.Application.getIntegrationType();
if (integrationType && integrationType.toLowerCase() == 'false') {
if (!sku && !response.IsSimple)
sku = editModeSKU();
fetchProductOptions(function () {
insertCustomizeButton(initResponse.CustomizedButtonLabel, initResponse.IsOptional, initResponse.ProductSku, extraQueryString);
const event = new CustomEvent('artifi-customize-button-inserted');
document.dispatchEvent(event);
});
}
else if (integrationType && integrationType.toLowerCase() == 'true') {
$('.productView').find('.productView-images').css('display', 'none');
$(personalizeButtonContainer).append(addtoCartButton);
$('#form-action-addToCart').hide();
initializeArtifi(sku, designId);
var button = document.getElementById('artifiaddtocart');
button.addEventListener('click', function () {
Artifi.addToCart();
});
}
registerArtifiEventHandler();
} else {
showAddToCartButton();
}
BigCommerceArtifi.Customer.setFetchingInProgress(false);
}
window.addEventListener("artifi-initialized", function (e) {
console.log("artifi-initialized", e.detail.data
);
});
function toggleArtifiDesigner(designId) {
var integrationType = BigCommerceArtifi.Application.getIntegrationType();
if (integrationType && integrationType.toLowerCase() == 'false') {
if (designId && $('#bigcommerce-artifi-iframe-container').is(":visible")) {
document.location.href = '/cart.php';
}
window.scrollTo(0, 50);
$('#bigcommerce-artifi-iframe-container').toggle();
if ($('#bigcommerce-artifi-iframe-container').css('visibility') == 'hidden') {
$('#bigcommerce-artifi-iframe-container').css('visibility', 'visible');
$('#bigcommerce-artifi-iframe-container').css({ 'position': 'initial', 'left': '0', 'display': 'block' })
$('.productView').css('display', 'none');
$('#artifiAddToCart').css('display', 'block');
}
else {
$('#bigcommerce-artifi-iframe-container').css('visibility', 'hidden');
$('.productView').css('display', 'block');
$('#artifiAddToCart').css('display', 'none');
detachArtifiSkuChangedEventHandler(); // Detach the event listener
}
}
}
function insertCustomizeButton(buttonLabel, IsOptional, productSku, extraQueryString) {
if (personalizeButton) {
personalizeButton = personalizeButton.replace(new RegExp("{personalizeButtonLabel}", 'g'), buttonLabel);
} else {
var personalizeButton = $('
');
personalizeButton.css({
'display': 'inline-block',
});
personalizeButton.attr('id', '');
personalizeButton.attr('class', '');
personalizeButton.html('
');
personalizeButton.attr('onClick', "BigCommerceArtifi.ProductPage.launchDesignerForVariant('" + productSku + "', '" + extraQueryString + "');");
}
if (IsOptional == 1) {
$(addToCartSelector).show();
}
if (personalizeButtonContainer) {
$(personalizeButtonContainer).append(personalizeButton);
} else {
$('#ProductDetails').find('.addto').append(personalizeButton);
}
}
/*
*This method will initialize designer if an variant sku is selected.
*@param @string @productSku - Parent SKU of product.
*@param @string @extraQueryString - additional parameter for launching
*/
function launchDesignerForVariant(productSku, extraQueryString) {
var sku = $('.productView').find('[data-product-sku]').text().trim();
if (sku && productSku) {
attachArtifiSkuChangedEventHandler();
insertArtifiDesigner(productSku, sku, extraQueryString);
toggleArtifiDesigner();
}
}
function triggerAddToCartEvent() {
Artifi.AddToCart();
};
function isInEditMode() {
var designId = BigCommerceArtifi.Application.getUrlParameter('designId');
return parseInt(designId);
}
function editModeSKU() {
var designId = BigCommerceArtifi.Application.getUrlParameter('designId');
var sku = ""
if (designId) {
sku = BigCommerceArtifi.Application.getUrlParameter('sku');
}
return sku;
}
function insertArtifiDesigner(productSku, sku, extraQueryString) {
var integrationType = BigCommerceArtifi.Application.getIntegrationType();
if (integrationType && integrationType.toLowerCase() == 'false') {
if (!productSku && !sku) {
/*Commented out to troubleshoot issue with 'Refrigiwear' where 'productSku' was coming as undefined,
causing the 'Personalize' button to be disabled. After commenting, all conditions have been verified
and the functionality is working correctly. */
//$('input[type="button"][value="Personalize"]').attr("disabled", "disabled");
return
}
$('input[type="button"][value="Personalize"]').attr("disabled", false);
if (sku && productSku && productSku !== sku) {
isArtifiInitialize = false;
}
if (isArtifiInitialize && sku) {
Artifi.setSkuDetails(sku);
return true;
}
$("#bigcommerce-artifi-iframe-container").remove();
$("#bigcommerce-artifi-background").remove();
var personalizeContainer = "";
if (personalizeIframeContainer) {
personalizeContainer = $(personalizeIframeContainer);
} else {
personalizeContainer = $('#ProductDetails')
}
var customerId = BigCommerceArtifi.Customer.getCustomerId(),
isGuest = customerId ? false : true,
width = personalizeContainer.width();
var designId = isInEditMode();
var background = $('