/**
* Блок T1002, находится в категории "Магазин"
* Скрипт добавляет на страницу виджет вишлиста и кнопку "Добавить в избранное" для каждого товара на странице.
* Список избранного хранится в localStorage.
* Используется вместе с блоками товаров (ST***), в этих блоках и скрипте tilda-catalog-1.1.js
* триггерится событие 'twishlist_addbtn', которое запускает отрисовку кнопок для товаров
* (актуально для попапов/сниппетов и динамически отрисовываемых товаров).
*/
// global variables declaration
window.t_wishlist__isiOS = false;
if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
window.t_wishlist__isiOS = true;
}
window.t_wishlist__iOSMajorVersion = 0;
if (window.t_wishlist__isiOS) {
var version = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
if (version !== null) {
window.t_wishlist__iOSMajorVersion = parseInt(version[1], 10);
}
}
window.t_wishlist__browserLang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2);
/**
* Language override based on attribute
*/
t_onReady(function () {
var allrecords = document.getElementById('allrecords');
var projectLang;
if (allrecords) {
projectLang = allrecords.getAttribute('data-tilda-project-lang');
}
if (projectLang) {
window.t_wishlist__browserLang = projectLang;
}
});
function twishlist__init(recid) {
var wishlistBlock = document.querySelector('.t1002');
if (!wishlistBlock) return;
var wishlistBlocksLength = document.querySelectorAll('.t1002').length;
var rec = document.querySelector('#rec' + recid);
// предотвращает несколько инициализаций
if (window.twishlist_initted === 'yes' && wishlistBlocksLength > 1) {
var errorText =
window.t_wishlist__browserLang === 'RU'
? 'Ошибка: На странице присутствуют ' +
wishlistBlocksLength +
' виджета избранного (блок ST110). Пожалуйста, удалите дубликаты. Блоки могут находиться на странице Header или Footer.'
: 'Error: ' +
wishlistBlocksLength +
' wishlist widgets (block ST110) on the page. Remove a duplicate. Blocks can be on the Header or Footer page.';
if (!document.querySelector('.t1002__previewmode-infobox .t1002__previewmode-infobox-error')) {
Array.prototype.forEach.call(
document.querySelectorAll('.t1002__previewmode-infobox center'),
function (infobox) {
infobox.insertAdjacentHTML(
'beforeend',
'
' + errorText + '
'
);
}
);
}
if (window.twishlist_erroralert === undefined) {
alert(errorText);
window.twishlist_erroralert = 'yes';
console.error('Error: Two wishlist widgets (block ST110) on the page. Remove a duplicate.');
}
return;
}
// сколько дней товар хранится в избранном
var maxStoreDays = wishlistBlock.getAttribute('data-wishlist-maxstoredays');
if (maxStoreDays) {
window.twishlist_maxstoredays = maxStoreDays;
}
window.twishlist_initted = 'yes';
/**
* TODO: подключение нового скрипта осуществляется через блоки ST100, ST110 и T985,
* но данный скрипт подключится после переопубликации страниц,
* чтобы не рассинхронизировать скрипты и правки в уще существующих файлах, проверяем, есть скрипт на странице или нет,
* если его нету, загружаем, возможно через какое то время удалить данную проверку, дата публикации 16.12.24
*/
if (!document.querySelector('script[src*="tilda-widget-positions"]')) {
t_onFuncLoad('t_loadJsFile', () => {
t_loadJsFile(
'https://static.tildacdn.' + twishlist__getRootZone() + '/js/tilda-widget-positions-1.0.min.js'
);
});
}
twishlist__loadLocalObj();
twishlist__reDrawCartIcon();
twishlist__addEvent__links();
twishlist__addEvents();
twishlist__addProductButtons();
setTimeout(function () {
var hash;
try {
hash = decodeURIComponent(document.location.hash);
} catch (error) {
hash = document.location.hash;
}
// добавление в избранное с любой кнопки по ссылке
if (hash && hash.indexOf('#addtofavorites:') !== -1) {
var customWishlistBtn = document.querySelector('a[href="' + hash + '"]');
customWishlistBtn.click();
}
});
// отключает эффект появления при скролле
rec.setAttribute('data-animationappear', 'off');
rec.style.opacity = '1';
// добавляет дефолтный заголовок для попапа
var wishlistHeading = wishlistBlock.querySelector('.t1002__wishlistwin-heading');
if (wishlistHeading.innerHTML == '') {
wishlistHeading.innerHTML = twishlist_dict('yourWishlist') + ':';
}
}
function twishlist_dict(msg) {
var dict = [];
dict['yourWishlist'] = {
EN: 'Favorites',
RU: 'Избранное',
FR: 'Favoris',
DE: 'Favoriten',
ES: 'Favoritos',
PT: 'Favoritos',
JA: 'お気に入り',
ZH: '收藏',
UK: 'Вибране',
PL: 'Ulubione',
KK: 'Таңдаулылар',
IT: 'Preferiti',
LV: 'Izlase',
};
dict['youAdd'] = {
EN: 'added to favorites',
RU: 'добавлено в избранное',
FR: 'enregistré dans les favoris',
DE: 'in favoriten gespeichert',
ES: 'guardado en favoritos',
PT: 'guardado nos favoritos',
JA: 'お気に入り に保存しました',
ZH: '已添加到愿望清单',
UK: 'додано у вибране',
PL: 'zapisano w ulubionych',
KK: 'таңдаулыларға қосылды',
IT: 'salvato nei preferiti',
LV: 'pievienots izlasei',
};
dict['undo'] = {
EN: 'Undo',
RU: 'Вернуть',
FR: 'Annuler',
DE: 'Rückgängig',
ES: 'Deshacer',
PT: 'Desfazer',
JA: '元に戻す',
ZH: '撤销',
UK: 'Повернути',
PL: 'Powrót',
KK: 'Болдырмау',
IT: 'Disfare',
LV: 'Atcelt',
};
dict['mm'] = {
EN: 'mm',
RU: 'мм',
FR: 'mm',
DE: 'mm',
ES: 'mm',
PT: 'mm',
UK: 'мм',
JA: 'mm',
ZH: 'mm',
PL: 'mm',
KK: 'мм',
IT: 'mm',
LV: 'mm',
};
dict['g'] = {
EN: 'g',
RU: 'г',
FR: 'g',
DE: 'g',
ES: 'g',
PT: 'g',
UK: 'г',
JA: 'g',
ZH: 'g',
PL: 'r',
KK: 'г',
IT: 'g',
LV: 'g',
};
dict['PCE'] = {
EN: 'pc',
RU: 'шт' /* штук */,
};
dict['NMP'] = {
EN: 'pack',
RU: 'уп' /* упаковка */,
};
dict['MGM'] = {
EN: 'mg',
RU: 'мг' /* миллиграмм */,
};
dict['GRM'] = {
EN: 'g',
RU: 'г' /* грамм */,
};
dict['KGM'] = {
EN: 'kg',
RU: 'кг' /* килограмм */,
};
dict['TNE'] = {
EN: 't',
RU: 'т' /* тонна */,
};
dict['MLT'] = {
EN: 'ml',
RU: 'мл' /* миллилитр */,
};
dict['LTR'] = {
EN: 'l',
RU: 'л' /* литр */,
};
dict['MMT'] = {
EN: 'mm',
RU: 'мм' /* миллиметр */,
};
dict['CMT'] = {
EN: 'cm',
RU: 'см' /* сантиметр */,
};
dict['DMT'] = {
EN: 'dm',
RU: 'дм' /* дециметр */,
};
dict['MTR'] = {
EN: 'm',
RU: 'м' /* метр */,
};
dict['MTK'] = {
EN: 'm²',
RU: 'м²' /* квадратный метр */,
};
dict['MTQ'] = {
EN: 'm³',
RU: 'м³' /* кубический метр */,
};
dict['LMT'] = {
EN: 'lm',
RU: 'пог. м' /* погонный метр */,
};
dict['HAR'] = {
EN: 'ha',
RU: 'га' /* гектар */,
};
dict['ACR'] = {
EN: 'acre',
RU: 'акр',
};
if (dict[msg]) {
if (dict[msg][window.t_wishlist__browserLang]) {
return dict[msg][window.t_wishlist__browserLang];
} else {
return dict[msg]['EN'];
}
}
return 'Text not found #' + msg;
}
function twishlist__nullObj() {
var twishlist = {};
twishlist['products'] = [];
twishlist['prodamount'] = 0;
twishlist['amount'] = 0;
return twishlist;
}
/**
* Загружает вишлист из localStorage, устанавливает отображение валюты
*/
function twishlist__loadLocalObj() {
var dataJsonStr = null;
var timestamp;
var delta;
if (typeof localStorage === 'object') {
try {
dataJsonStr = localStorage.getItem('twishlist');
} catch (e) {
console.error('Your web browser does not support storing a Wishlist data locally.');
}
}
if (dataJsonStr === null) {
window.twishlist = twishlist__nullObj();
} else {
window.twishlist = JSON.parse(dataJsonStr);
}
// удаляет из window.twishlist пустые или удаленные товары
if (window.twishlist['products'] !== undefined) {
var actualProductsObj = [];
var oldCountProducts = window.twishlist['products'].length;
window.twishlist['products'].forEach(function (product) {
if (!twishlist__isEmptyObject(product) && product.deleted !== 'yes') {
actualProductsObj.push(product);
}
});
window.twishlist['products'] = actualProductsObj;
var actualCountProducts = window.twishlist['products'].length;
if (actualCountProducts !== oldCountProducts) {
twishlist__saveLocalObj();
}
}
// проверяет срок хранения в вишлисте
if (window.twishlist_maxstoredays) {
var maxStoreDays = window.twishlist_maxstoredays;
if (maxStoreDays > 0) {
if (window.twishlist.updated > 0) {
timestamp = Math.floor(Date.now() / 1000);
delta = timestamp * 1 - window.twishlist.updated * 1;
if (delta > 60 * 60 * 24 * maxStoreDays) {
if (typeof localStorage === 'object') {
window.twishlist.products = [];
localStorage.setItem('twishlist', JSON.stringify(window.twishlist));
}
window.twishlist = twishlist__nullObj();
}
}
} else if (maxStoreDays == '0') {
window.twishlist = twishlist__nullObj();
}
} else if (window.twishlist.updated > 0) {
timestamp = Math.floor(Date.now() / 1000);
delta = timestamp * 1 - window.twishlist.updated * 1;
if (delta > 60 * 60 * 24 * 30) {
window.twishlist = twishlist__nullObj();
}
}
// устанавливает дефолтное отображение валюты
delete window.twishlist['currency'];
delete window.twishlist['currency_txt'];
delete window.twishlist['currency_txt_l'];
delete window.twishlist['currency_txt_r'];
delete window.twishlist['currency_side'];
delete window.twishlist['currency_sep'];
delete window.twishlist['currency_dec'];
window.twishlist['currency'] = '$';
window.twishlist['currency_side'] = 'l';
window.twishlist['currency_sep'] = '.';
window.twishlist['currency_dec'] = '';
// если валюта задана в настройках user payment
var wishlistBlock = document.querySelector('.t1002');
if (!wishlistBlock) return;
var paymentCurrency = wishlistBlock.getAttribute('data-userpayment-currency');
if (paymentCurrency) {
window.twishlist['currency'] = paymentCurrency;
}
//////
// если валюта задана в настройках проекта:
var projectCurrency = wishlistBlock.getAttribute('data-project-currency');
if (projectCurrency) {
window.twishlist['currency'] = projectCurrency;
}
// название валюты
window.twishlist['currency_txt'] = window.twishlist['currency'];
// расположение значка валюты
projectCurrency = wishlistBlock.getAttribute('data-project-currency-side');
if (projectCurrency == 'r') {
window.twishlist['currency_side'] = 'r';
}
if (window.twishlist['currency_side'] == 'l') {
window.twishlist['currency_txt_l'] = window.twishlist['currency_txt'] + '';
window.twishlist['currency_txt_r'] = '';
} else {
window.twishlist['currency_txt_r'] = ' ' + window.twishlist['currency_txt'];
window.twishlist['currency_txt_l'] = '';
}
// десятичный разделитель
projectCurrency = wishlistBlock.getAttribute('data-project-currency-sep');
if (projectCurrency == '.' || projectCurrency == ',') {
window.twishlist['currency_sep'] = projectCurrency;
} else if (
window.twishlist['currency'] == '$' ||
window.twishlist['currency'] == '€' ||
window.twishlist['currency'] == 'USD' ||
window.twishlist['currency'] == 'EUR'
) {
window.twishlist['currency_sep'] = '.';
} else {
window.twishlist['currency_sep'] = ',';
}
// десятичный формат
projectCurrency = wishlistBlock.getAttribute('data-project-currency-dec');
if (projectCurrency == '00') {
window.twishlist['currency_dec'] = projectCurrency;
} else {
window.twishlist['currency_dec'] = '';
}
twishlist__updateTotalProductsObj();
}
/**
* Сохраняет объект window.twishlist в localStorage, обновляет дату изменения
*/
function twishlist__saveLocalObj() {
// если max days == 0 - не сохраняем
if (typeof window.twishlist_maxstoredays != 'undefined' && window.twishlist_maxstoredays == 0) {
return;
}
if (typeof window.twishlist == 'object') {
window.twishlist.updated = Math.floor(Date.now() / 1000);
var dataJsonStr = JSON.stringify(window.twishlist);
if (typeof localStorage === 'object') {
try {
localStorage.setItem('twishlist', dataJsonStr);
} catch (e) {
console.error('Your web browser does not support storing a Wishlist data locally.');
}
}
}
}
/**
* Синхронизирует товары в объекте window.twishlist и localStorage
*/
function twishlist__syncProductsObject__LStoObj() {
if (typeof window.twishlist_maxstoredays != 'undefined' && window.twishlist_maxstoredays == 0) {
return;
}
if (typeof localStorage === 'object') {
try {
var lsJsonStr = localStorage.getItem('twishlist');
var lsJsonObj = JSON.parse(lsJsonStr);
if (typeof lsJsonObj['products'] == 'object') {
// удаляет из window.twishlist пустые или удаленные товары
var actualProductsObj = [];
var oldCountProducts = lsJsonObj['products'].length;
lsJsonObj['products'].forEach(function (product) {
if (!twishlist__isEmptyObject(product) && product.deleted !== 'yes' && product.quantity > 0) {
actualProductsObj.push(product);
}
});
window.twishlist['products'] = actualProductsObj;
var actualCountProducts = window.twishlist['products'].length;
if (actualCountProducts !== oldCountProducts) {
twishlist__saveLocalObj();
}
twishlist__updateTotalProductsObj();
}
} catch (e) {
/* */
}
}
}
/**
* Добавляет кнопку с сердечком на каждую карточку товара
*/
function twishlist__addProductButtons() {
var productElementsList = document.querySelectorAll('.js-product');
var wishlistBtnPosition = document.querySelector('.t1002').getAttribute('data-wishlistbtn-pos');
if (productElementsList.length > 0) {
Array.prototype.forEach.call(productElementsList, function (productElement) {
var productObj = twishlist__getProductObjFromPel(productElement);
var productInWishlist = twishlist__checkIfInWishlist(productObj).flag;
var btnClass = productInWishlist ? ' t1002__addBtn_active' : '';
var addBtn = productElement.querySelector('.t1002__addBtn');
var t1002BtnsWrapper = productElement.querySelector('.t1002__btns-wrapper');
var jsStoreBtnsWrapper = productElement.querySelector('.js-catalog-buttons-wrapper, .js-store-buttons-wrapper');
var tStorePopupBtnsWrapper = productElement.querySelector('.t-catalog__prod-popup__btn-wrapper, .t-store__prod-popup__btn-wrapper');
var t1002PictureWrapper = productElement.querySelector('.t1002__picture-wrapper');
var tStoreImgWrapper = productElement.querySelector('.t-catalog__card__imgwrapper, .t-store__card__imgwrapper');
var productIsSingle =
productElement.classList.contains('js-product-single') ||
productElement.classList.contains('t-catalog__product-snippet') ||
productElement.classList.contains('t-store__product-snippet') ||
productElement.closest('.t-popup');
var btnStyles = twishlist__getButtonStyle(
t1002BtnsWrapper,
jsStoreBtnsWrapper,
tStorePopupBtnsWrapper,
wishlistBtnPosition
);
var btnSvg =
'';
var wishlistBtn =
'' +
btnSvg +
'';
if (!addBtn) {
// попап и одиночный продукт
if (productIsSingle && (t1002BtnsWrapper || tStorePopupBtnsWrapper)) {
if (t1002BtnsWrapper) t1002BtnsWrapper.insertAdjacentHTML('beforeend', wishlistBtn);
if (tStorePopupBtnsWrapper) tStorePopupBtnsWrapper.insertAdjacentHTML('beforeend', wishlistBtn);
} else if (wishlistBtnPosition === 'picture' && (t1002PictureWrapper || tStoreImgWrapper)) {
if (tStoreImgWrapper) tStoreImgWrapper.classList.add('t1002__picture-wrapper');
productElement
.querySelector('.t1002__picture-wrapper')
.insertAdjacentHTML('beforeend', wishlistBtn);
} else if (wishlistBtnPosition === 'button' && (t1002BtnsWrapper || jsStoreBtnsWrapper)) {
if (t1002BtnsWrapper) t1002BtnsWrapper.insertAdjacentHTML('beforeend', wishlistBtn);
if (jsStoreBtnsWrapper) jsStoreBtnsWrapper.insertAdjacentHTML('beforeend', wishlistBtn);
}
} else {
productInWishlist
? addBtn.classList.add('t1002__addBtn_active')
: addBtn.classList.remove('t1002__addBtn_active');
}
});
}
}
function twishlist__getButtonStyle(t1002BtnsWrapper, jsStoreBtnsWrapper, tStorePopupBtnsWrapper, wishlistBtnPosition) {
let buttonsWrapper = '';
if (t1002BtnsWrapper) {
buttonsWrapper = t1002BtnsWrapper;
} else if (jsStoreBtnsWrapper) {
buttonsWrapper = jsStoreBtnsWrapper;
} else if (tStorePopupBtnsWrapper) {
buttonsWrapper = tStorePopupBtnsWrapper;
}
const DEFAULT_STYLE = { link: '', svg: '', path: '' };
if (!buttonsWrapper) return DEFAULT_STYLE;
const buttons = buttonsWrapper.querySelectorAll('.t-btn');
if (wishlistBtnPosition !== 'button' || !buttons.length) return DEFAULT_STYLE;
const button = buttons[buttons.length - 1];
const styleAttribute = button.getAttribute('style');
let borderRadius = 0;
let linkStyle = '';
let svgStyle = '';
let pathStyle = '';
if (styleAttribute) {
const btnStyleTag = styleAttribute.split(';');
for (const style of btnStyleTag) {
if (!style.includes('border-radius')) continue;
const currentBorderRadius = parseInt(style.match(/\d+/g)?.[0], 10);
if (!isNaN(currentBorderRadius)) borderRadius = currentBorderRadius;
break;
}
} else {
const compStyle = window.getComputedStyle(button);
const parsedRadius = parseInt(compStyle.getPropertyValue('border-radius'), 10);
if (!isNaN(parsedRadius)) borderRadius = parsedRadius;
}
if (borderRadius) {
linkStyle += `border-radius:${borderRadius}px;`;
}
if (button.classList.contains('t-btn_xs') || button.classList.contains('t-btnflex_xs')) {
linkStyle += 'width: 35px;height: 35px;';
svgStyle += 'width: 60%;height: 60%;';
pathStyle += 'stroke-width: 1px;';
} else if ((button.classList.contains('t-btn_sm') || button.classList.contains('t-btnflex_sm')) && borderRadius <= 15) {
svgStyle += 'width: 55%;height: 55%;';
} else if (button.classList.contains('t-btn_md') || button.classList.contains('t-btnflex_md')) {
linkStyle += 'width: 60px;height: 60px;';
svgStyle += 'width: 50%;height: 50%;';
} else if (button.classList.contains('t-btn_lg') || button.classList.contains('t-btnflex_lg')) {
linkStyle += 'width: 60px;height: 60px;border: none;';
svgStyle += 'width: 50%;height: 50%;';
} else if (button.classList.contains('t-btn_xl') || button.classList.contains('t-btnflex_xl')) {
linkStyle += 'width: 80px;height: 80px;border: none;';
svgStyle += 'width: 50%;height: 50%;';
} else if (button.classList.contains('t-btn_xxl') || button.classList.contains('t-btnflex_xxl')) {
linkStyle += 'width: 100px;height: 100px;border: none;';
svgStyle += 'width: 50%;height: 50%;';
}
button.style.marginRight = '0px';
return {
link: linkStyle ? ' style="' + linkStyle + '"' : '',
svg: svgStyle ? ' style="' + svgStyle + '"' : '',
path: pathStyle ? ' style="' + pathStyle + '"' : '',
};
}
/**
* События виджета вишлиста и localStorage
*/
function twishlist__addEvents() {
var body = document.querySelector('body');
if (window.jQuery) {
(function ($) {
$('body').on('twishlist_addbtn', function () {
twishlist__addProductButtons();
});
})(jQuery);
} else {
body.addEventListener('twishlist_addbtn', function () {
twishlist__addProductButtons();
});
}
var wishlistIcon = document.querySelector('.t1002__wishlisticon');
if (wishlistIcon) {
wishlistIcon.addEventListener('click', function () {
twishlist__openWishlist();
});
}
body.addEventListener('click', function (e) {
if (e.target && e.target.closest('a[href="#showfavorites"]')) {
twishlist__openWishlist();
e.preventDefault();
}
});
document.querySelector('.t1002__wishlistwin-close').addEventListener('click', function () {
twishlist__closeWishlist();
});
document.querySelector('.t1002__wishlistwin').addEventListener('mousedown', function (e) {
if (e.target == this) {
var windowWidth = window.innerWidth;
var maxScrollBarWidth = 17;
var windowWithoutScrollBar = windowWidth - maxScrollBarWidth;
if (e.clientX > windowWithoutScrollBar) {
return;
}
twishlist__closeWishlist();
}
});
// синхронизирует localstorage в разных вкладках
window.addEventListener('storage', function (e) {
if (e.isTrusted) {
if (e.key === 'twishlist') {
try {
var lsJsonStr = localStorage.getItem('twishlist');
var lsJsonObj = JSON.parse(lsJsonStr);
if (typeof lsJsonObj['products'] == 'object') {
window.twishlist['products'] = lsJsonObj['products'];
twishlist__updateTotalProductsObj();
}
} catch (e) {
/* */
}
twishlist__reDrawCartIcon();
// перерисовывает товары в открытом окне вишлиста
if (document.querySelector('body').classList.contains('t1002__body_wishlistwinshowed')) {
twishlist__reDrawProducts();
}
}
}
});
}
/**
* Генерирует объект товара из html-элемента
*
* @param {HTMLElement} productElement - элемент, содержащий информацию о товаре
* @returns {object} productObj - объект товара
*/
function twishlist__getProductObjFromPel(productElement) {
var price = '0';
var name = '';
var img = '';
var sku = '';
var lid = '';
var uid = '';
var recid = '';
var inv = '';
var single = '';
var unit = '';
var portion = '';
var packLabel = '';
var packM = '';
var packX = '';
var packY = '';
var packZ = '';
var options = [];
if (productElement) {
if (name == '') {
var el_name = productElement.querySelector('.js-product-name');
name = el_name ? el_name.textContent : '';
}
if (price == '' || price == 0) {
var el_price = productElement.querySelector('.js-product-price');
if (el_price) {
if (el_price.classList.contains('js-catalog-prod-price-range-val') || el_price.classList.contains('js-store-prod-price-range-val')) {
price = el_price.getAttribute('data-product-price-def');
} else {
price = el_price.textContent;
}
}
price = twishlist__cleanPrice(price);
}
if (img == '') {
if (productElement.getAttribute('data-product-img')) {
img = productElement.getAttribute('data-product-img');
} else {
var imgDiv = productElement.querySelector('.js-product-img');
if (imgDiv) {
var original = imgDiv.getAttribute('data-original') || '';
if (original.length > 0) {
img = original;
} else if (imgDiv.tagName == 'IMG') {
img = imgDiv.getAttribute('src');
} else if (imgDiv.tagName == 'DIV') {
img = '';
var imgCss = getComputedStyle(imgDiv)['background-image'];
if (imgCss) {
img = imgCss.replace('url(', '').replace(')', '').replace(/"/gi, '');
}
}
}
}
}
if (lid == '') {
lid = productElement.getAttribute('data-product-lid') || '';
}
if (uid == '') {
uid = productElement.getAttribute('data-product-uid') || '';
}
if (recid == '') {
var recidAttr = productElement.closest('.r').getAttribute('id');
recid = recidAttr ? recidAttr.replace('rec', '') : '';
}
if (inv == '') {
inv = productElement.getAttribute('data-product-inv') || '';
}
unit = productElement.getAttribute('data-product-unit') || '';
portion = productElement.getAttribute('data-product-portion') || '';
single = productElement.getAttribute('data-product-single') || '';
// варианты товара (с разными свойствами)
var editionOptionsElements = productElement.querySelectorAll('.js-product-edition-option');
Array.prototype.forEach.call(editionOptionsElements, function (optionsElement) {
var optionName = optionsElement.querySelector('.js-product-edition-option-name').textContent;
var selectedOption = optionsElement.querySelector('option:checked');
if (selectedOption) {
var optionVariant = selectedOption.value;
var optionPrice = selectedOption.getAttribute('data-product-edition-variant-price');
optionPrice = twishlist__cleanPrice(optionPrice);
if (optionName && optionVariant) {
var optionObj = {};
if (optionName != '') {
optionName = twishlist__escapeHtml(optionName);
}
if (optionVariant != '') {
optionVariant = twishlist__escapeHtml(optionVariant);
optionVariant = optionVariant.replace(/(?:\r\n|\r|\n)/g, '');
}
if (optionName.length > 1 && optionName.charAt(optionName.length - 1) == ':') {
optionName = optionName.substring(0, optionName.length - 1);
}
optionObj['option'] = optionName;
optionObj['variant'] = optionVariant;
optionObj['price'] = optionPrice;
options.push(optionObj);
}
}
});
// дополнительные опции
var optionsElements = productElement.querySelectorAll('.js-product-option');
Array.prototype.forEach.call(optionsElements, function (optionsElement) {
var optionName = optionsElement.querySelector('.js-product-option-name').textContent;
var selectedOption = optionsElement.querySelector('option:checked');
if (selectedOption) {
var optionVariant = selectedOption.value;
var optionPrice = selectedOption.getAttribute('data-product-variant-price');
optionPrice = twishlist__cleanPrice(optionPrice);
if (optionName && optionVariant) {
var optionObj = {};
if (optionName != '') {
optionName = twishlist__escapeHtml(optionName);
}
if (optionVariant != '') {
optionVariant = twishlist__escapeHtml(optionVariant);
optionVariant = optionVariant.replace(/(?:\r\n|\r|\n)/g, '');
}
if (optionName.length > 1 && optionName.charAt(optionName.length - 1) == ':') {
optionName = optionName.substring(0, optionName.length - 1);
}
optionObj['option'] = optionName;
optionObj['variant'] = optionVariant;
optionObj['price'] = optionPrice;
options.push(optionObj);
}
}
});
if (sku == '') {
sku = productElement.querySelector('.js-product-sku')
? productElement.querySelector('.js-product-sku').textContent.trim()
: '';
}
if (packLabel == '') {
packLabel = productElement.getAttribute('data-product-pack-label') || '';
}
if (packM == '') {
packM = productElement.getAttribute('data-product-pack-m') || '';
}
if (packX == '') {
packX = productElement.getAttribute('data-product-pack-x') || '';
}
if (packY == '') {
packY = productElement.getAttribute('data-product-pack-y') || '';
}
if (packZ == '') {
packZ = productElement.getAttribute('data-product-pack-z') || '';
}
}
var productUrl = productElement.getAttribute('data-product-url');
var settedLinkInToProduct = productElement.querySelector(
'.js-product-link:not([href="#prodpopup"]):not([href="#addtofavorites"]):not([href="#order"])'
);
var settedLinkInToProductHref;
if (settedLinkInToProduct) {
settedLinkInToProductHref = settedLinkInToProduct.getAttribute('href');
}
if (!productUrl && settedLinkInToProductHref) {
productUrl = settedLinkInToProductHref;
} else if (!productUrl && recid && lid) {
productUrl = window.location.origin + window.location.pathname + '#!/tproduct/' + recid + '-' + lid;
} else if (!productUrl) {
productUrl = window.location.origin + window.location.pathname + '#rec' + recid;
}
if (name == '' && (price == '' || price == 0)) {
return null;
}
if (name == '') name = 'NoName';
if (price == '') price = 0;
if (name != '') name = twishlist__escapeHtml(name);
if (img != '') img = twishlist__escapeHtmlImg(img);
var productObj = {};
productObj['name'] = name;
productObj['price'] = price;
productObj['img'] = img;
productObj['recid'] = recid;
productObj['lid'] = lid;
productObj['pack_label'] = packLabel;
productObj['pack_m'] = packM;
productObj['pack_x'] = packX;
productObj['pack_y'] = packY;
productObj['pack_z'] = packZ;
productObj['url'] = productUrl;
if (options.length > 0) {
productObj['options'] = options;
}
if (sku) {
sku = twishlist__escapeHtml(sku);
productObj['sku'] = sku;
}
if (uid) productObj['uid'] = uid;
if (lid) productObj['lid'] = lid;
if (inv > 0) productObj['inv'] = parseInt(inv, 10);
if (unit) {
productObj['unit'] = unit;
}
if (portion) {
productObj['portion'] = portion;
}
if (single) {
productObj['single'] = single;
}
return productObj;
}
/**
* События кнопки добавления в избранное
*/
function twishlist__addEvent__links() {
var recs = document.querySelectorAll('.r');
Array.prototype.forEach.call(recs, function (rec) {
rec.addEventListener('click', function (e) {
var wishlistBtn = e.target.closest('[href^="#addtofavorites"]')
? e.target.closest('[href^="#addtofavorites"]')
: '';
if (!wishlistBtn) return;
e.preventDefault();
e.stopPropagation();
var price = '0';
var name = '';
var img = '';
var recid = '';
var wishlistBtnLink = wishlistBtn.getAttribute('href');
var productObj = {
name: '',
price: '0',
img: '',
recid: '',
};
var imgLink;
// получает данные товара из ссылки
if (wishlistBtnLink.substring(0, 16) == '#addtofavorites:') {
var productData = wishlistBtnLink.substring(16);
if (productData) {
// если есть специальный параметр для картинки
if (productData.indexOf(':::') > 0) {
var imgLinkPos = productData.indexOf(':::');
// проверяет, что ::: не в названии товара
if (productData.indexOf('=') > 0 && productData.indexOf('=') < productData.indexOf(':::')) {
imgLink = productData.substring(imgLinkPos + 3);
productData = productData.substring(0, imgLinkPos);
}
}
if (productData.indexOf('=') > 0) {
var productDataParams = productData.split('=');
if (productDataParams[0]) name = productDataParams[0];
if (productDataParams[1]) price = productDataParams[1];
price = twishlist__cleanPrice(price);
} else {
name = productData;
}
// обрабатывает параметры
if (imgLink) {
if (imgLink.indexOf('=') > 0) {
var imgLinkArr = imgLink.split('=');
if (imgLinkArr[0] && imgLinkArr[1]) {
if (imgLinkArr[0] == 'image' && imgLinkArr[1].indexOf('.tildacdn.') > 0) {
img = imgLinkArr[1];
}
}
}
}
if (recid == '') {
recid = wishlistBtn.closest('.r').getAttribute('id')
? wishlistBtn.closest('.r').getAttribute('id').replace('rec', '')
: '';
}
}
productObj['name'] = name;
productObj['price'] = price;
productObj['recid'] = recid;
if (recid) productObj['url'] = window.location.origin + window.location.pathname + '#rec' + recid;
productObj['img'] = img;
}
// получает данные товара из html-элемента
var productElement = wishlistBtn.closest('.js-product');
if (productElement) {
wishlistBtn.classList.add('t1002__addBtn_neworder');
wishlistBtn.classList.add('t1002__addBtn_active');
setTimeout(function () {
wishlistBtn.classList.remove('t1002__addBtn_neworder');
}, 500);
productObj = twishlist__getProductObjFromPel(productElement);
}
// если товар уже в вишлисте - удаляет его
var objFromWishlist = twishlist__checkIfInWishlist(productObj);
if (objFromWishlist.flag) {
var id = objFromWishlist.id;
window.twishlist.products[id].deleted = 'yes';
var wishlistIconCounter = document.querySelector('.js-wishlisticon-counter');
twishlist__updateTotalProductsObj();
if (wishlistIconCounter) {
wishlistIconCounter.innerHTML = window.twishlist.total;
}
// меню с поиском, корзиной и вишлистом
var widgetsWishlistCounters = document.querySelectorAll(
'[data-menu-widgeticon-wishlist="yes"] .js-wishlisticon-counter'
);
Array.prototype.forEach.call(widgetsWishlistCounters, function (widgetsWishlistCounter) {
widgetsWishlistCounter.innerHTML = window.twishlist.total;
});
twishlist__saveLocalObj();
wishlistBtn.classList.remove('t1002__addBtn_active');
window.twishlist.products[id] = {};
if (twishlist__isEmptyObject(window.twishlist.products[id])) {
window.twishlist.products.splice(id, 1);
twishlist__reDrawProducts();
}
twishlist__reDrawCartIcon();
} else {
twishlist__addProduct(productObj);
var bubbleTxt = productObj.name + ' ' + twishlist_dict('youAdd');
twishlist__showBubble(bubbleTxt);
}
twishlist__addProductButtons();
});
});
}
/**
* Проверяет, добавлен ли товар в вишлист
*
* @param {object} productObj - объект товара
* @returns {object} objInWishlist - находится ли товар в вишлисте, id этого товара в вишлисте
*/
function twishlist__checkIfInWishlist(productObj) {
var products = window.twishlist['products'];
var isInWishlist = false;
var objIndex = '';
if (products.length > 0) {
Array.prototype.forEach.call(products, function (product, index) {
var isEqualOptions = 'y';
var isEqualSKU = '';
if (!productObj) {
return;
}
if (
(product['uid'] !== undefined && product['uid'] == productObj['uid']) ||
(product['uid'] == undefined &&
product['name'] &&
product['name'].trim() == productObj['name'].trim() &&
product['price'] == productObj['price'] &&
((product['lid'] && product['lid'] == productObj['lid']) || !product['lid']))
) {
if (
product['options'] == undefined &&
productObj['options'] == undefined &&
product['sku'] == undefined &&
productObj['sku'] == undefined
) {
objIndex = index;
isInWishlist = true;
return;
}
if (
product['options'] == undefined &&
productObj['options'] == undefined &&
product['sku'] != undefined &&
productObj['sku'] != undefined &&
product['sku'] == productObj['sku']
) {
objIndex = index;
isInWishlist = true;
return;
}
if (typeof product['options'] == 'object' && typeof productObj['options'] == 'object') {
Array.prototype.forEach.call(product['options'], function (option, index) {
if (typeof option == 'object' && typeof productObj['options'][index] == 'object') {
if (
option['option'] !== productObj['options'][index]['option'] ||
option['variant'] !== productObj['options'][index]['variant'] ||
option['price'] !== productObj['options'][index]['price']
) {
isEqualOptions = false;
}
} else if (option == undefined || productObj['options'][index] == undefined) {
isEqualOptions = false;
}
});
if (product['sku'] === productObj['sku']) {
isEqualSKU = 'y';
}
if (isEqualOptions === 'y' && isEqualSKU === 'y') {
objIndex = index;
isInWishlist = true;
}
}
}
});
}
var objInWishlist = {
id: objIndex,
flag: isInWishlist,
};
return objInWishlist;
}
/**
* Добавляет товар в вишлист
*
* @param {object} productObj - объект товара
*/
function twishlist__addProduct(productObj) {
var timestamp = Math.floor(Date.now() / 1000);
var twishlistIcon = document.querySelector('.t1002__wishlisticon');
var menuWishlistIcons = document.querySelectorAll('.t-menuwidgeticons__link_wishlist');
twishlist__syncProductsObject__LStoObj();
var isObjInWishlist = twishlist__checkIfInWishlist(productObj).flag;
if (!isObjInWishlist) {
if (productObj['quantity'] === undefined) {
productObj['quantity'] = 1;
productObj['amount'] = productObj['price'];
} else {
productObj['amount'] = twishlist__roundPrice(productObj['price'] * productObj['quantity']);
}
productObj['ts'] = timestamp;
window.twishlist['products'].push(productObj);
}
twishlist__updateTotalProductsObj();
twishlist__reDrawCartIcon();
twishlist__saveLocalObj();
if (document.querySelector('.t1002').getAttribute('data-openwishlist-onorder') == 'yes') {
setTimeout(function () {
twishlist__openWishlist();
}, 10);
} else if (twishlistIcon || menuWishlistIcons.length) {
if (twishlistIcon) {
twishlistIcon.classList.add('t1002__wishlisticon_neworder');
setTimeout(function () {
twishlistIcon.classList.remove('t1002__wishlisticon_neworder');
}, 500);
}
if (menuWishlistIcons.length) {
Array.prototype.forEach.call(menuWishlistIcons, function (menuWishlistIcon) {
menuWishlistIcon.classList.add('t1002__wishlisticon_neworder');
setTimeout(function () {
menuWishlistIcon.classList.remove('t1002__wishlisticon_neworder');
}, 500);
});
}
}
}
/**
* Обновляет количество товаров в избранном
*/
function twishlist__updateTotalProductsObj() {
var products = window.twishlist['products'];
if (products.length > 0) {
// пропускает пустые или удаленные товары
var total = 0;
var prodamount = 0;
Array.prototype.forEach.call(products, function (product) {
if (!twishlist__isEmptyObject(product) && product.deleted !== 'yes') {
if (product.single === 'y') {
total = total + 1;
} else {
total = total + product['quantity'] * 1;
}
prodamount = prodamount * 1 + product['amount'] * 1;
}
});
prodamount = twishlist__roundPrice(prodamount);
window.twishlist['total'] = total;
window.twishlist['prodamount'] = prodamount;
var amount = prodamount;
if (amount > 0) {
amount = twishlist__roundPrice(amount);
}
window.twishlist['amount'] = amount;
} else {
window.twishlist['total'] = 0;
window.twishlist['prodamount'] = 0;
window.twishlist['amount'] = 0;
}
}
function twishlist__reDrawCartIcon() {
var twishlist = window.twishlist;
var wishlistIcon = document.querySelector('.t1002__wishlisticon');
var wishlistIconCounters;
if (wishlistIcon) {
wishlistIconCounters = wishlistIcon.querySelectorAll('.js-wishlisticon-counter');
if (twishlist['total'] == 1) {
wishlistIcon.style.opacity = 0;
wishlistIcon.style.transition = 'opacity .3s';
wishlistIcon.style.opacity = 1;
}
}
var widgetsMenuWishlistCounters = document.querySelectorAll(
'[data-menu-widgeticon-wishlist="yes"] .js-wishlisticon-counter'
);
if (twishlist.products !== undefined && twishlist.products.length > 0 && twishlist['total'] > 0) {
if (wishlistIcon) {
wishlistIcon.classList.add('t1002__wishlisticon_showed');
if (wishlistIconCounters.length) {
Array.prototype.forEach.call(wishlistIconCounters, function (wishlistIconCounter) {
wishlistIconCounter.innerHTML = twishlist['total'];
});
}
}
Array.prototype.forEach.call(widgetsMenuWishlistCounters, function (widgetsMenuWishlistCounter) {
widgetsMenuWishlistCounter.innerHTML = twishlist['total'];
});
} else {
if (wishlistIcon) {
wishlistIcon.classList.remove('t1002__wishlisticon_showed');
Array.prototype.forEach.call(wishlistIconCounters, function (wishlistIconCounter) {
wishlistIconCounter.innerHTML = '';
});
}
Array.prototype.forEach.call(widgetsMenuWishlistCounters, function (widgetsMenuWishlistCounter) {
widgetsMenuWishlistCounter.innerHTML = '';
});
}
t_onFuncLoad('t_posWidget__updateStyleWidget', function () {
t_posWidget__updateStyleWidget();
});
if (window.lazy === 'y' || document.querySelector('#allrecords').getAttribute('data-tilda-lazy') === 'yes') {
try {
twishlist__onFuncLoad('t_lazyload_update', function () {
t_lazyload_update();
});
} catch (e) {
console.error('js lazyload not loaded');
}
}
}
function twishlist__openWishlist() {
var wishlistIcon = document.querySelector('.t1002__wishlisticon');
var wishlistWindow = document.querySelector('.t1002__wishlistwin');
if (wishlistIcon) {
wishlistIcon.classList.remove('t1002__wishlisticon_showed');
}
t_triggerEvent(document.body, 'popupShowed');
document.querySelector('body').classList.add('t1002__body_wishlistwinshowed');
twishlist__syncProductsObject__LStoObj();
wishlistWindow.style.display = '';
wishlistWindow.style.opacity = 0;
wishlistWindow.style.transition = 'opacity .3s';
wishlistWindow.classList.add('t1002__wishlistwin_showed');
// фикс для анимации
setTimeout(function () {
wishlistWindow.style.opacity = 1;
var contentEl = document.querySelector('.t1002__wishlistwin-content');
contentEl.classList.add('t1002__wishlistwin-content_showed');
}, 0);
twishlist__reDrawProducts();
document.addEventListener('keyup', twishlist__keyUpFunc);
if (window.lazy === 'y' || document.querySelector('#allrecords').getAttribute('data-tilda-lazy') === 'yes') {
try {
twishlist__onFuncLoad('t_lazyload_update', function () {
t_lazyload_update();
});
} catch (e) {
console.error('js lazyload not loaded');
}
}
}
/**
* Перерисовывает товары в окне вишлиста
*/
function twishlist__reDrawProducts() {
var wishlistWindowProducts = document.querySelector('.t1002__wishlistwin-products');
var actualProductsObj = [];
// удаляет пустые или удаленные товары
if (window.twishlist['products'] !== undefined) {
var oldCountProducts = window.twishlist['products'].length;
Array.prototype.forEach.call(window.twishlist['products'], function (product) {
if (!twishlist__isEmptyObject(product) && product.deleted !== 'yes' && product.quantity > 0) {
actualProductsObj.push(product);
}
});
window.twishlist['products'] = actualProductsObj;
var actualCountProducts = window.twishlist['products'].length;
if (actualCountProducts !== oldCountProducts) {
twishlist__saveLocalObj();
}
}
var hasImg = '';
if (actualProductsObj.length > 0) {
var str = '';
Array.prototype.forEach.call(actualProductsObj, function (product, index) {
if (product['img'] != '') {
hasImg = 'yes';
}
str += '