(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && arguments[0] !== undefined ? arguments[0] : true; // Не проверяем очередь _mgq, если предыдущий вызов _mgwqp не обработал все записи в очереди if (firstCall && typeof _mgwqp.started == 'boolean' && _mgwqp.started) { return; } _mgwqp.started = true; // Выполняем проверку очереди _mgq for (var i = 0; i < _mgq.length; i++) { var mgRec = _mgq[i]; var mglibName = '_mgLib' + mgRec[1].lib; if (typeof window[mglibName] == 'function') { _mgq.splice(i--, 1); if (typeof window[mglibName][mgRec[0]] == 'function') { setTimeout(function (libName, _mgRec) { window[libName][_mgRec[0]](_mgRec[1]); }(mglibName, mgRec), 1); } else { console.warn('MgError: function ' + _mgRec[0] + ' not found in library ' + mglibName); } } } // Если в очереди остались записи, назначаем повторный вызов _mgwqp if (_mgq.length) { setTimeout(function () { _mgwqp(false); }, 1000); } else { _mgwqp.started = false; } }; } },{"./main":1}],3:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _debug = require('./modules/debug'); Object.keys(_debug).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _debug[key]; } }); }); var _styles = require('./modules/styles'); Object.keys(_styles).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _styles[key]; } }); }); var _widgetCapping = require('./modules/widgetCapping'); Object.keys(_widgetCapping).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _widgetCapping[key]; } }); }); var _teaserCapping = require('./modules/teaserCapping'); Object.keys(_teaserCapping).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _teaserCapping[key]; } }); }); var _videoAds = require('./modules/videoAds'); Object.keys(_videoAds).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _videoAds[key]; } }); }); var _videoInread = require('./modules/videoInread'); Object.keys(_videoInread).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _videoInread[key]; } }); }); var _vrw = require('./modules/vrw'); Object.keys(_vrw).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _vrw[key]; } }); }); var _videoInline = require('./modules/videoInline'); Object.keys(_videoInline).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _videoInline[key]; } }); }); var _loader = require('./modules/loader'); Object.keys(_loader).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _loader[key]; } }); }); var _helpers = require('./modules/helpers'); Object.keys(_helpers).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _helpers[key]; } }); }); },{"./modules/debug":4,"./modules/helpers":5,"./modules/loader":6,"./modules/styles":7,"./modules/teaserCapping":8,"./modules/videoAds":9,"./modules/videoInline":11,"./modules/videoInread":12,"./modules/vrw":13,"./modules/widgetCapping":14}],4:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @module debug * Поддерживает следующие спобосы включения режима откладки: * 1. Через URL: ?mgwdebug=true или ?mgwdebug_123=true&mgwdebug_456=true * второй вариант включает отладку только в инфромерах с cid=123 и cid=456 * 2. Через конфигурацию информера (поле config в таблице g_blocks) json: {"debug":true} * 3. Через DOM атрибут в блоке кода информера на странице:
*/ /** * Класс Debug */ var Debug = function () { function Debug(widget) { _classCallCheck(this, Debug); var queryArray = Debug.queryString(); if (queryArray.mgwdebug) { this.debugFlag = true; if (widget) { widget.sensorUrl = widget.libConfig.videoSensorUrl; widget.debugMode = queryArray.mgwdebug; } } } /** * Добавляет к объекту библиотеки информера метод debug и устанавливает флаг debugFlag, если включена отладка * @param {_mgLib4} widget - библиотека информеров */ _createClass(Debug, [{ key: 'debug', /** * Выводит отладочную информацию на консоль при установленном debugFlag * @memberof _mgLib4 * @param {*} message */ value: function debug(message) { if (this.debugFlag) { if ((typeof message === 'undefined' ? 'undefined' : _typeof(message)) !== 'object') { message = new Date().toISOString().replace('Z', 'MG') + ' ' + message; } if (this.debugMode === 'remote') { this.remoteMessage(message); } else { console.debug(message); } } } /** * Отправляет сообщение на удалённый узел отладки * @param {string} message */ }, { key: 'remoteMessage', value: function remoteMessage(message) { var img0gif = new Image(); if (this.sensorUrl) { img0gif.src = this.sensorUrl + '?e=mgwdebug' + '&o=' + encodeURIComponent(message) + '&c=' + Math.floor(Math.random() * 65535); } } }], [{ key: 'init', value: function init(widget) { if (!widget.debug) { var debugObject = new Debug(widget); widget.debug = debugObject.debug; widget.remoteMessage = debugObject.remoteMessage; } var queryArray = this.queryString(); var confDebug = widget.mgRec.config.debug; if (queryArray.mgwdebug || queryArray['mgwdebug_' + widget.mgRec.cid] || confDebug && typeof confDebug !== 'string' || typeof confDebug === 'string' && parseInt(confDebug) || widget.block.getAttribute('data-mgwdebug')) { widget.debugFlag = true; } } /** * Возвращает массив аргументов из URL * @returns {Object} */ }, { key: 'queryString', value: function queryString() { var queryArray = {}; var query = window.location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (typeof queryArray[pair[0]] === 'undefined') { queryArray[pair[0]] = decodeURIComponent(pair[1]); } else if (typeof queryArray[pair[0]] === 'string') { var arr = void 0; arr = [queryArray[pair[0]], decodeURIComponent(pair[1])]; queryArray[pair[0]] = arr; } else { queryArray[pair[0]].push(decodeURIComponent(pair[1])); } } return queryArray; } }]); return Debug; }(); exports.Debug = Debug; },{}],5:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module Helpers */ var Helpers = function () { function Helpers() { _classCallCheck(this, Helpers); } _createClass(Helpers, null, [{ key: 'isScrolledIntoView', /** * Проверка на попадание элемента в область видимости * @param {HTMLElement} elem - Проверяемый элемент * @param {Number} showenPart - Если число < 1 и > 0, то провека будет успешной если в области видимости только * часть элемента равная showenPart * 100% * @returns {boolean} */ value: function isScrolledIntoView(elem) { var showenPart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var docViewTop = window.pageYOffset || document.documentElement.scrollTop; var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var docViewBottom = docViewTop + windowHeight; var elemTop = this.getOffsetTop(elem); var elemBottom = elemTop; if (elem.offsetHeight) { elemBottom += elem.offsetHeight; } else { var parent = this.getParentTeaserBlock(elem, 'mgline'); if (parent) { elemBottom += parent.offsetHeight; } } return elemBottom - (1 - showenPart) * elem.offsetHeight <= docViewBottom && elemTop + (1 - showenPart) * elem.offsetHeight >= docViewTop; } /** * Получить смещение элемента от начала страницы * @param {HTMLElement} elem - Проверяемый элемент * @returns {number} */ }, { key: 'getOffsetTop', value: function getOffsetTop(elem) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var clientTop = docElem.clientTop || body.clientTop || 0; var top = box.top + scrollTop - clientTop; return Math.round(top); } /** * Находит родительский элемент тизера с заданым классом * @param {HTMLElement} elem - Проверяемый элемент * @param {string} className * @returns {?HTMLElement} */ }, { key: 'getParentTeaserBlock', value: function getParentTeaserBlock(elem, className) { var current = elem; while (current != document && current.parentNode) { if (current.className.indexOf(className) >= 0) { return current; } else { current = current.parentNode; } } return null; } }, { key: 'getTeaserAlign', /** * Возвращает положение тизера на странице * @param {HTMLElement} elem - Проверяемый элемент * @param {float} [percent = 1] percent * @returns {string} (left|right|center) */ value: function getTeaserAlign(elem) { var percent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var bodyWidth = document.body.scrollWidth; var teaserDims = this.getRect(elem, true); if (teaserDims.right * percent < 0.3 * bodyWidth) { return 'left'; } else if (teaserDims.left * (1 + (1 - percent)) >= 0.7 * bodyWidth) { return 'right'; } else { return 'center'; } } }, { key: 'getRect', /** * Возвращает позицию элемента * @param {HTMLElement} elem - Проверяемый элемент * @param {boolean} withScroll * @returns {{top: Number, bottom: Number, left: Number, right: Number, height: Number, width: Number}} */ value: function getRect(elem, withScroll) { var rect = elem.getBoundingClientRect(); var toReturn = { top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right, height: rect.height ? rect.height : rect.bottom - rect.top, width: rect.width ? rect.width : rect.right - rect.left }; if (withScroll) { var scroll = this.getScroll(); toReturn.top += scroll.top; toReturn.bottom += scroll.top; toReturn.left += scroll.left; toReturn.right += scroll.left; } return toReturn; } }, { key: 'getAtf', /** * Находится ли элемент на первом экране * @param {HTMLElement} elem - Проверяемый элемент * @returns {boolean} */ value: function getAtf(elem) { var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var elemTop = this.getOffsetTop(elem); return elemTop < windowHeight; } /** * Возвращает значения скролла * @returns {{top: number, left: number}} */ }, { key: 'getScroll', value: function getScroll() { return { top: document.body.scrollTop || document.documentElement.scrollTop || 0, left: document.body.scrollLeft || document.documentElement.scrollLeft || 0 }; } }, { key: 'removeClass', /** * Удалить класс элемента * @param element Элемент * @param className Имя класса */ value: function removeClass(element, className) { if (element) element.className = element.className.replace(new RegExp('(?:^|\\s)' + className, 'g'), ''); } }, { key: 'addClass', /** * Добавить класс элемента * @param element Элемент * @param className Имя класса */ value: function addClass(element, className) { if (!element) return; var cn = element.className; if (cn.indexOf(className) !== -1) { return; } if (cn !== '') { className = ' ' + className; } element.className = cn + className; } /** * Объеденяет два объекта в один * @param {object} object1 * @param {object} object2 * @returns {object} */ }, { key: 'mergeObjects', value: function mergeObjects(object1, object2) { var attrName = ''; for (attrName in object2) { if (object2.hasOwnProperty(attrName)) { object1[attrName] = object2[attrName]; } } return object1; } /** * Определяет мобильное устройство * @returns {boolean} */ }, { key: 'isMobile', value: function isMobile() { return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ); } /** * Определяет версию iOS * @returns {number|boolean} */ }, { key: 'iOSversion', value: function iOSversion() { var match = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); var version = 0; if (match !== undefined && match !== null) { version = [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3] || 0, 10)]; return parseFloat(version.join('.')); } return false; } /** * Создает элемент IMG * @param {string} src */ }, { key: 'createImg', value: function createImg(src) { var img0gif = new Image(); img0gif.src = src; } /** * Обновляет стили в браузере Safari * @param {object} jwPlayer */ }, { key: 'repaintSafari', value: function repaintSafari(jwPlayer) { if (jwPlayer && jwPlayer.utils.isSafari()) { var styleSheets = document.styleSheets; if (styleSheets) { var styleSheetsLenght = styleSheets.length; var i = void 0; for (i = 0; i < styleSheetsLenght; i++) { if (styleSheets[i].rules !== null) { styleSheets[i].addRule('.mgReload', 'color: red;'); styleSheets[i].removeRule(styleSheets[i].rules.length - 1); break; } } } } } /** * Переопределяет методы addEventListener, removeEventListener и добавляет метод getEventListeners(type) */ }, { key: 'setCustomEventListenerManager', value: function setCustomEventListenerManager() { ListenerTracker.init(); } /** * Определяет портретную ориентацию устройства */ }, { key: 'isPortrait', value: function isPortrait() { return window.matchMedia('(orientation: portrait)').matches; } /** * Определяет пейзажную ориентацию устройства */ }, { key: 'isLandscape', value: function isLandscape() { return window.matchMedia('(orientation: landscape)').matches; } /** * Декодирует ACSII строку в UNICODE (символы вида \uXXXX) * @param {string} inputString * @returns {string} */ }, { key: 'fromAscii', value: function fromAscii(inputString) { var res = inputString.replace(/\\u([\d\w]{4})/gi, function (match, grp) { return String.fromCharCode(parseInt(grp, 16)); }); res = res.replace(/\\"/g, '"').replace(/\\[nt]/g, ' '); return res; } }]); return Helpers; }(); var ListenerTracker = function () { function ListenerTracker() { _classCallCheck(this, ListenerTracker); this.elements = []; this.listeners = []; this.interceptEventsListeners(); } _createClass(ListenerTracker, [{ key: 'interceptEventsListeners', value: function interceptEventsListeners() { this.super = { addEventListener: HTMLElement.prototype.addEventListener, removeEventListener: HTMLElement.prototype.removeEventListener }; Element.prototype.addEventListener = function (type, listener, useCapture) { var listeners = ListenerTracker.registerElement(this); window.listTracker.super.addEventListener.apply(this, arguments); useCapture = useCapture ? 1 : 0; if (!listeners[useCapture][type]) listeners[useCapture][type] = []; listeners[useCapture][type].push(listener); }; Element.prototype.removeEventListener = function (type, listener, useCapture) { var listeners = ListenerTracker.registerElement(this); window.listTracker.super.removeEventListener.apply(this, arguments); useCapture = useCapture ? 1 : 0; if (!listeners[useCapture][type]) return; var lid = listeners[useCapture][type].indexOf(listener); if (lid > -1) listeners[useCapture][type].splice(lid, 1); }; Element.prototype.getEventListeners = function (type) { var listeners = ListenerTracker.registerElement(this); var result = []; for (var useCapture = 0, list; list = listeners[useCapture]; useCapture++) { if (typeof type === 'string') { if (list[type]) { for (var id in list[type]) { result.push({ type: type, listener: list[type][id], useCapture: !!useCapture }); } } } else { for (var _type in list) { for (var _id in list[_type]) { result.push({ type: _type, listener: list[_type][_id], useCapture: !!useCapture }); } } } } return result; }; } }], [{ key: 'init', value: function init() { if (!window.listTracker) { window.listTracker = new ListenerTracker(); } } }, { key: 'registerElement', value: function registerElement(element) { if (window.listTracker.elements.indexOf(element) === -1) { var eltListeners = [{/*useCapture=false*/}, {/*useCapture=true*/}]; window.listTracker.elements.push(element); window.listTracker.listeners.push(eltListeners); } return window.listTracker.listeners[window.listTracker.elements.indexOf(element)]; } }]); return ListenerTracker; }(); exports.Helpers = Helpers; },{}],6:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module Loader */ var Loader = function () { /** * Конструктор класса * @param {object} config {"jQuery":{"dep":[],"url":"..."},"slick":{"dep":["jQuery"],"url":"..."}} * @param {function} callback */ function Loader(config, callback) { var _this = this; _classCallCheck(this, Loader); this.config = config; this.callback = callback; this.loaded = {}; this.loading = {}; this.allLoaded = false; this.checkAgain = false; Object.keys(this.config).forEach(function (name) { if (_this.config[name].hasOwnProperty('exists')) { _this.loading[name] = false; _this.loaded[name] = !!eval(_this.config[name].exists); } }); this.checkLoaded(); } /** * Проверяет все ли библиотеки загрузились */ _createClass(Loader, [{ key: 'checkLoaded', value: function checkLoaded() { var _this2 = this; this.allLoaded = true; this.checkAgain = false; Object.keys(this.loaded).forEach(function (libName) { if (!_this2.loaded[libName]) { var allDepLoaded = true; if (_this2.config[libName].hasOwnProperty('dep')) { for (var i = 0; i < _this2.config[libName].dep.length; i++) { if (!_this2.loaded[_this2.config[libName].dep[i]]) { allDepLoaded = false; } } } if (allDepLoaded) { _this2.allLoaded = _this2.allLoaded && _this2.createScript(libName); } } }); if (this.checkAgain) { this.checkLoaded(); } else if (this.allLoaded) { this.callback(); } } /** * Создает элемент script * @param {string} libName Название елемента * @returns {boolean} */ }, { key: 'createScript', value: function createScript(libName) { var _this3 = this; var lib = document.getElementById(libName); if (!lib) { lib = document.createElement('script'); lib.id = libName; lib.src = this.config[libName].url; lib.onload = function () { _this3.onLoadScript(lib); }; document.head.appendChild(lib); this.loading[libName] = true; } else if (!lib.getAttribute('data-loaded') && !this.loading[libName]) { this.loading[libName] = true; var onLoadPrev = lib.onload; lib.onload = function () { _this3.onLoadScript(lib, onLoadPrev); }; } else if (lib.getAttribute('data-loaded')) { this.loaded[libName] = true; this.checkAgain = true; return true; } return false; } /** * Обработчик события загрузки скрипта * @param {HTMLElement} elem * @param {function} callback */ }, { key: 'onLoadScript', value: function onLoadScript(elem) { var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; elem.setAttribute('data-loaded', true); this.loaded[elem.id] = true; this.checkLoaded(); if (callback) { callback(); } } }]); return Loader; }(); exports.Loader = Loader; },{}],7:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module styles */ /** * Класс Styles */ var Styles = function () { function Styles() { _classCallCheck(this, Styles); } _createClass(Styles, null, [{ key: 'init', /** * Добавляет элемент styles в head с данными из конфигурации информера * @param {_mgLib4} widget - библиотека информеров */ value: function init(widget) { if (!widget.mgRec.stylesInited) { widget.mgRec.stylesInited = true; var style = document.createElement('style'); style.setAttribute('type', 'text/css'); style.appendChild(document.createTextNode(widget.mgRec.styles)); document.head.appendChild(style); } } }]); return Styles; }(); exports.Styles = Styles; },{}],8:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module teaserCapping */ /** * Класс TeaserCapping * при инициализации класса в него передается список тизеров на странице * в случае нахождения тизера в области видимости пользователя в метод callSensor() передаются ID видимых тизеров */ var TeaserCapping = function () { /** * Конструктор класса * @param {_mgLib4} widget * @param {Array.<{ teaserId: string, item: HTMLElement, hash: string }>} linkElems */ function TeaserCapping(widget, linkElems) { _classCallCheck(this, TeaserCapping); this.widget = widget; linkElems.forEach(function (i) { return i.shownTeaser = false; }); this.linkElems = linkElems; this.helpers = widget.modules.Helpers; this.sensorUrl = this.widget.libConfig.teaserCappingSensorUrl || '//c.mgid.com/c'; var currentProtocol = window.location.href.split('///'); this.fileProtocol = currentProtocol[0] === 'file:'; this.updateTeaserId(); } /** * Заполняет teaserId из id, если teaserId отсутствует в linkElems */ _createClass(TeaserCapping, [{ key: 'updateTeaserId', value: function updateTeaserId() { this.linkElems.forEach(function (linkElement) { if (!linkElement.teaserId) { linkElement.teaserId = linkElement.id; } }); } /** * Формирует и отправляет сообщение на сервер * @param {Array.|Array.<{ id: string, item: HTMLElement }> } ids Идентификаторы видимых тизеров * @param {boolean} withElements */ }, { key: 'callSensor', value: function callSensor(ids) { var _this = this; var withElements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!ids || ids.length === 0) { return; } var elements = ids; if (withElements) { ids = []; elements.forEach(function (i) { return ids.push(i.id); }); } var src = this.sensorUrl + '?pv=2&t=G'; var _loop = function _loop(i) { if (ids.indexOf(_this.linkElems[i].teaserId) >= 0 && !_this.linkElems[i].shownTeaser) { _this.linkElems[i].shownTeaser = true; var shownItem = _this.linkElems[i].item; if (withElements) { elements.forEach(function (e) { return e.id === _this.linkElems[i].teaserId ? shownItem = e.item : ''; }); } var parent = _this.helpers.getParentTeaserBlock(shownItem, 'mgline'); if (!parent) { parent = shownItem; } var elemText = '&v='; var align = _this.helpers.getTeaserAlign(shownItem); elemText += shownItem.offsetWidth + '|'; elemText += shownItem.offsetHeight + '|'; elemText += (align === 'left' ? 32 : 0) + (align === 'right' ? 16 : 0) + (_this.helpers.getAtf(parent) ? 8 : 0) + (parent.querySelector('.mcprice') && _this.helpers.isScrolledIntoView(parent.querySelector('.mcprice')) ? 2 : 0) + (parent.querySelector('.mcdesc') && _this.helpers.isScrolledIntoView(parent.querySelector('.mcdesc')) ? 1 : 0) + '|'; elemText += _this.linkElems[i].hash ? _this.linkElems[i].hash : ''; src += elemText; } }; for (var i = 0; i < this.linkElems.length; i++) { _loop(i); } if (this.widget.mgRec.cappingData) { src += this.widget.mgRec.cappingData.ts ? '&ts=' + this.widget.mgRec.cappingData.ts : ''; src += this.widget.mgRec.cappingData.tt ? '&tt=' + this.widget.mgRec.cappingData.tt : ''; src += this.widget.mgRec.cappingData.h2 ? '&h2=' + this.widget.mgRec.cappingData.h2 : ''; } src += '&cid=' + this.widget.mgRec.cid; if (!this.sendF && (!window._mgwcapping || window._mgwcapping.indexOf(this.widget.mgRec.cid) === -1)) { src += '&f=1'; this.sendF = true; if (!window._mgwcapping) { window._mgwcapping = []; } window._mgwcapping.push(this.widget.mgRec.cid); } this.widget.debug('Teaser capping sending message.'); this.widget.debug('Generated link: ' + src); if (!this.fileProtocol) { var img0gif = new Image(); img0gif.src = src; } } }]); return TeaserCapping; }(); exports.TeaserCapping = TeaserCapping; },{}],9:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module videoAds */ /** * Класс видео рекламмы для jwplayer */ var VideoAds = function () { _createClass(VideoAds, null, [{ key: 'init', /** * Создаёт экземпляр класса Video * @param {_mgLib4} widget - библиотека информеров */ value: function init(widget) { if (!widget.mgRec.config.wages_types) { widget.mgRec.config.wages_types = [widget.mgRec.config.wages_type]; } else if (typeof widget.mgRec.config.wages_types === 'string') { widget.mgRec.config.wages_types = widget.mgRec.config.wages_types.split(/\s*,\s*/); } widget.mgRec.config.wages_types.every(function (wt) { if (['video', 'video_content'].indexOf(wt) !== -1 && widget.mgRec.config.vast) { widget.videoAds = new VideoAds(widget); return false; } return true; }); } /** * Конструктор класса * @param {_mgLib4} widget - библиотека информеров */ }]); function VideoAds(widget) { _classCallCheck(this, VideoAds); this.widget = widget; this.config = widget.mgRec.config; this.vast = this.config.vast; this.iid = this.config.uid; this.skipoffset = this.config.skipoffset; this.linkElems = [{ teaserId: '0', item: this.widget.block, hash: null }]; var TeaserCapping = this.widget.modules.TeaserCapping; /** @type {TeaserCapping} */ this.teaserCapping = new TeaserCapping(this.widget, this.linkElems); this.sensorUrl = this.widget.libConfig.videoSensorUrl || '//c.mgid.com/vs/'; this.firstVastPlaying = true; /** @type {Helpers} */ this.helpers = widget.modules.Helpers; this.completeFunc = function () {}; this.resetStat(); } /** * Получить настройки рекламмы для jwplayer.setup * @param useFlash */ _createClass(VideoAds, [{ key: 'getAdsConfig', value: function getAdsConfig() { var useFlash = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; if (!this.macrosAdded) { var vasts = this.vast; if (!Array.isArray(vasts)) { vasts = [vasts]; } var playerWidth = '__player-width__'; var playerBlock = this.widget.block.querySelector('.video-info__player_' + this.widget.mgRec.cid); if (playerBlock) { var computedStyle = window.getComputedStyle(playerBlock); if (computedStyle.width) { playerWidth = parseInt(computedStyle.width); } } for (var i = 0; i < vasts.length; i++) { vasts[i] += (vasts[i].indexOf('?') === -1 ? '?' : '&') + 'jwc=__companion-div__' + ('&jwd=__domain__&jwh=__player-height__&jww=' + playerWidth) + '&jwn=__random-number__&jwu=__page-url__&jwt=__timestamp__&jwr=__referrer__'; if (vasts[i].indexOf('mgid.com') !== -1) { vasts[i] += '&flash=' + useFlash; } } this.macrosAdded = true; this.vast = vasts; } this.widget.debug('getAdsConfig: tag: ' + JSON.stringify(this.vast)); return { client: 'vast', skipoffset: this.skipoffset, schedule: { adbreak: { tag: this.vast, offset: this.config.adPosition ? this.config.adPosition : 'pre' } } }; } /** * This callback is called when ad completed. * @callback videoCallback */ /** * Настройка событий jwplayer * @param {object} params - объект с параметрами */ }, { key: 'addPlayerEvents', value: function addPlayerEvents(params) { var _this = this; var jwplayer = params.jwplayer, bottomLinkId = params.bottomLinkId, bottomLinkFinishId = params.bottomLinkFinishId, completeFunc = params.completeFunc, pauseFunc = params.pauseFunc, adPauseFunc = params.adPauseFunc, progressFunc = params.progressFunc, impressionFunc = params.impressionFunc, showPlayerFunc = params.showPlayerFunc, startedFunc = params.startedFunc, loadFunc = params.loadFunc, vpaidFunc = params.vpaidFunc, errorFunc = params.errorFunc; jwplayer.on('adRequest', function (e) { _this.widget.debug('adRequest'); _this.widget.debug(e.tag); _this.resetStat(); if (loadFunc) loadFunc(e); if (!_this.sensorLoad) { _this.callSensor('load'); _this.sensorLoad = true; } }); jwplayer.on('adMeta', function (e) { _this.widget.debug('adMeta'); _this.firstVastPlaying = !(e.witem && e.witem > 1); var mgVideoBottomLink = null; if (bottomLinkId) { mgVideoBottomLink = document.getElementById(bottomLinkId); } if (e.clickthrough) { _this.linkClickHandler = function () { if (jwplayer) { if (jwplayer.getConfig().mute) { _this.jwplayer.setMute(true); } if (pauseFunc && _this.jwPlayerStatus !== 'stop') pauseFunc(); } }; if (mgVideoBottomLink && mgVideoBottomLink.querySelector('a')) { _this.videoBottomLink = mgVideoBottomLink.querySelector('a'); _this.videoBottomLink.setAttribute('href', e.clickthrough); _this.videoBottomLink.addEventListener('click', _this.linkClickHandler); } if (bottomLinkFinishId) { var mgVideoBottomLinkFinish = document.getElementById(bottomLinkFinishId); if (mgVideoBottomLinkFinish && mgVideoBottomLinkFinish.querySelector('a')) { _this.videoBottomLinkFinish = mgVideoBottomLinkFinish.querySelector('a'); _this.videoBottomLinkFinish.setAttribute('href', e.clickthrough); _this.videoBottomLinkFinish.addEventListener('click', _this.linkClickHandler); } } var urlParts = void 0; if (urlParts = e.clickthrough.match(/\/ghits\/(\d+)\/.*[?&]h=([^&]+)/)) { _this.setTeaserId(urlParts[1]); _this.setHash(urlParts[2]); } } else if (mgVideoBottomLink) { mgVideoBottomLink.style.display = 'none'; } if (e.skipoffset) { if (typeof e.skipoffset === 'number') { _this.skipoffset = e.skipoffset; } else if (typeof e.skipoffset === 'string') { var timeParts = e.skipoffset.split(':'); if (timeParts.length > 2) { _this.skipoffset = (parseInt(timeParts[0]) || 0) * 60 * 60 + (parseInt(timeParts[1]) || 0) * 60 + (parseInt(timeParts[2]) || 0); } } _this.widget.debug('skipoffset: ' + _this.skipoffset); } }); jwplayer.on('adStarted', function (e) { _this.widget.debug('VPAID adStarted'); if (_this.jwPlayerStatus === 'hiddenPlay') { _this.widget.debug('adStarted: Found hiddenPlay'); if (showPlayerFunc) showPlayerFunc(); } if (startedFunc) startedFunc(); if (vpaidFunc) vpaidFunc(); _this.callSensor('vpaid', e.tag); }); jwplayer.on('adImpression', function (e) { _this.mediaType = e.creativetype; _this.widget.debug(e.creativetype); if (_this.mediaType === 'application/javascript') { var adStartInt = setInterval(function () { if (_this.jwplayer) _this.jwplayer.seek(); if (_this.adTimeStarted) { clearInterval(adStartInt); } }, 1000); } if (_this.jwPlayerStatus === 'hiddenPlay') { if (showPlayerFunc) showPlayerFunc(); } if (e.wrapper && e.wrapper.length > 0) { var wrapper = e.wrapper[0].match(/Mgid:(.+)/); _this.wrapper = wrapper && wrapper.length > 1 ? wrapper[1] : null; _this.setHash(_this.wrapper); _this.widget.debug('Found wrapper with hash: ' + _this.wrapper); } if (startedFunc) startedFunc(); }); jwplayer.on('adTime', function (e) { if (!_this.adPaused) { if (progressFunc) progressFunc(e.position, e.duration); } if (e.position > 0 && !_this.adTimeStarted) { _this.widget.debug('adTimeStarted'); _this.adTimeStarted = true; } if (!_this.cappingAdded && e.position >= 0 && _this.mediaType) { _this.widget.debug('adTime cappingAdded'); _this.cappingAdded = true; if (impressionFunc) impressionFunc(); if (_this.wrapper) { _this.callSensor('paid', e.tag); if (_this.teaserCapping && _this.widget.videoInread) { _this.teaserCapping.callSensor(['0']); } } } if (!_this.firstQuartile && e.position / e.duration >= 0.25) { _this.firstQuartile = true; _this.callSensor('video_25', e.position); } if (!_this.midpoint && e.position / e.duration >= 0.5) { _this.midpoint = true; _this.callSensor('video_50', e.position); } if (!_this.thirdQuartile && e.position / e.duration >= 0.75) { _this.thirdQuartile = true; _this.callSensor('video_75', e.position); _this.duration = e.duration; } _this.lastPosition = e.position; }); jwplayer.on('adPause', function () { _this.widget.debug('adPause'); _this.adPaused = true; if (_this.jwPlayerStatus === 'hiddenPlay') { if (showPlayerFunc) showPlayerFunc(); } if (adPauseFunc) adPauseFunc(); }); jwplayer.on('adPlay', function () { _this.adPaused = false; }); jwplayer.on('adClick', function (e) { _this.widget.debug('adClick'); _this.callSensor('click', e.tag); }); jwplayer.on('adSkipped', function () { _this.widget.debug('adSkipped'); _this.skipHandler(); }); jwplayer.on('adComplete', function () { _this.widget.debug('adComplete'); if (_this.wrapper) { _this.callSensor('complete', _this.duration); } if (completeFunc) completeFunc(); }); jwplayer.on('adError', function (e) { _this.widget.debug('adError: ' + e.message); _this.errorMessage = e.message; _this.callSensor('error', e.tag); if ((!e.witem || !e.wcount || e.witem === e.wcount) && completeFunc) completeFunc(); if (e.creativetype === 'application/x-shockwave-flash') { _this.widget.debug('Flash ads can not be played.'); } if (errorFunc) errorFunc(); }); if (completeFunc) { this.completeFunc = completeFunc; } } /** * Обработчик события Skip */ }, { key: 'skipHandler', value: function skipHandler() { this.callSensor('skip', this.lastPosition); this.completeFunc(); } /** * Устанавливаем стартовые значения переменным, необходимых для обработи событий рекламного блока jwPlayer */ }, { key: 'resetStat', value: function resetStat() { this.teaserId = 0; this.hash = ''; this.wrapper = null; this.adTimeStarted = false; this.cappingAdded = false; this.firstQuartile = false; this.midpoint = false; this.thirdQuartile = false; this.mediaType = ''; this.jwPlayerStatus = 'none'; this.lastPosition = 0; this.vrShowHash = ''; this.linkElems[0].hash = null; } /** * Отправляет запрос на video_sensor c указанным в параметрах событием * @param {string} eventName - Событие * @param {string} optional - Дополительный параметр, например time offset или error message */ }, { key: 'callSensor', value: function callSensor(eventName) { var optional = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; if (!this.firstVastPlaying && ['impression', 'paid', 'skip', 'click', 'video_25', 'video_50', 'video_75', 'complete'].indexOf(eventName) >= 0) return; var rnd = Math.floor(Math.random() * 65535); var templateId = this.config.templateId || '0'; var src = this.sensorUrl + '?tid=' + this.teaserId + '&iid=' + this.iid + '&e=' + eventName + '&o=' + encodeURIComponent(optional) + '&t=' + templateId + '&c=' + rnd; if (this.linkElems[0].hash) { src += '&h=' + this.linkElems[0].hash; } if (this.vrShowHash) { src += '&v=' + this.vrShowHash; } if (eventName === 'error') { src += '&src=' + encodeURIComponent(this.errorMessage); } this.widget.debug('Event ' + eventName + ' fired.'); this.widget.debug('Link generated: ' + src); return this.helpers.createImg(src); } }, { key: 'setTeaserId', value: function setTeaserId(teaserId) { this.teaserId = teaserId; this.linkElems[0].teaserId = teaserId; } }, { key: 'setHash', value: function setHash(hash) { this.hash = hash; this.linkElems[0].hash = hash; } }, { key: 'cleanHandlers', value: function cleanHandlers() { if (this.linkClickHandler) { if (this.videoBottomLink) this.videoBottomLink.removeEventListener('click', this.linkClickHandler); if (this.videoBottomLinkFinish) this.videoBottomLinkFinish.removeEventListener('click', this.linkClickHandler); } } }]); return VideoAds; }(); exports.VideoAds = VideoAds; },{}],10:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module VideoBase */ var VideoBase = function () { /** * Конструктор класса * @param {_mgLib4} widget */ function VideoBase(widget) { _classCallCheck(this, VideoBase); var config = widget.mgRec.config; this.widget = widget; this.jwPlayer = null; this.uid = config.uid; this.itemIndex = 0; this.sensorUrl = this.widget.libConfig.videoSensorUrl || '//c.mgid.com/vs/'; this.wasFirstClick = false; this.firstQuartile = false; this.midpoint = false; this.thirdQuartile = false; this.userSeekPaused = false; /** @type {Helpers} */ this.helpers = widget.modules.Helpers; /** @type {VideoAds} */ this.videoAds = widget.videoAds; this.sourceShowHash = 'null'; this.loadedAds = true; this.timeLeftText = this.helpers.isMobile() ? 'Ad: (%mm%:%ss%)' : 'Advertisement: (%mm%:%ss%)'; this.mgVideoIndex = widget.mgRec.cid + '_' + widget.getWidgets().length; widget.debug('mgVideoIndex: ' + this.mgVideoIndex); this.helpers.setCustomEventListenerManager(); } /** * Прорисовывает информер в скрытом виде и инициализирует jwplayer */ _createClass(VideoBase, [{ key: 'renderWidget', value: function renderWidget() { this.widget.debug(this.constructor.name + ' renderWidget'); this.widget.block.className += ' mgVideoContainer_' + this.widget.mgRec.cid; this.addTemplate(); } /** * Подгружает библиотеки jwplayer */ }, { key: 'addLibraries', value: function addLibraries() { var _this = this; var jwplayerLib = { url: this.jwplatformUrl, exists: 'typeof window.jwplayer !== \'undefined\'' }; this.widget.mgRec.config.extLibraries = this.widget.mgRec.config.extLibraries || {}; this.widget.mgRec.config.extLibraries.mgJwplatform = jwplayerLib; var Loader = this.widget.modules.Loader; new Loader(this.widget.mgRec.config.extLibraries, function () { _this.renderWidget(); }); } /** * Добавляет индексы к ID элементов * @param {HTMLElement[]} children */ }, { key: 'addIndexes', value: function addIndexes(children) { if (children.length > 0) { for (var i = 0; i < children.length; i++) { if (children[i].getAttribute('id')) { children[i].setAttribute('id', children[i].getAttribute('id') + this.mgVideoIndex); } this.addIndexes(children[i].children); } } } /** * Поиск и выполнение элементов script в шаблоне */ }, { key: 'addCustomScripts', value: function addCustomScripts() { var scripts = this.widget.block.querySelectorAll('script'); for (var i = 0; i < scripts.length; i++) { var script = document.getElementById('Custom_' + this.mgVideoIndex + '_' + i); if (!script) { var customScript = document.createElement('script'); customScript.innerHTML = scripts[i].innerHTML; customScript.id = 'Custom_' + this.mgVideoIndex + '_' + i; document.head.appendChild(customScript); } } } /** * Останавливает VPAID iframe */ }, { key: 'stopVpaid', value: function stopVpaid() { var _this2 = this; var isTimeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; this.widget.debug('stopVpaid: ' + isTimeout); if (this.loadedAds) { if (!isTimeout) this.stopVpaidLoopRun = true; if (this.jwPlayer) { this.jwPlayer.skipAd(); this.widget.debug('stopVpaid: Finish loop. jwPlayer.state: ' + this.jwPlayer.getState() + (' stopVpaidLoopRun: ' + this.stopVpaidLoopRun)); } this.pauseVideosInBlock(this.widget.block); this.jwMedia = this.widget.block.querySelector('.jw-media'); if (this.jwMedia) { var childNodes = this.jwMedia.childNodes; if (childNodes) { childNodes = Array.prototype.slice.call(childNodes); childNodes.forEach(function (node) { if (node.tagName === 'IFRAME') { if (node.contentDocument) { _this2.pauseVideosInBlock(node.contentDocument); if (node.contentDocument.querySelector('body')) node.contentDocument.querySelector('body').style.height = '0'; } } if (node.tagName !== 'VIDEO') { node.style.display = 'none'; node.style.height = '0'; } }); } } } } /** * Ставит на паузу все видео в блоке * @param {Element|Document} block */ }, { key: 'pauseVideosInBlock', value: function pauseVideosInBlock(block) { var videos = block.querySelectorAll('video:not(.jw-video)'); if (videos.length) { videos = Array.prototype.slice.call(videos); videos.forEach(function (node) { node.pause(); }); } } /** * Сбрасывает метки просмотра и полосу прогресса рекламного ролика */ }, { key: 'resetMarks', value: function resetMarks() { this.firstQuartile = false; this.midpoint = false; this.thirdQuartile = false; this.progress10s = false; this.progress20s = false; this.vimpressionSent = false; this.vimpressionTime = null; this.adSeeked = false; this.skipElementInitiated = false; this.updateProgressBar(0); } /** * Изменяет ширину progress bar'а времени рекламы * @param {number} progress */ }, { key: 'updateProgressBar', value: function updateProgressBar(progress) { if (!progress) { this.previousProgress = 0; } if (!this.progressBar) { this.progressBar = this.widget.block.querySelector('.mg-progress-point_' + this.widget.mgRec.cid); } if (this.progressBar && progress >= this.previousProgress) { this.previousProgress = progress; this.progressBar.style.width = 100 * progress + '%'; } } /** * Обновляет таймер окончания рекламного ролика * @param {number} secLeft */ }, { key: 'updateTimeLeft', value: function updateTimeLeft(secLeft) { var seconds = secLeft % 60; var minutes = Math.floor(secLeft / 60); if (!this.timeVideoLeftElement) { this.timeVideoLeftElement = this.widget.block.querySelector('.videoTimeLeftText_' + this.widget.mgRec.cid); } if (this.timeVideoLeftElement && (!this.previousTimeLeft && this.previousTimeLeft !== 0 || this.previousTimeLeft > secLeft)) { if (secLeft >= 0) { this.previousTimeLeft = secLeft; this.timeVideoLeftElement.innerText = this.timeLeftText.replace(/%mm%/, minutes).replace(/%ss%/, seconds > 9 ? seconds : '0' + seconds); } else { this.timeVideoLeftElement.innerText = ''; } } } /** * Обнуляет таймер окончания рекламного ролика */ }, { key: 'resetTimeLeft', value: function resetTimeLeft() { this.previousTimeLeft = null; this.timeLeft = 0; this.updateTimeLeft(-1); } /** * Возвращает экземпляр наблюдателя * @returns {MutationObserver} */ }, { key: 'getObserver', value: function getObserver() { var _this3 = this; if (!this.observer) { this.observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.type === 'childList') { if (mutation.addedNodes.length) { var addedNodes = Array.prototype.slice.call(mutation.addedNodes); addedNodes.forEach(function (node) { if (node.tagName === 'VIDEO' && (_this3.helpers.isMobile() || node.className.indexOf('jw-video') === -1)) { node.addEventListener('play', function () { if (_this3.popupVRW && _this3.popupVRW.style.visibility === 'hidden') { node.pause(); } }); node.addEventListener('timeupdate', function (e) { _this3.progressAdvertisement(e.target.currentTime, e.target.duration); }); } }); } } }); }); } return this.observer; } }, { key: 'clearEventListeners', value: function clearEventListeners() { this.helpers.removeClass(this.jwPlayer.getContainer(), 'jw-flag-ads-hide-controls'); if (!this.jwVideo) { this.jwVideo = this.widget.block.querySelector('.jw-video'); } if (this.jwVideo) { var eventListeners = this.jwVideo.getEventListeners('click'); for (var i = 0; i < eventListeners.length; i++) { this.jwVideo.removeEventListener('click', eventListeners[i].listener); } this.widget.debug('EventListeners cleared.'); } } /** * Заполняет дополнительные значения * @param {Element|Document} elem * @param {{duration: number, impressions: number}} videoExt */ }, { key: 'fillAdditional', value: function fillAdditional(elem, videoExt) { var viewsElem = elem.querySelector('.mg-total-views'); if (viewsElem && videoExt.impressions) { viewsElem.innerText = viewsElem.innerText.replace(/^\d*/, videoExt.impressions); } var durationElem = elem.querySelector('.mg-video-duration') || elem.querySelector('.mgline-pop__duration'); if (durationElem && videoExt.duration) { var seconds = videoExt.duration % 60; var minutes = Math.floor(videoExt.duration / 60); durationElem.innerText = minutes + ':' + (seconds > 9 ? seconds : '0' + seconds); } } /** * Отмечает прогресс рекламного ролика * @param {Number} position * @param {Number} duration */ }, { key: 'progressAdvertisement', value: function progressAdvertisement(position, duration) { this.updateProgressBar(position / duration); if (!this.previousTimeLeft) { if (!this.jwMedia) this.jwMedia = this.widget.block.querySelector('.jw-media'); if (this.jwMedia) { var childNodes = this.jwMedia.querySelectorAll('div>div'); childNodes = Array.prototype.slice.call(childNodes); /** @var {Node} node */ childNodes.forEach(function (node) { if (node.style.pointerEvents === 'all') { node.style.bottom = node.style.height; } }); } } this.timeLeft = Math.floor(duration - position); this.updateTimeLeft(this.timeLeft); } }]); return VideoBase; }(); exports.VideoBase = VideoBase; },{}],11:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.VideoInline = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _videoBase = require('./videoBase'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** @module VideoInline */ var STATUS_PLAYING = 'playing'; var STATUS_PAUSED = 'paused'; var STATUS_INIT = 'init'; var PLAYER_MUTED = 'muted'; var PLAYER_UNMUTED = 'unmuted'; var PLAYER_STRETCHED = 'stretched'; var PLAYER_NORMAL = 'normal'; var VideoInline = function (_VideoBase) { _inherits(VideoInline, _VideoBase); /** * Конструктор класса * @param {_mgLib4} widget - библиотека информеров */ function VideoInline(widget) { _classCallCheck(this, VideoInline); var _this = _possibleConstructorReturn(this, (VideoInline.__proto__ || Object.getPrototypeOf(VideoInline)).call(this, widget)); _this.jwplatformUrl = widget.mgRec.config.jwplatformUrl || widget.libConfig.jwPlayerIdInline; _this.playerStatus = null; _this.playerSize = PLAYER_NORMAL; _this.muteStatus = PLAYER_MUTED; _this.jwPlayerReady = false; /** @type {Array.<{id:string, title:string, img:string, link:string, hash:string}>} */ _this.playlist = _this.widget.mgRec.vr_playlist || []; /** @type {HTMLElement} */ _this.titleElem = null; var TeaserCapping = _this.widget.modules.TeaserCapping; _this.teaserCapping = new TeaserCapping(_this.widget, _this.playlist); _this.addWindowListeners(); _this.addLibraries(); return _this; } /** * Создаёт экземпляр класса VideoInline * @param {_mgLib4} widget - библиотека информеров */ _createClass(VideoInline, [{ key: 'addTemplate', /** * Добавляет html элементы плеера */ value: function addTemplate() { if (this.widget.mgRec.template) { this.widget.block.innerHTML = this.widget.mgRec.template; } var children = this.widget.block.children; this.addIndexes(children); this.videoBlock = this.widget.block.querySelector('#vrJwPlayerBlock_' + this.mgVideoIndex); this.teaserElem = this.widget.block.querySelector('.vrline'); var videoTeaserImg = this.widget.block.querySelector('.vrline .mcimg .image-container'); if (videoTeaserImg && this.videoBlock) { videoTeaserImg.appendChild(this.videoBlock); } this.titleElem = this.widget.block.querySelector('.mctitle a[href*="javascript:void({\'id\':\'' + this.playlist[0].id + '\'"]'); this.popup = document.getElementById('vrPopup_' + this.mgVideoIndex); var items = this.widget.block.querySelectorAll('.mcimg>a'); for (var i = 0; i < items.length; i++) { var json = items[i].getAttribute('href'); if (!json) continue; json = json.substring(json.indexOf('({') + 1, json.indexOf('})') + 1); json = json.replace(/'/gm, '"'); try { var item = JSON.parse(json); if (item.videoExt) { var videoExt = JSON.parse(atob(item.videoExt)); if (videoExt) { this.fillAdditional(items[i], videoExt); } } } catch (ex) {} } this.addCustomScripts(); this.initInlinePlayer(); } /** * Добавляет обработчики событий к window */ }, { key: 'addWindowListeners', value: function addWindowListeners() { var _this2 = this; window.addEventListener('scroll', function () { _this2.checkPlayer(); }); } /** * Инициализация jwplayer в режиме inline */ }, { key: 'initInlinePlayer', value: function initInlinePlayer() { var _this3 = this; var jwId = 'mgJwPlayer_' + this.mgVideoIndex; var playlist = []; if (this.playlist) { for (var i = 0; i < this.playlist.length; i++) { var videoLink = this.playlist[i].link; videoLink = videoLink.replace(/\.mp4/, '_360.mp4'); playlist.push({ file: videoLink, image: this.playlist[i].img, title: this.playlist[i].title, mediaid: this.playlist[i].id }); } } this.jwPlayer = jwplayer(jwId); this.jwPlayer.setup(this.helpers.mergeObjects({ autostart: false, repeat: true, mute: true, advertising: this.videoAds ? this.videoAds.getAdsConfig(0) : {}, aspectratio: '16:9', width: '100%', playlist: playlist, abouttext: 'Native Video by MGID', aboutlink: 'https://www.mgid.com/', key: 'csf/L2teHL4F9Bs6xS1UvQl4h2Vjay94HN3dAg==' }, this.widget.mgRec.config.jwsetup)); this.jwPlayer.on('ready', function () { _this3.widget.debug('JWPlayer ready'); _this3.jwPlayerReady = true; _this3.playerStatus = STATUS_INIT; _this3.jwPlayer.getContainer().style.display = 'block'; var mediaQueryList = window.matchMedia('(orientation: portrait)'); mediaQueryList.addListener(function (e) { if (e.matches) { _this3.orientationPortrait && setTimeout(function () { _this3.orientationPortrait(); }, 0); } else { _this3.orientationLandscape && setTimeout(function () { _this3.orientationLandscape(); }, 0); } }); if (_this3.helpers.isMobile() && _this3.helpers.isPortrait()) { _this3.getThumbnailImg().style.setProperty('height', '0', 'important'); } else { _this3.getThumbnailImg(); _this3.jwPlayer.getContainer().style.setProperty('height', '0', 'important'); } var resumeCover = _this3.widget.block.querySelector('.mgCover_' + _this3.widget.mgRec.cid); if (resumeCover) { resumeCover.addEventListener('click', function () { resumeCover.style.display = 'none'; _this3.callSensor('vr_click', 0); _this3.setMute(false); _this3.muteStatus = PLAYER_UNMUTED; if (_this3.helpers.isPortrait()) { _this3.checkPlayer(); } if (_this3.volumeBtn) { _this3.helpers.removeClass(_this3.volumeBtn, 'jw-off'); } }); resumeCover.style.display = 'block'; } _this3.volumeBtn = _this3.widget.block.querySelector('.mgVolumeButton_' + _this3.widget.mgRec.cid); if (_this3.volumeBtn) { _this3.volumeBtn.addEventListener('click', function () { _this3.jwPlayer.setMute(); if (_this3.jwPlayer.getMute()) { _this3.helpers.addClass(_this3.volumeBtn, 'jw-off'); _this3.muteStatus = PLAYER_MUTED; } else { _this3.helpers.removeClass(_this3.volumeBtn, 'jw-off'); _this3.muteStatus = PLAYER_UNMUTED; } }); if (_this3.helpers.isPortrait()) { _this3.volumeBtn.style.display = 'block'; } } _this3.helpers.repaintSafari(_this3.jwPlayer); _this3.checkPlayer(); }); var teaserLinks = this.widget.block.querySelectorAll('a[href*="javascript:void({\'id\':\'' + this.playlist[0].id + '\'"]'); for (var _i = 0; _i < teaserLinks.length; _i++) { teaserLinks[_i].addEventListener('click', function (e) { if (e.target.tagName === 'A' || e.target.tagName === 'IMG' || e.target.parentNode.tagName === 'A') { if (_this3.jwPlayer && _this3.helpers.isLandscape()) { _this3.jwPlayer.getContainer().style.setProperty('height', '', ''); _this3.setFullscreen(true); _this3.jwPlayer.play(true); } } }); } if (!this.jwMedia) this.jwMedia = this.widget.block.querySelector('.jw-media'); this.jwMedia && this.getObserver().observe(this.jwMedia, { childList: true, subtree: true }); this.addPlayerEvents(); } /** * Настройка событий jwplayer */ }, { key: 'addPlayerEvents', value: function addPlayerEvents() { var _this4 = this; this.jwPlayer.on('playlistItem', function () { _this4.resetMarks(); _this4.changeTitle(); }); this.jwPlayer.on('displayClick', function () {}); this.jwPlayer.on('firstFrame', function () { _this4.playerStatus = STATUS_PLAYING; _this4.stopVpaid(true); _this4.callSensor('vr_impression'); }); /** @param {{duration: number, position: number}} e */ this.jwPlayer.on('time', function (e) { if (!_this4.firstQuartile && e.position / e.duration > 0.25) { _this4.firstQuartile = true; _this4.callSensor('vr_progress_25', e.position); } if (!_this4.midpoint && e.position / e.duration > 0.5) { _this4.midpoint = true; _this4.callSensor('vr_progress_50', e.position); } if (!_this4.thirdQuartile && e.position / e.duration > 0.75) { _this4.thirdQuartile = true; _this4.callSensor('vr_progress_75', e.position); _this4.duration = e.duration; } if (!_this4.vimpressionTime) { _this4.vimpressionTime = e.position; } if (!_this4.vimpressionSent && _this4.vimpressionTime + 2 <= e.position) { _this4.vimpressionSent = true; _this4.callSensor('vr_vimpression', e.position); } if (!_this4.progress10s && e.position >= 10) { _this4.progress10s = true; _this4.callSensor('vr_progress_10s', e.position); } if (!_this4.progress20s && e.position >= 20) { _this4.progress20s = true; _this4.callSensor('vr_progress_20s', e.position); } }); this.jwPlayer.on('beforeComplete', function () { if (_this4.thirdQuartile) { _this4.callSensor('vr_progress_100', _this4.duration); } }); /** @param {{playReason: string}} e */ this.jwPlayer.on('play', function (e) { if (e.playReason === 'interaction') { _this4.playerStatus = STATUS_PLAYING; if (!_this4.nextButtonPressed && !_this4.userSeekPaused) { _this4.callSensor('vr_play', _this4.jwPlayer.getPosition()); } else { if (_this4.userSeekPaused) { _this4.jwPlayer.pause(true); } _this4.nextButtonPressed = false; _this4.userSeekPaused = false; } } if (_this4.muteStatus === PLAYER_MUTED) { _this4.setMute(true); } if (_this4.bufferingTimeout) { clearTimeout(_this4.bufferingTimeout); _this4.bufferingTimeout = null; } if (_this4.helpers.isMobile()) { _this4.helpers.removeClass(_this4.jwPlayer.getContainer(), 'jw-flag-ads-hide-controls'); } }); /** @param {{oldstate: string}} e */ this.jwPlayer.on('buffer', function () { if (!_this4.bufferingTimeout) { _this4.bufferingTimeout = setTimeout(function () { _this4.bufferingTimeout = null; _this4.jwPlayer.seek(_this4.jwPlayer.getPosition()); }, 3000); } }); this.jwPlayer.on('mute', function (e) { if (!_this4.muteArtificial) _this4.callSensor(e.mute ? 'vr_mute' : 'vr_unmute', _this4.jwPlayer.getPosition()); _this4.muteArtificial = false; }); /** @param {{pauseReason: string}} e */ this.jwPlayer.on('pause', function (e) { if (e.pauseReason === 'interaction') { _this4.playerStatus = STATUS_PAUSED; _this4.callSensor('vr_pause', _this4.jwPlayer.getPosition()); } if (_this4.vimpressionTime) { _this4.vimpressionTime = null; } if (_this4.helpers.isMobile()) { _this4.helpers.removeClass(_this4.jwPlayer.getContainer(), 'jw-flag-ads-hide-controls'); } }); this.jwPlayer.on('fullscreen', function (e) { if (!_this4.fullscreenArtificial) { _this4.callSensor(e.fullscreen ? 'vr_fullscreen' : 'vr_windowed', _this4.jwPlayer.getPosition()); } if (!e.fullscreen && (!_this4.helpers.isMobile() || _this4.helpers.isLandscape())) { setTimeout(function () { window.scrollTo(0, _this4.helpers.getRect(_this4.widget.block, true).top); }, 100); _this4.jwPlayer.getContainer().style.setProperty('height', '0', 'important'); _this4.jwPlayer.pause(true); } _this4.fullscreenArtificial = false; }); /** @param {{offset: number, position: number}} e */ this.jwPlayer.on('seek', function (e) { if (_this4.vimpressionTime) { _this4.vimpressionTime = e.offset - (e.position - _this4.vimpressionTime); } if (_this4.jwPlayer.getState() === 'paused') { _this4.userSeekPaused = true; } }); this.jwPlayer.on('seeked', function () { if (_this4.jwPlayer.getState() !== 'paused') { _this4.checkPlayer(); } }); if (this.videoAds) { this.videoAds.addPlayerEvents({ jwplayer: this.jwPlayer, bottomLinkId: 'mgVideoBottomLink_' + this.mgVideoIndex, progressFunc: function progressFunc() { if (_this4.muteStatus === PLAYER_MUTED && !_this4.jwPlayer.getMute()) { _this4.setMute(true); } }, startedFunc: function startedFunc() { _this4.loadedAds = true; var videoInfoFrameElement = _this4.widget.block.querySelector('.video-info__frame_' + _this4.widget.mgRec.cid) || _this4.widget.block.querySelector('#vrJwPlayerBlock_' + _this4.mgVideoIndex); _this4.helpers.addClass(videoInfoFrameElement, 'adEnable'); if (_this4.bufferingTimeout) { clearTimeout(_this4.bufferingTimeout); _this4.bufferingTimeout = null; } if (_this4.muteStatus === PLAYER_MUTED) { _this4.setMute(true); } }, completeFunc: function completeFunc() { var videoInfoFrameElement = _this4.widget.block.querySelector('.video-info__frame_' + _this4.widget.mgRec.cid) || _this4.widget.block.querySelector('#vrJwPlayerBlock_' + _this4.mgVideoIndex); _this4.helpers.removeClass(videoInfoFrameElement, 'adEnable'); if (_this4.vpaidStarted && _this4.skipElement) { _this4.vpaidStarted = false; _this4.skipElement.style.display = 'none'; } if (_this4.skipOffsetElement) _this4.skipOffsetElement.style.display = 'none'; _this4.updateProgressBar(0); _this4.resetTimeLeft(); }, pauseFunc: function pauseFunc() { if (_this4.jwPlayer) { _this4.jwPlayer.pause(true); } }, adPauseFunc: function adPauseFunc() { if (_this4.jwPlayer && _this4.vpaidStarted) { var resumeCover = _this4.widget.block.querySelector('.mgCover_' + _this4.widget.mgRec.cid); if (resumeCover) { resumeCover.addEventListener('click', function () { _this4.jwPlayer.play(true); resumeCover.style.display = 'none'; }); resumeCover.style.display = 'block'; } } }, loadFunc: function loadFunc(e) { _this4.videoAds.vrShowHash = _this4.playlist[_this4.jwPlayer.getPlaylistIndex()].hash; _this4.loadedAds = false; _this4.videoAds.callSensor('opportunity', e.tag); }, vpaidFunc: function vpaidFunc() { _this4.vpaidStarted = true; if (!_this4.adSeeked && (!_this4.helpers.iOSversion() || _this4.helpers.iOSversion() >= 10)) { _this4.adSeeked = true; _this4.jwPlayer.seek(0); } _this4.updateProgressBar(0); _this4.resetTimeLeft(); if (!_this4.skipElementInitiated) { _this4.skipElementInitiated = true; _this4.skipOffsetElement = _this4.widget.block.querySelector('.mgVideoSkipOffset_' + _this4.widget.mgRec.cid); if (_this4.skipOffsetElement) { _this4.timeToSkipLeftElem = _this4.skipOffsetElement.querySelector('#mgVideoSkipOffsetText_' + _this4.mgVideoIndex); if (_this4.timeToSkipLeftElem) { _this4.timeToSkipLeftElem.innerText = _this4.videoAds.skipoffset || 5; if (_this4.timeToSkipIntervalId) clearInterval(_this4.timeToSkipIntervalId); _this4.timeToSkipIntervalId = setInterval(function () { _this4.timeToSkipLeftElem.innerText = parseInt(_this4.timeToSkipLeftElem.innerText) - 1; if (parseInt(_this4.timeToSkipLeftElem.innerText) <= 0 && _this4.timeToSkipIntervalId) { clearInterval(_this4.timeToSkipIntervalId); _this4.timeToSkipIntervalId = null; if (_this4.skipOffsetElement) _this4.skipOffsetElement.style.display = 'none'; if (_this4.skipElement) _this4.skipElement.style.display = 'block'; } }, 1000); } _this4.skipOffsetElement.style.display = 'block'; } _this4.skipElement = _this4.widget.block.querySelector('.mgVideoSkip_' + _this4.widget.mgRec.cid); if (_this4.skipElement) { _this4.skipElement.onclick = function () { _this4.widget.debug('skipElement click.'); _this4.skipElement.style.display = 'none'; _this4.stopVpaid(); _this4.videoAds.skipHandler(); if (_this4.helpers.isMobile()) { _this4.clearEventListeners(); } }; _this4.skipElement.style.display = 'none'; } } if (_this4.muteStatus === PLAYER_MUTED) { _this4.setMute(true); } }, errorFunc: function errorFunc() { _this4.loadedAds = true; } }); } } /** * Проверка видимости плеера */ }, { key: 'checkPlayer', value: function checkPlayer() { if (this.jwPlayer && this.jwPlayerReady) { if (this.helpers.isMobile() && this.helpers.isPortrait()) { var playerContainer = this.jwPlayer.getContainer(); if (this.playerStatus === STATUS_PLAYING || this.playerStatus === STATUS_INIT) { if (this.helpers.isScrolledIntoView(playerContainer)) { if (!this.teaserCappingTriggered) { this.teaserCapping.callSensor([{ id: this.playlist[0].id, item: playerContainer }], true); this.teaserCappingTriggered = true; } if (['playing', 'buffering'].indexOf(this.jwPlayer.getState()) === -1) { if (!this.sourceShowHashUpdated) { this.sourceShowHash = this.playlist[0].hash; this.sourceShowHashUpdated = true; } this.jwPlayer.play(true); } } else if (!this.helpers.isScrolledIntoView(playerContainer, 0.9)) { if (['paused', 'idle'].indexOf(this.jwPlayer.getState()) === -1) { this.jwPlayer.pause(true); } } } } } else { var teaserImg = this.widget.block.querySelector('.vrline .mcimg > a'); if (teaserImg && this.helpers.isScrolledIntoView(teaserImg) && !this.teaserCappingTriggered) { this.teaserCapping.callSensor([{ id: this.playlist[0].id, item: teaserImg }], true); this.teaserCappingTriggered = true; } } } /** * Отправляет запрос на video_sensor c указанным в параметрах событием * @param {string} eventName - Событие * @param {Number} position - Позиция видеофайла в секундах * * Клик по рекомендационному блоку ( vr_click ) * Старт воспроизведения видео ( vr_impression ) * 25%, 50%, 75%, 100% просмотра ( vr_progress_25, vr_progress_50, vr_progress_75, vr_progress_100 ) */ }, { key: 'callSensor', value: function callSensor(eventName) { var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var rnd = Math.floor(Math.random() * 65535); var teaserId = this.playlist[this.jwPlayer.getPlaylistIndex()].id; var clickAddition = '&h=' + this.playlist[this.jwPlayer.getPlaylistIndex()].hash; if (eventName === 'vr_click') { if (this.widget.mgRec.cappingData) { clickAddition += typeof this.widget.mgRec.cappingData.isBot !== 'undefined' ? '&o=' + this.widget.mgRec.cappingData.isBot : '&o=0'; } else { clickAddition += '&o=0'; } clickAddition += '&src=' + position; if (!this.sourceShowHashUpdated) { clickAddition += '&v=' + this.sourceShowHash; } } else { clickAddition += '&o=' + Math.floor(position); if (eventName.indexOf('vr_') === 0) { if (this.sourceShowHash !== this.playlist[this.jwPlayer.getPlaylistIndex()].hash) { clickAddition += '&v=' + this.sourceShowHash; } } } var templateId = this.widget.mgRec.config.templateId || '0'; var src = this.sensorUrl + '?tid=' + teaserId + '&iid=' + this.widget.mgRec.cid + ('&e=' + eventName + clickAddition + '&t=' + templateId + '&c=' + rnd); this.widget.debug('Event ' + eventName + ' fired.'); this.widget.debug('Generated link: ' + src); return this.helpers.createImg(src); } /** * Растягивает плеер на ширину окна браузера * @returns {?Element} */ }, { key: 'stretchPlayer', value: function stretchPlayer() { if (!this.videoBlock) { this.videoBlock = this.widget.block.querySelector('#vrJwPlayerBlock_' + this.mgVideoIndex); } if (this.videoBlock) { if (this.teaserElem) { this.teaserElem.style.overflow = 'visible'; } this.videoBlock.parentNode.style.overflow = 'visible'; this.videoBlock.style.position = 'absolute'; this.videoBlock.style.width = window.innerWidth + 'px'; this.videoBlock.style.left = '-' + this.helpers.getRect(this.videoBlock.parentNode).left + 'px'; this.videoBlock.style.top = 0; this.videoBlock.style.height = '100%'; this.videoBlock.style.maxWidth = 'none'; this.jwPlayer.resize(); this.videoBlock.parentNode.style.height = this.jwPlayer.getHeight() + 'px'; } return this.videoBlock; } /** * Возвращает плеер в нормальное состояние * @returns {?Element} */ }, { key: 'normalizePlayer', value: function normalizePlayer() { if (!this.videoBlock) { this.videoBlock = document.querySelector('#vrJwPlayerBlock_' + this.mgVideoIndex); } if (this.videoBlock) { this.videoBlock.parentNode.setAttribute('style', ''); this.videoBlock.setAttribute('style', ''); if (this.teaserElem) { this.teaserElem.style.overflow = ''; } this.jwPlayer.resize(); } return this.videoBlock; } /** * Функция обновления заголовка тизера */ }, { key: 'changeTitle', value: function changeTitle() { if (this.titleElem && this.jwPlayer) { this.titleElem.innerText = this.playlist[this.jwPlayer.getPlaylistIndex()].title; this.getThumbnailImg(); } } /** * Возвращает миниатюру видео * @returns {?Element} */ }, { key: 'getThumbnailImg', value: function getThumbnailImg() { if (!this.thumbnailImg) { this.thumbnailImg = this.widget.block.querySelector('.image-container img.mcimg'); } this.thumbnailImg.src = this.playlist[this.jwPlayer.getPlaylistIndex()].img; this.thumbnailImg.alt = this.playlist[this.jwPlayer.getPlaylistIndex()].title; return this.thumbnailImg; } /** * Обработчик перехода в портретную ориентацию */ }, { key: 'orientationPortrait', value: function orientationPortrait() { var _this5 = this; if (this.jwPlayer) { this.getThumbnailImg().style.setProperty('height', '0', 'important'); this.jwPlayer.getContainer().style.setProperty('height', '', ''); this.setFullscreen(false); if (['playing', 'buffering'].indexOf(this.jwPlayer.getState()) !== -1) { setTimeout(function () { window.scrollTo(0, _this5.helpers.getRect(_this5.jwPlayer.getContainer(), true).top); }, 0); } if (this.playerSize === PLAYER_STRETCHED) { this.stretchPlayer(); } this.checkPlayer(); } if (this.volumeBtn) { this.volumeBtn.style.display = 'block'; } } /** * Обработчик перехода в пейзажную ориентацию */ }, { key: 'orientationLandscape', value: function orientationLandscape() { if (this.jwPlayer) { this.normalizePlayer(); this.getThumbnailImg().style.setProperty('height', '', ''); if (['playing', 'buffering'].indexOf(this.jwPlayer.getState()) !== -1) { this.setFullscreen(true); } else { this.jwPlayer.pause(true); this.jwPlayer.getContainer().style.setProperty('height', '0', 'important'); } } if (this.volumeBtn) { this.volumeBtn.style.display = 'none'; } } /** * Управление заглушением звука плеера * @param {boolean} state */ }, { key: 'setMute', value: function setMute(state) { if (this.jwPlayer) { this.muteArtificial = true; this.jwPlayer.setMute(state); } } /** * Управление полноэкранным режимом плеера * @param {boolean} state * @param {boolean} isArtificial */ }, { key: 'setFullscreen', value: function setFullscreen(state) { var isArtificial = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; if (this.jwPlayer) { if (isArtificial) this.fullscreenArtificial = true; this.jwPlayer.setFullscreen(state); } } }], [{ key: 'init', value: function init(widget) { if (widget.mgRec.config.wages_types.indexOf('video_content') !== -1 && widget.mgRec.config.format && widget.mgRec.config.format === 'inline') { widget.videoInline = new VideoInline(widget); } } }]); return VideoInline; }(_videoBase.VideoBase); exports.VideoInline = VideoInline; },{"./videoBase":10}],12:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** @module video */ /** * Класс inread (out-stream) видео информера */ var VideoInread = function () { /** * Конструктор класса * @param {_mgLib4} widget - библиотека информеров */ function VideoInread(widget) { var _this = this; _classCallCheck(this, VideoInread); var config = widget.mgRec.config; this.widget = widget; this.jwplatformLoaded = false; this.jwplatformUrl = config.jwplatformUrl || widget.libConfig.jwPlayerIdInread; this.velocityUrl = config.velocityUrl || '//cdn.mgid.com/js/velocity.min.js'; this.velocityLoaded = false; this.jwPlayerStatus = 'none'; this.helpers = widget.modules.Helpers; /** @type {VideoAds} */ this.videoAds = widget.videoAds; this.mgVideoIndex = widget.mgRec.cid + '_' + widget.getWidgets().length; widget.debug('mgVideoIndex: ' + this.mgVideoIndex); this.addLibraries(); var WidgetCapping = widget.modules.WidgetCapping; this.widgetCapping = new WidgetCapping(widget, function () { _this.renderWidget(); }); this.widgetCapping.cappingTimes = config.capping || this.widgetCapping.cappingTimes; this.widgetCapping.cappingInterval = config.cappingInterval || this.widgetCapping.cappingInterval; } /** * Создаёт экземпляр класса Video * @param {_mgLib4} widget - библиотека информеров */ _createClass(VideoInread, [{ key: 'renderWidget', /** * Прорисовывает информер в скрытом виде и инициализирует jwplayer */ value: function renderWidget() { var _this2 = this; if (this.jwplatformLoaded && this.velocityLoaded) { this.widget.debug('Video renderWidget'); this.widget.block.className += ' mgVideoContainer_' + this.widget.mgRec.cid; this.addTemplate(); this.initPlayer(); } else { setTimeout(function () { _this2.renderWidget(); }, 500); } } /** * Подгружает библиотеки jwplayer и velocity */ }, { key: 'addLibraries', value: function addLibraries() { var _this3 = this; var jwplatformLib = document.getElementById('mgJwplatform'); if (!jwplatformLib) { jwplatformLib = document.createElement('script'); jwplatformLib.id = 'mgJwplatform'; jwplatformLib.src = this.jwplatformUrl; jwplatformLib.onload = function () { jwplatformLib.setAttribute('data-loaded', true); }; document.head.appendChild(jwplatformLib); } else if (jwplatformLib.getAttribute('data-loaded')) { this.jwplatformLoaded = true; } var velocityLib = document.getElementById('mgVelocity'); if (!velocityLib) { velocityLib = document.createElement('script'); velocityLib.id = 'mgVelocity'; velocityLib.src = this.velocityUrl; velocityLib.onload = function () { velocityLib.setAttribute('data-loaded', true); }; document.head.appendChild(velocityLib); } else if (velocityLib.getAttribute('data-loaded')) { this.velocityLoaded = true; this.Velocity = typeof Velocity === 'undefined' ? typeof $ === 'undefined' ? typeof jQuery === 'undefined' ? null : jQuery.Velocity : $.Velocity : Velocity; } if (!this.jwplatformLoaded || !this.velocityLoaded) { setTimeout(function () { _this3.addLibraries(); }, 500); } } /** * Добавляет html элементы логитипа, плеера и ссылки на рекламодателя */ }, { key: 'addTemplate', value: function addTemplate() { this.widget.block.innerHTML = this.widget.mgRec.template; var children = this.widget.block.children; this.addIndexes(children); var playerBlock = document.getElementById('mgJwPlayerBlock_' + this.mgVideoIndex); this.widget.mgRec.config.width = playerBlock.offsetWidth; this.widget.mgRec.config.height = playerBlock.offsetHeight; } /** * Добавляет индексы к ID элементов * @param children */ }, { key: 'addIndexes', value: function addIndexes(children) { if (children.length > 0) { for (var i = 0; i < children.length; i++) { if (children[i].getAttribute('id')) { children[i].setAttribute('id', children[i].getAttribute('id') + this.mgVideoIndex); } this.addIndexes(children[i].children); } } } /** * Проверка на поддержку флеша * @returns {boolean} */ }, { key: 'hasFlash', value: function hasFlash() { if (typeof this.flash !== 'boolean') { var a = 'Shockwave'; var b = 'Flash'; try { a = new ActiveXObject(a + b + '.' + a + b); } catch (e) { a = navigator.plugins[a + ' ' + b]; } this.flash = !!a; this.widget.debug('hasFlash: ' + (this.flash ? 1 : 0)); } return this.flash; } /** * Проверка на возможность использования флеша * @returns {boolean} */ }, { key: 'useFlash', value: function useFlash() { return this.hasFlash() && document.getElementById('mgJwPlayerBlock_' + this.mgVideoIndex).offsetWidth >= 462; } /** * Инициализация jwplayer и настройка обработчиков событий от него */ }, { key: 'initPlayer', value: function initPlayer() { var _this4 = this; this.widget.debug('Init player: ' + this.mgVideoIndex); var jwId = 'mgJwPlayer_' + this.mgVideoIndex; this.updateProgressBar(0); var mute = this.widget.mgRec.config.mute; if (mute && typeof mute !== 'string') { mute = true; } else if (typeof mute === 'string') { mute = !!parseInt(mute); } else { mute = false; } jwplayer(jwId).setup(this.helpers.mergeObjects({ autostart: false, repeat: false, mute: mute, aspectratio: '16:9', width: '100%', primary: this.useFlash() ? 'flash' : 'html5', advertising: this.videoAds.getAdsConfig(this.useFlash() ? 1 : 0), abouttext: 'Native Video by MGID', aboutlink: 'https://www.mgid.com/', playlist: [{ description: '', image: '//video-cdn.mgid.com/XHcEUCFl-720.jpg', pubdate: 'Mon, 30 May 2016 13:13:14 -0000', sources: [{ duration: 1, file: '//video-cdn.mgid.com/XHcEUCFl-26327326.mp4', height: 240, label: '180p', type: 'video/mp4', width: 320 }, { duration: 1, file: '//video-cdn.mgid.com/XHcEUCFl-26327327.mp4', height: 360, label: '270p', type: 'video/mp4', width: 480 }, { duration: 1, file: '//video-cdn.mgid.com/XHcEUCFl-26327331.m4a', height: -1, label: 'AAC Audio', type: 'audio/mp4', width: -1 }], tags: '', title: 'Ads', tracks: [{ file: '//video-cdn.mgid.com/XHcEUCFl-120.vtt', kind: 'thumbnails' }] }] }, this.widget.mgRec.config.jwsetup)); this.jwplayer = jwplayer(jwId); this.jwplayer.on('complete', function () { _this4.jwcomplete(); }); this.jwplayer.on('adSkipped', function () { _this4.jwcomplete(true); }); this.videoAds.addPlayerEvents({ jwplayer: this.jwplayer, bottomLinkId: 'mgVideoBottomLink_' + this.mgVideoIndex, bottomLinkFinishId: 'mgVideoBottomLinkFinish_' + this.mgVideoIndex, completeFunc: function completeFunc() { _this4.jwcomplete(!_this4.videoAds.videoBottomLinkFinish); }, pauseFunc: function pauseFunc() { _this4.setJwPlayerStatus('pause'); _this4.pausePlayer(); }, progressFunc: function progressFunc(position, duration) { _this4.updateProgressBar(position / duration); }, impressionFunc: function impressionFunc() { _this4.widgetCapping.sendAddCapping(); }, showPlayerFunc: function showPlayerFunc() { _this4.showPlayer(); _this4.setJwPlayerStatus('play'); } }); this.jwplayer.on('play', function () { if (!_this4.jwResolutionInited) { var qualityLevels = _this4.jwplayer.getQualityLevels(); if (qualityLevels !== null) { for (var i = 0; i < qualityLevels.length; i++) { if (qualityLevels[i].label === '720p') { _this4.jwplayer.setCurrentQuality(qualityLevels[i].index); break; } } } _this4.jwResolutionInited = true; } }); this.jwplayer.on('ready', function () { _this4.helpers.repaintSafari(_this4.jwplayer); setTimeout(function () { _this4.checkPlayer(); }, 1); }); this.jwplayer.on('error', function (e) { _this4.widget.debug('jwplayer error: ' + e.message); }); /** * Обработчик события scroll */ var scrollHandler = this.scrollHandler = function () { _this4.checkPlayer(); }; window.addEventListener('scroll', scrollHandler); if (mute) { var mouseOverHandler = this.mouseOverHandler = function () { if (_this4.jwplayer) _this4.jwplayer.setMute(false); }; var mouseOutHandler = this.mouseOutHandler = function () { if (_this4.jwplayer) _this4.jwplayer.setMute(true); }; this.widget.block.addEventListener('mouseover', mouseOverHandler); this.widget.block.addEventListener('mouseout', mouseOutHandler); } var closePlayerHandler = this.closePlayerHandler = function () { if (_this4.jwplayer) _this4.jwplayer.pause(true); _this4.jwcomplete(true); }; var closeButton = this.widget.block.querySelector('.mg-close-cross_' + this.widget.mgRec.cid); if (closeButton) { closeButton.addEventListener('click', closePlayerHandler); } } /** * Обновить статус времени в .mg-text-alt из содержимого .jw-text-alt */ }, { key: 'updateTimeStatus', value: function updateTimeStatus() { if (!this.statusElementJw) { this.statusElementJw = this.widget.block.querySelector('.jw-text-alt'); } if (!this.statusElementSkin) { this.statusElementSkin = this.widget.block.querySelector('.mg-text-alt'); } if (!this.statusElementJw || !this.statusElementSkin) { return; } this.statusElementSkin.innerText = this.statusElementJw.innerText; } /** * Сворачивание плеера по окончанию рекламного ролика * @param {boolean} instant */ }, { key: 'jwcomplete', value: function jwcomplete() { var _this5 = this; var instant = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (this.jwPlayerStatus === 'stop') return; this.widget.debug('jwcomplete'); this.setJwPlayerStatus('stop'); if (instant) { this.hidePlayer(); } else { var closeButton = this.widget.block.querySelector('.mg-close-cross_' + this.widget.mgRec.cid); if (closeButton) { closeButton.style.zIndex = 1001; } var cover = this.widget.block.querySelector('.mgCover_' + this.widget.mgRec.cid); if (cover) { this.helpers.removeClass(cover, 'mgHiddenBlock_' + this.widget.mgRec.cid); this.helpers.addClass(cover, 'mgVisibleBlock_' + this.widget.mgRec.cid); this.helpers.addClass(cover, 'mgBlackBG_' + this.widget.mgRec.cid); } var mgVideoBottomLink = document.getElementById('mgVideoBottomLink_' + this.mgVideoIndex); if (mgVideoBottomLink) { this.helpers.removeClass(mgVideoBottomLink, 'mgVisibleBlock_' + this.widget.mgRec.cid); this.helpers.addClass(mgVideoBottomLink, 'mgHiddenBlock_' + this.widget.mgRec.cid); } var mgVideoBottomLinkFinish = document.getElementById('mgVideoBottomLinkFinish_' + this.mgVideoIndex); if (mgVideoBottomLinkFinish) { this.helpers.removeClass(mgVideoBottomLinkFinish, 'mgHiddenBlock_' + this.widget.mgRec.cid); this.helpers.addClass(mgVideoBottomLinkFinish, 'mgVisibleBlock_' + this.widget.mgRec.cid); } setTimeout(function () { _this5.hidePlayer(); }, this.widget.mgRec.config.timeAfterEnd ? this.widget.mgRec.config.timeAfterEnd : 10000); } } }, { key: 'hidePlayer', value: function hidePlayer() { window.removeEventListener('scroll', this.scrollHandler); this.widget.block.removeEventListener('mouseover', this.mouseOverHandler); this.widget.block.removeEventListener('mouseout', this.mouseOutHandler); var mgVideo = this.widget.block; mgVideo.className = mgVideo.className.replace(/ mgVideoContainerActive_\d+/g, ''); this.Velocity(mgVideo, { height: 0 }, 1000); var closeButton = this.widget.block.querySelector('.mg-close-cross_' + this.widget.mgRec.cid); if (closeButton) { closeButton.removeEventListener('click', this.closePlayerHandler); } var mgVideoBottomLink = document.getElementById('mgVideoBottomLink_' + this.mgVideoIndex); if (mgVideoBottomLink && mgVideoBottomLink.querySelector('a')) { this.videoAds.cleanHandlers(); } } /** * Ставит плеер на паузу */ }, { key: 'pausePlayer', value: function pausePlayer() { var _this6 = this; this.widget.debug('Call pausePlayer'); var state = this.jwplayer.getState(); if (state !== 'paused') { this.widget.debug('State: ' + state + ' Send pause jwPlayerStatus: ' + this.jwPlayerStatus); this.jwplayer.pause(true); setTimeout(function () { _this6.pausePlayer(); }, 500); } else { this.widget.debug('Player paused'); if (this.jwPlayerStatus !== 'stop') { if (this.jwPlayerStatus === 'hide') { this.checkPlayer(); } else if (this.jwPlayerStatus === 'play') { this.startPlayer(); } } } } /** * Проверяет сосотяние плеера и попадение его в область видимости * При измнении состояния запускает или ставит на паузу видео */ }, { key: 'checkPlayer', value: function checkPlayer() { if (!this.jwplayerMarker) this.jwplayerMarker = document.getElementById('mgJwPlayer_' + this.mgVideoIndex); var mgVideo = this.widget.block; if (this.jwPlayerStatus === 'none') { this.jwplayerMarker.style.width = this.widget.mgRec.config.width; this.jwPlayerHeight = this.widget.block.offsetHeight; this.widget.debug('jwPlayerHeight: ' + this.jwPlayerHeight); this.widget.debug('jwPlayerWidth: ' + this.jwplayerMarker.offsetWidth); this.widget.debug('calc Height: ' + Math.floor(this.jwplayerMarker.offsetWidth * 9 / 16)); } if (this.isScrolledIntoView(mgVideo, 0.5)) { if (this.jwplayer.getState() === 'playing' && this.jwPlayerStatus !== 'play' && this.jwPlayerStatus !== 'stop') { this.setJwPlayerStatus('play'); } this.widget.debug('isScrolledIntoView: true Status: ' + this.jwPlayerStatus); if (['none', 'hide'].indexOf(this.jwPlayerStatus) >= 0) { this.setJwPlayerStatus('hiddenPlay'); this.widget.debug('checkPlayer: Change status to hiddenPlay.'); this.startPlayer(); this.showFromHide(); } else if (this.jwPlayerStatus === 'pause') { this.startPlayer(); this.setJwPlayerStatus('play'); } else if (this.jwplayer.getState() !== 'playing' && this.jwPlayerStatus === 'play') { this.startPlayer(); } } else if (this.isScrolledIntoView(mgVideo, 0.01) && ['none', 'hide'].indexOf(this.jwPlayerStatus) >= 0) { this.widget.debug('isScrolledIntoView: true (1%) Status: ' + this.jwPlayerStatus); this.setJwPlayerStatus('hiddenPlay'); this.startPlayer(); this.showFromHide(true); } else { if (this.jwplayer.getState() === 'paused') this.setJwPlayerStatus('pause'); this.widget.debug('isScrolledIntoView: false Status: ' + this.jwPlayerStatus); if (this.jwPlayerStatus === 'play' && this.showenJwPx / this.jwPlayerHeight < 0.5) { this.widget.debug('checkPlayer: Change status to pause.'); this.jwplayer.pause(true); this.setJwPlayerStatus('pause'); } else if (this.jwPlayerStatus === 'pause' && this.showenJwPx / this.jwPlayerHeight > 0.5) { this.setJwPlayerStatus('play'); this.startPlayer(); } else if (this.jwPlayerStatus === 'none') { this.setJwPlayerStatus('hide'); } } } /** * Раскрывает плеер, если видео было приостановлено после статуса hiddenPlay */ }, { key: 'showFromHide', value: function showFromHide() { var _this7 = this; var paused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var showFromHideInterval = function showFromHideInterval() { var currentStatus = _this7.jwplayer.getState(); _this7.widget.debug('showFromHide: ' + currentStatus); if (currentStatus === 'buffering') return; if (_this7.jwPlayerStatus === 'hiddenPlay' && ['playing', 'idle'].indexOf(_this7.jwplayer.getState() >= 0)) { _this7.showPlayer(); } if (paused && !_this7.isScrolledIntoView(_this7.widget.block, 0.5)) { _this7.setJwPlayerStatus('pause'); _this7.pausePlayer(); } _this7.checkPlayer(); clearInterval(interval); }; var interval = setInterval(showFromHideInterval, 50); showFromHideInterval(); } /** * Проверка на попадание элемента в область видимости * @param {HTMLElement} elem - Проверяемый элемент * @param {Number} showenPart - Если число < 1 и > 0, то провека будет успешной если в области видимости только * часть элемента равная showenPart * 100% * @returns {boolean} */ }, { key: 'isScrolledIntoView', value: function isScrolledIntoView(elem) { var showenPart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var docViewTop = window.pageYOffset || document.documentElement.scrollTop; var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; var docViewBottom = docViewTop + windowHeight; var elemTop = this.helpers.getOffsetTop(elem); var elemBottom = elemTop + this.jwPlayerHeight; if (elemTop < docViewTop && elemBottom > docViewTop) { this.showenJwPx = elemBottom - docViewTop; } else if (elemTop < docViewBottom && elemBottom > docViewBottom) { this.showenJwPx = docViewBottom - elemTop; } else if (elemBottom <= docViewBottom && elemTop >= docViewTop) { this.showenJwPx = this.jwPlayerHeight; } else { this.showenJwPx = 0; } return elemBottom - (1 - showenPart) * this.jwPlayerHeight <= docViewBottom && elemTop + (1 - showenPart) * this.jwPlayerHeight >= docViewTop; } /** * Запускает проигрывание видео */ }, { key: 'startPlayer', value: function startPlayer() { this.widget.debug('startPlayer: Send play.'); if (this.jwPlayerStatus === 'hiddenPlay') { this.widget.block.style.width = this.widget.mgRec.config.width + (this.widget.mgRec.config.width.toString().substr(-1, 1) === '%' ? '' : 'px'); if (this.helpers.isMobile()) { this.jwplayer.setMute(true); } } if (this.videoAds.mediaType === 'application/javascript') { if (this.jwplayer) this.jwplayer.seek(); } else { this.jwplayer.play(true); } } /** * Показывает плеер */ }, { key: 'showPlayer', value: function showPlayer() { var mgVideo = this.widget.block; mgVideo.className += ' mgVideoContainerActive_' + this.widget.mgRec.cid; mgVideo.style.width = this.widget.mgRec.config.width + (this.widget.mgRec.config.width.toString().substr(-1, 1) === '%' ? '' : 'px'); this.widget.debug('showPlayer: Width: ' + mgVideo.style.width); var cover = this.widget.block.querySelector('.mgCover_' + this.widget.mgRec.cid); if (cover) { this.helpers.removeClass(cover, 'mgVisibleBlock_' + this.widget.mgRec.cid); this.helpers.addClass(cover, 'mgHiddenBlock_' + this.widget.mgRec.cid); } this.jwPlayerHeight = this.widget.block.offsetHeight; } /** * Изменяет ширину progress bar'а времени рекламы * @param {number} progress */ }, { key: 'updateProgressBar', value: function updateProgressBar(progress) { if (!this.progressBar) { this.progressBar = this.widget.block.querySelector('.mg-progress-point_' + this.widget.mgRec.cid); } if (this.progressBar) { this.progressBar.style.width = 100 * progress + '%'; } } /** * Установить новый статус jwPlayer * @param jwPlayerStatus */ }, { key: 'setJwPlayerStatus', value: function setJwPlayerStatus(jwPlayerStatus) { this.jwPlayerStatus = jwPlayerStatus; this.videoAds.jwPlayerStatus = jwPlayerStatus; } }], [{ key: 'init', value: function init(widget) { if (widget.mgRec.config.wages_types.indexOf('video') !== -1) { widget.videoInread = new VideoInread(widget); } } }]); return VideoInread; }(); exports.VideoInread = VideoInread; },{}],13:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.VRW = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _videoBase = require('./videoBase'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** @module VRW (Video Recommendation Widget) */ var VRW = function (_VideoBase) { _inherits(VRW, _VideoBase); /** * Конструктор класса * @param {_mgLib4} widget - библиотека информеров */ function VRW(widget) { _classCallCheck(this, VRW); var _this = _possibleConstructorReturn(this, (VRW.__proto__ || Object.getPrototypeOf(VRW)).call(this, widget)); _this.jwplatformUrl = widget.mgRec.config.jwplatformUrl || widget.libConfig.jwPlayerIdVrw; _this.firstVideoPlayed = false; _this.popupPlayerInitialized = false; _this.slickElemSelector = '.video-info__footer_' + _this.widget.mgRec.cid + ' .mgbox'; _this.jwPlaylist = []; _this.linkElems = []; _this.showedLinkElems = []; _this.addLibraries(); return _this; } /** * Создаёт экземпляр класса VRW * @param {_mgLib4} widget - библиотека информеров */ _createClass(VRW, [{ key: 'addTemplate', /** * Добавляет html элементы плеера */ value: function addTemplate() { if (this.widget.mgRec.template) { this.widget.block.innerHTML = this.widget.mgRec.template; } var children = this.widget.block.children; this.addIndexes(children); this.popupVRW = document.getElementById('vrPopup_' + this.mgVideoIndex); if (this.popupVRW) { var popupFooter = this.popupVRW.querySelector('.video-info__footer_' + this.widget.mgRec.cid); if (popupFooter) { if (this.widget.mgRec.vr_playlist) { this.playlist = this.widget.mgRec.vr_playlist; var sidebarDesign = this.popupVRW.querySelector('.video-info__centering_' + this.widget.mgRec.cid); var playlistWraper = document.createElement('div'); playlistWraper.className = 'mgbox-pop'; if (sidebarDesign) { playlistWraper = popupFooter; } for (var i = 0; i < this.playlist.length; i++) { var curPlaylistElem = this.playlist[i]; var videoExt = null; if (curPlaylistElem.videoExt) { try { videoExt = JSON.parse(atob(curPlaylistElem.videoExt)); } catch (ex) { this.widget.debug(ex.message); } } var hrefValue = 'javascript:void({\'id\':\'' + curPlaylistElem.id + '\',' + ('\'link\':\'' + curPlaylistElem.link + '\',\'hash\':\'' + curPlaylistElem.hash + '\''); if (curPlaylistElem.videoExt) { hrefValue += ',\'videoExt\':\'' + curPlaylistElem.videoExt + '\''; } var teaser = this.widget.block.querySelector('.mcimg>a[href*="' + hrefValue + '"]'); if (teaser) { hrefValue = teaser.href; } else { hrefValue += '})'; } var elementWrap = document.createElement('div'); elementWrap.className = 'mgline-pop'; elementWrap.innerHTML = ''; if (sidebarDesign) { elementWrap = document.createElement('a'); elementWrap.className = 'mgline-pop'; elementWrap.href = hrefValue; elementWrap.innerHTML = '
' + ('
' + curPlaylistElem.title + '') + '
Now playing
' + '
HD
' + '
' + ('
' + curPlaylistElem.title + '
'); } if (videoExt) { this.fillAdditional(elementWrap, videoExt); } playlistWraper.appendChild(elementWrap); this.linkElems.push({ item: elementWrap, teaserId: curPlaylistElem.id, link: curPlaylistElem.link, hash: curPlaylistElem.hash, videoExt: videoExt, showed: false }); } if (!sidebarDesign) { popupFooter.appendChild(playlistWraper); } } else { var box = document.createElement('div'); box.className = 'mgbox-pop'; popupFooter.appendChild(box); var teasers = this.widget.block.querySelectorAll('.mgline'); for (var _i = 0; _i < teasers.length; _i++) { var imgLinkElem = teasers[_i].querySelector('.mcimg>a'); if (imgLinkElem) { var href = imgLinkElem.getAttribute('href'); if (href.indexOf('({') >= 0 || href.indexOf('})') >= 0) { var clone = teasers[_i].cloneNode(true); clone.removeAttribute('style'); this.helpers.removeClass(clone, 'mgline'); this.helpers.addClass(clone, 'mgline-pop'); clone.innerHTML = clone.innerHTML.replace(/mcimg/g, 'mcimg-pop'); clone.innerHTML = clone.innerHTML.replace(/image-with-text/g, 'image-with-text-pop'); clone.innerHTML = clone.innerHTML.replace(/image-container/g, 'image-container-pop'); clone.innerHTML = clone.innerHTML.replace(/mctitle/g, 'mctitle-pop'); var resizeSensor = clone.querySelector('.resize-sensor'); if (resizeSensor) { resizeSensor.parentNode.removeChild(resizeSensor); } box.appendChild(clone); } } } } } this.slickElemSelector = '.video-info__footer_' + this.widget.mgRec.cid + ' .mgbox-pop'; } this.addCustomScripts(); this.addListeners(); this.addPreview(); } /** * Добавляет preview в тизер */ }, { key: 'addPreview', value: function addPreview() { for (var i = 0; i < this.linkElems.length; i++) { var sameLinks = this.widget.block.querySelectorAll('a[href*="javascript:void({\'id\':\'' + this.linkElems[i].teaserId + '\'"] .image-container'); for (var j = 0; j < sameLinks.length; j++) { if (this.linkElems[i].videoExt && this.linkElems[i].videoExt.preview) { var parentElem = this.helpers.getParentTeaserBlock(sameLinks[j], 'mgline'); if (parentElem) { var videoDiv = document.createElement('div'); videoDiv.setAttribute('style', 'position:absolute;top:0;width:100%;height:100%;'); videoDiv.innerHTML = '