Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function cqGetDate() {
- var today = new Date(),
- isoDate = today.toISOString();
- return isoDate.split('.')[0];
- };
- function cqGetTimelapse() {
- var seconds = Math.floor((Date.now()-parseInt(localStorage['orderStartedTime']))/1000),
- timeLapse = new Date(null);
- timeLapse.setSeconds(seconds);
- var lapseResult = timeLapse.toISOString().substr(11, 8);
- return lapseResult;
- };
- function getClosest(el, s) {
- var r = undefined;
- while (el) {
- if (el.matches(s)) {
- r = el;
- break;
- } else if (el.tagName.toLowerCase()=='body') {
- break;
- };
- el = el.parentElement;
- };
- return r;
- };
- var isProdPage = document.querySelectorAll('.ty-product-block.ty-product-detail').length>0;
- if (isProdPage) {
- var name, img, amount, url = location.href;
- var checkProps = setInterval(function() {
- if ((document.querySelectorAll('.ty-product-block-title bdi').length>0)&&
- (document.querySelectorAll('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').length>0)&&
- (document.querySelectorAll('.ty-product-block img.ty-pict').length>0)) {
- clearInterval(checkProps);
- name = document.querySelector('.ty-product-block-title bdi').textContent.trim();
- img = document.querySelector('.ty-product-block img.ty-pict').getAttribute('src');
- amount = parseInt(document.querySelector('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').textContent.split(',')[0].split('.')[0].replace(/\D/g, ''));
- carrotquest.track('$product_viewed', {
- '$name': name,
- '$img': img,
- '$amount': amount,
- '$url': url
- });
- carrotquest.identify([{op: 'union', key: '$viewed_products', value: name}]);
- };
- }, 500);
- document.addEventListener('click', function(e) {
- if (e.target.matches('.ty-product-block button[type="submit"]')) {
- amount = parseInt(document.querySelector('.ty-product-block .ty-price bdi .ty-price-num:nth-of-type(1)').textContent.split(',')[0].split('.')[0].replace(/\D/g, ''));
- var qty = parseInt(document.querySelector('.ty-product-block .ty-value-changer__input.cm-amount, .ty-product-block .ty-qty select[name*="[amount]"]').value),
- ttl = amount * qty,
- opt = document.querySelectorAll('.ty-product-options__box input:checked').length!=0?
- document.querySelector('.ty-product-options__box input:checked').parentElement.textContent.trim():' ';
- carrotquest.track('$cart_added', {
- '$name': name,
- '$img': img,
- '$amount': amount,
- '$url': url,
- 'Вариация': opt
- });
- carrotquest.identify([
- {op: 'union', key: '$cart_items', value: name},
- {op: 'add', key: '$cart_amount', value: ttl}
- ]);
- };
- });
- } else if (document.querySelectorAll('.ty-breadcrumbs').length>0 && document.querySelectorAll('.ty-product-list').length!=0) {
- var crumbs = Array.from(document.querySelectorAll('.ty-breadcrumbs__a, .ty-breadcrumbs__current bdi')).map(function(el) {
- return el.textContent.trim()
- });
- switch (crumbs.length) {
- case 4:
- carrotquest.track('Посмотрел подкатегорию', {
- 'Название подкатегории': crumbs[3]
- });
- carrotquest.identify([
- {op: 'union', key: 'Просмотренные подкатегории', value: crumbs[3]},
- {op: 'union', key: 'Просмотренные категории', value: crumbs[2]},
- {op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}
- ]);
- break;
- case 3:
- carrotquest.track('Посмотрел категорию', {
- 'Название категории': crumbs[2]
- });
- carrotquest.identify([
- {op: 'union', key: 'Просмотренные категории', value: crumbs[2]},
- {op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}
- ]);
- break;
- case 2:
- carrotquest.track('Посмотрел раздел', {
- 'Название раздела': crumbs[1]
- });
- carrotquest.identify([{op: 'union', key: 'Просмотренные разделы', value: crumbs[1]}]);
- break;
- default: break;
- };
- document.addEventListener('click', function(e) {
- if (e.target.matches('.ty-product-list form[name*="product_form_"] button.ty-btn__add-to-cart')) {
- var item = getClosest(e.target, 'form[name*="product_form_"]'),
- name = item.querySelector('.product-title').textContent.trim(),
- url = item.querySelector('.product-title').getAttribute('href'),
- img = item.querySelector('img.ty-pict').getAttribute('src'),
- price = parseInt(item.querySelector('bdi > .ty-price-num').textContent.split('.')[0].replace(/\D/g, '')),
- qty = parseInt(item.querySelector('.ty-qty [name*="[amount]"]').value),
- ttl = price * qty;
- carrotquest.track('$cart_added', {
- '$name': name,
- '$img': img,
- '$amount': price,
- '$url': url,
- 'Вариация': ' '
- });
- carrotquest.identify([
- {op: 'union', key: '$cart_items', value: name},
- {op: 'add', key: '$cart_amount', value: ttl}
- ]);
- };
- });
- };
- document.addEventListener('click', function(e) {
- if (e.target.matches('button[name="dispatch[auth.login]"]')) {
- carrotquest.track('Клик "Войти"');
- } else if (e.target.matches('form[name="coupon_code_form"] button[type="submit"]')) {
- var promo = getClosest(e.target, 'form').querySelector('input#coupon_field').value;
- carrotquest.track('Ввел промокод', {
- 'Промокод': promo
- });
- };;
- });
- if (location.pathname=='/cart/') {
- function get_items() {
- var items = document.querySelectorAll('.ty-cart-content__product-elem a.ty-cart-content__product-title').length,
- cartAmount = items==0?0:parseInt(document.querySelector('#sec_cart_total').textContent.split('.')[0].replace(/\D/g, ''));
- carrotquest.identify([
- {
- op: items == 0 ? 'delete' : 'update_or_create',
- key: '$cart_items',
- value: items == 0 ? 0 : Array.from(document.querySelectorAll('.ty-cart-content__product-elem a.ty-cart-content__product-title')).map(function(elem) {
- return elem.textContent.trim();
- })
- },
- { op: items == 0 ? 'delete' : 'update_or_create', key: '$cart_amount', value: cartAmount }
- ])
- localStorage['lastAmount'] = cartAmount;
- };
- setTimeout(get_items, 1000);
- carrotquest.track('$cart_viewed');
- document.addEventListener('click', function(e) {
- if (e.target.matches('a.ty-cart-content__product-delete, a.ty-cart-content__product-delete *')) {
- carrotquest.track('Удалил товар из корзины', {
- '$name': getClosest(e.target, '.ty-cart-content__product-elem').querySelector('a.ty-cart-content__product-title').textContent.trim()
- });
- setTimeout(get_items, 1000);
- } else if (e.target.matches('a[href="https://surmarket.ru/checkout/"]')) {
- localStorage['lastAmount'] = parseInt(document.querySelector('#sec_cart_total').textContent.split('.')[0].replace(/\D/g, ''));
- };
- });
- };
- if (location.pathname=='/checkout/') {
- carrotquest.track('$order_started');
- localStorage['orderStarted'] = true;
- localStorage['orderStartedTime'] = Date.now();
- setTimeout(function() {
- localStorage['lastAmount'] = document.querySelector('.ty-checkout-summary__item[data-ct-checkout-summary="items"]>span>bdi>span').textContent.split('.')[0].replace(/\D/g, '');
- carrotquest.identify([{op: 'update_or_create', key: '$cart_amount', value: localStorage['lastAmount']}]);
- }, 2000);
- document.addEventListener('mousedown', function(e) {
- if (e.target.matches('a.ty-order-products__item-delete, a.ty-order-products__item-delete *')) {
- var dName = getClosest(e.target, '.ty-order-products__item').querySelector('bdi').textContent.trim();
- carrotquest.track('Удалил товар из корзины', {
- '$name': dName
- });
- carrotquest.identify([{op: 'exclude', key: '$cart_items', value: dName}]);
- } else if (e.target.matches('button#litecheckout_place_order, button#litecheckout_place_order *')) {
- var name = document.querySelector('input#litecheckout_fullname').value,
- phone = document.querySelector('input#litecheckout_phone').value,
- email = document.querySelector('input#litecheckout_email').value;
- if (name!='') {
- carrotquest.identify([{op: 'update_or_create', key: '$name', value: name}]);
- };
- if (phone!='') {
- carrotquest.identify([{op: 'update_or_create', key: '$phone', value: phone}]);
- };
- if (email!='') {
- carrotquest.identify([{op: 'update_or_create', key: '$email', value: email}]);
- };
- };
- });
- };
- if (location.search.indexOf('?dispatch=checkout.complete&order_id=')>-1 && localStorage['orderStarted']=='true') {
- var orderId = location.search.replace(/\D/g, '');
- carrotquest.track('$order_completed', {
- '$order_amount': localStorage['lastAmount'],
- '$order_id_human': orderId
- });
- carrotquest.identify([
- { op: "delete", key: "$cart_items", value: 0 },
- { op: "delete", key: "$viewed_products", value: 0 },
- { op: "delete", key: "$cart_amount", value: 0 },
- { op: "add", key: "$revenue", value: parseInt(localStorage['lastAmount']) },
- { op: "add", key: "$orders_count", value: 1 },
- { op: "update_or_create", key: "$last_payment", value: localStorage['lastAmount'] },
- { op: "update_or_create", key: "Номер последнего заказа", value: orderId },
- { op: "update_or_create", key: "Дата последнего заказа", value: cqGetDate() },
- { op: 'update_or_create', key: 'Продолжительность оформления заказа', value: cqGetTimelapse() }
- ]);
- localStorage['orderStarted'] = false;
- localStorage.removeItem('lastAmount');
- localStorage.removeItem('orderStartedTime');
- };
- switch (location.pathname) {
- case '/profiles-add/':
- carrotquest.track('Переход "Регистрация"');
- break;
- case '/profiles-update/':
- carrotquest.track('Переход "Учетная запись"');
- break;
- case '/orders/':
- carrotquest.track('Переход "Мои заказы"');
- break;
- case '/reward-points/':
- carrotquest.track('Переход "Мои бонусные баллы"');
- break;
- case '/wishlist/':
- carrotquest.track('Переход "Список желаний"');
- break;
- case '/compare/':
- carrotquest.track('Переход "Список сравнения"');
- break;
- case '/dostavka/':
- carrotquest.track('Переход "Доставка и оплата"');
- break;
- case '/faq/about-shipping/':
- carrotquest.track('Переход "Пример расчета стоимости доставки"');
- break;
- case '/reclamation/':
- carrotquest.track('Переход "Обмен или возврат"');
- break;
- case '/contact/':
- carrotquest.track('Переход "Контакты и реквизиты"');
- break;
- case '/faq/cdek':
- carrotquest.track('Переход "Склады СДЭК"');
- break;
- case '/feedback/':
- carrotquest.track('Переход "Обратная связь"');
- break;
- case '/contact':
- carrotquest.track('Переход "Наши реквизиты"');
- break;
- case '/cooperation/':
- carrotquest.track('Переход "Работа с юридическими лицами"');
- break;
- case '/opt/':
- carrotquest.track('Переход "Оптовые предложения (от 10000 руб.)"');
- break;
- case '/about/':
- carrotquest.track('Переход "О нас"');
- break;
- case '/sales-office/':
- carrotquest.track('Переход "Офис продаж"');
- break;
- case '/reward':
- carrotquest.track('Переход "Бонусная программа"');
- break;
- case '/feedback-ru/':
- carrotquest.track('Переход "Отзывы покупателей"');
- break;
- case '/info/':
- carrotquest.track('Переход "Информация для покупателей"');
- break;
- case '/sitemap/':
- carrotquest.track('Переход "Карта сайта"');
- break;
- default: break;
- };
- document.addEventListener('submit', function(e) {
- if (e.target.matches('form[name="search_form"]')) {
- carrotquest.track('Поиск', {
- 'Значение поиска': e.target.querySelector('input#ecl_live_search').value
- });
- };
- });
- function dataCollection() {
- if (typeof $ !='undefined') {
- clearInterval(checkJQuery);
- $(document).on('change', 'input[name="user_data[phone]"]', function() {
- carrotquest.identify([{op: 'update_or_create', key: '$phone', value: $(this).val()}]);
- });
- $(document).on('change', 'input[name="user_data[email]"], input[name="user_login"]', function() {
- carrotquest.identify([{op: 'update_or_create', key: '$email', value: $(this).val()}]);
- });
- $(document).on('change', 'input[name="user_data[fullname]"]', function() {
- carrotquest.identify([{op: 'update_or_create', key: '$name', value: $(this).val()}]);
- });
- };
- };
- var checkJQuery = setInterval(dataCollection, 500);
- setTimeout(function() {
- clearInterval(checkJQuery);
- }, 5000);
- (function() {
- init()
- function init() {
- setTimeout(addMouseout, 5000);
- }
- function addMouseout() {
- document.addEventListener('mouseout', mouseout);
- }
- function mouseout(e) {
- if (Math.round(e.x) >= 0 && Math.round(e.y) <= 0) {
- carrotquest.track('Попытка ухода с сайта');
- deleteEvent();
- setTimeout(addMouseout, 10000);
- }
- }
- function deleteEvent() {
- document.removeEventListener('mouseout', mouseout);
- }
- }());
- function TrackUtm(){
- var utm_source = window.location.href.match(/utm_source=([^&]+)/);
- var utm_medium = window.location.href.match(/utm_medium=([^&]+)/);
- var utm_campaign = window.location.href.match(/utm_campaign=([^&]+)/);
- var utm_term = window.location.href.match(/utm_term=([^&]+)/);
- var utm_content = window.location.href.match(/utm_content=([^&]+)/);
- if (utm_content != undefined) {
- carrotquest.identify([
- {op: 'update_or_create', key: 'Последняя метка UTM Content', value: utm_content[1]},
- {op: 'union', key: 'Все метки UTM Content', value: utm_content[1]}
- ]);
- }
- if (utm_source != undefined) {
- carrotquest.identify([
- {op: 'update_or_create', key: 'Последняя метка UTM Source', value: utm_source[1]},
- {op: 'union', key: 'Все метки UTM Source', value: utm_source[1]}
- ]);
- }
- if (utm_medium != undefined) {
- carrotquest.identify([
- {op: 'update_or_create', key: 'Последняя метка UTM Medium', value: utm_medium[1]},
- {op: 'union', key: 'Все метки UTM Medium', value: utm_medium[1]}
- ]);
- }
- if (utm_campaign != undefined) {
- carrotquest.identify([
- {op: 'update_or_create', key: 'Последняя метка UTM Campaign', value: utm_campaign[1]},
- {op: 'union', key: 'Все метки UTM Campaign', value: utm_campaign[1]}
- ]);
- }
- if (utm_term != undefined) {
- carrotquest.identify([
- {op: 'update_or_create', key: 'Последняя метка UTM Term', value: utm_term[1]},
- {op: 'union', key: 'Все метки UTM Term', value: utm_term[1]}
- ]);
- }
- };
- TrackUtm();
- carrotquest.addCallback('conversation_opened', function(data) {
- if (data.message == '198331') {
- ga('send', 'event', 'CarrotQuest', 'PopupSeen-Rus');
- yaCounter24705737.reachGoal('PopupSeen-Rus');
- } else if (data.message == '221627768880762521') {
- ga('send', 'event', 'CarrotQuest', 'PopupSeen-SPb');
- yaCounter24705737.reachGoal('PopupSeen-SPb');
- };
- });
- carrotquest.addCallback('user_replied', function(data) {
- if (data.message == '198331') {
- ga('send', 'event', 'CarrotQuest', 'LeftEmailInPopup-Rus');
- yaCounter24705737.reachGoal('LeftEmailInPopup-Rus');
- } else if (data.message == '221627768880762521') {
- ga('send', 'event', 'CarrotQuest', 'LeftEmailInPopup-SPb');
- yaCounter24705737.reachGoal('LeftEmailInPopup-SPb');
- };
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement