/* Minification failed. Returning unminified contents.
(538,31): run-time error JS1004: Expected ';'
(748,49-51): run-time error JS1008: Expected '{': =>
(762,41-42): run-time error JS1009: Expected '}': [
(762,49-50): run-time error JS1006: Expected ')': :
(762,49): run-time error JS1004: Expected ';'
(762,65-66): run-time error JS1195: Expected expression: )
(625,9-11): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: tp
 */
$(function () {

    // Hide Header on on scroll down
    var didScroll;
    var lastScrollTop = 0;
    var delta = 5;
    var navbarHeight = $('header').outerHeight();

    $(window).scroll(function (event) {
        didScroll = true;
    });

    setInterval(function () {
        if (didScroll) {
            hasScrolled();
            didScroll = false;
        }
    }, 250);

    function hasScrolled() {
        var st = $(this).scrollTop();

        // Make sure they scroll more than delta
        if (Math.abs(lastScrollTop - st) <= delta)
            return;

        // If they scrolled down and are past the navbar, add class .nav-up.
        // This is necessary so you never see what is "behind" the navbar.
        if (st > lastScrollTop && st > navbarHeight) {
            // Scroll Down
            $('header').removeClass('is-nav-primary-down').addClass('is-nav-primary-up');
        } else {
            // Scroll Up
            if (st + $(window).height() < $(document).height()) {
                $('header').removeClass('is-nav-primary-up').addClass('is-nav-primary-down');
            }
        }

        lastScrollTop = st;
    }
});;
//'use strict';

class ApplicationStart {
    //  a default constructor
    constructor() {
    }

    Init() {
        this.ApplicationStart();
        this.Channels();
        this.HeaderTop();
        this.Piano();
        this.TaboolaInitLoad();
    }
    TaboolaInitLoad() {
        console.log('Taboola Init Load.');
        let currentElements = document.querySelectorAll('[data-section]');
        currentElements.forEach((x) => {
            switch (x.dataset.section.toLowerCase()) {
                case 'top news':
                    x.dataset.tbRegion = 'Top News';
                    break;
                case 'ad':
                    x.dataset.tbRegion = 'Ad';
                    break;
                case 'shook':
                    x.dataset.tbRegion = 'Shook';
                    break;
                case 'local':
                    x.dataset.tbRegion = 'Local';
                    break;
                case 'world':
                    x.dataset.tbRegion = 'World';
                    break;
                case 'tech':
                    x.dataset.tbRegion = 'Calcalist-Tech';
                    break;
                case 'nadlan':
                    x.dataset.tbRegion = 'Nadlan';
                    break;
                case 'law and taxes':
                    x.dataset.tbRegion = 'law and taxes';
                    break;
                case 'money':
                    x.dataset.tbRegion = 'Money';
                    break;
                case 'motor':
                    x.dataset.tbRegion = 'Motor';
                    break;
                case 'sport':
                    x.dataset.tbRegion = 'Sports business';
                    break;
                case 'opinions':
                    x.dataset.tbRegion = 'Opinions';
                    break;
                case 'pnay':
                    x.dataset.tbRegion = 'Pnay';
                    break;
                case 'podcast':
                    x.dataset.tbRegion = 'Podcast';
                    break;
                default:
                    x.dataset.tbRegion = 'undefined';
                    break;
            }
        });
    }
    Piano() {
        tp.push(["setUsePianoIdUserProvider", true]);
        tp.push(["setAid", pianoenvSandbox ? pianoSandboxId : pianoProductionId]);
        tp.push(["setSandbox", pianoenvSandbox]);
        //tp.push(["setUseTinypassAccounts", false]);
        tp.push(["setZone", "Web"]);

        const getdcPathTags = (input) => {
            return input.split("-").reduce((arr, v) => ([...arr, arr.length ? `${arr[arr.length - 1]}-${v}` : v]), []);
        }
        let dcPathTags = getdcPathTags(dcPath.dcPath);
        tp.push(["setTags", dcPathTags]);
        // Execute when the page is first loaded
        tp.push(["init", function () {
            tp.experience.init();
        }]);
        (function (src) {
            var a = document.createElement("script");
            a.type = "text/javascript";
            a.async = true;
            a.src = src;
            var b = document.getElementsByTagName("script")[0];
            b.parentNode.insertBefore(a, b)
        })(pianoenvSandbox ? "https://sandbox.tinypass.com/api/tinypass.min.js" : "//cdn.piano.io/api/tinypass.min.js");

    }
    ApplicationStart() {
        /*
     * Replace all SVG images with inline SVG
        https://gist.github.com/arturparkhisenko/7a084e604d40bb9e5f45
     */
        $('img.svg').each(function () {
            var $img = jQuery(this);
            var imgID = $img.attr('id');
            var imgClass = $img.attr('class');
            var imgURL = $img.attr('src');
            var imgFillColor = $img.data('fill');

            jQuery.get(imgURL, function (data) {
                // Get the SVG tag, ignore the rest
                var $svg = jQuery(data).find('svg');

                // Add replaced image's ID to the new SVG
                if (typeof imgID !== 'undefined') {
                    $svg = $svg.attr('id', imgID);
                }
                // Add replaced image's classes to the new SVG
                if (typeof imgClass !== 'undefined') {
                    $svg = $svg.attr('class', imgClass + ' replaced-svg');
                    $svg.find('path').attr('fill', imgFillColor);
                }

                // Remove any invalid XML tags as per http://validator.w3.org
                $svg = $svg.removeAttr('xmlns:a');

                // Replace image with new SVG
                $img.replaceWith($svg);

            }, 'xml');

        });
        document.addEventListener('userway:render_completed', () => {
            UserWay.iconVisibilityOff();
        });
        document.querySelector('#c-menu__accessibility').addEventListener('click', () => {
            UserWay.widgetToggle();
        });
        document.addEventListener('lazybeforeunveil', function (e) {
            var element = e.target.getAttribute('data-link');

            if (element !== null && typeof element !== 'undefined') {
                if (element.indexOf('flowplayer') > -1) {
                    $('.s-video-content').css({ visibility: 'visible' });
                }

                if (element.indexOf('swiper') > -1) {
                    $('.s-photo-content').css({ visibility: 'visible' });
                    $('.s-hotarticle-content').css({ visibility: 'visible' });
                }
            }
        });
    }
    loadLink(url) {
        var link = document.createElement("link");
        link.rel = "text/css";
        link.rel = "stylesheet";
        link.href = url;

        if (link.readyState) {
            link.onreadystatechange = function () {
                if (link.readyState === "loaded" ||
                    link.readyState === "complete") {
                    link.onreadystatechange = null;

                }
            };
        } else {
            link.onload = function () {

            };
        }

        link.src = url;
        document.getElementsByTagName("head")[0].appendChild(link);
    }
    Independenceday() {

        //year, month-1, day, h,m,s
        const HolidaysConfig = [
            {
                'mindate': new Date(2023, 3, 5, 12, 0, 0),
                'maxdate': new Date(2023, 3, 12, 18, 0, 0),
                'className': 'PassoverFlag',
            },
            {
                'mindate': new Date(2022, 9, 4, 7, 0, 0),
                'maxdate': new Date(2022, 9, 5, 19, 0, 0),
                'className': 'KippurFlag',
            },
            {
                'mindate': new Date(2023, 8, 15, 10, 0, 0),
                'maxdate': new Date(2023, 8, 17, 18, 0, 0),
                'className': 'ShanaTovaFlag',
            },
            {
                'mindate': new Date(2023, 3, 25, 16, 0, 0),
                'maxdate': new Date(2023, 3, 25, 19, 0, 0),
                'className': 'IndependenceFlag',
            },
            {
                'mindate': new Date(2021, 8, 6, 10, 0, 0),
                'maxdate': new Date(2021, 8, 8, 19, 30, 0),
                'className': 'HappynewyearFlag',
            },
            {
                'mindate': new Date(2021, 8, 20, 10, 0, 0),
                'maxdate': new Date(2021, 8, 28, 19, 0, 0),
                'className': 'HappyholidyFlag',
            },
            {
                'mindate': new Date(2020, 8, 27, 12, 0, 0),
                'maxdate': new Date(2020, 8, 28, 20, 0, 0),
                'className': 'SignatureFlag',
            },
            {
                'mindate': new Date(2023, 8, 29, 9, 0, 0),
                'maxdate': new Date(2023, 9, 7, 18, 0, 0),
                'className': 'SokutFlag',
            }];

        let currentDatetime = new Date();
        let Isflag = HolidaysConfig.filter((item) =>
            currentDatetime >= item.mindate && currentDatetime <= item.maxdate
        ).slice(0)[0];

        if (typeof (Isflag) !== 'undefined' && dcPath.Type === 'Home') {
            document.getElementsByTagName('header')[0].classList.add(Isflag.className);
            this.loadLink(baseUrl + 'Content/styles/layout/_flag.css');
        }

    }
    Channels() {
        let getUrl = new URL(window.location.href);
        let gId = Number(getUrl.searchParams.get("guid"));
        let widgetId;
        if (gId === 5768) {
            document.querySelectorAll('.c-article__pubdate').forEach(x => { x.style.visibility = 'hidden' });
        }
        if ((gId === 3) && getUrl.pathname.toString().toLowerCase().indexOf('chanel.aspx') > -1) {
            if (gId === 3) {
                widgetId = '36a3dbd0-9e63-11e9-9c9d-3b8dbe1e6892';
            }
        }
        if (gId === 5783) {
            this.loadLink(baseUrl + 'Content/styles/layout/_dark.css');
        }
    }
    HeaderTop() {
        let x = document.querySelectorAll('.c-article__stamp, .StampaTitle');
        x.forEach(x => {
            if (x.classList.contains('c-article__stamp')) {
                if (x.querySelector('span').textContent === 'כלכליסט-טק') {
                    x.style.backgroundColor = '#10bbef';
                }
            }
        });
    }
}

//  Initialization
$(function () {
    let applicationStart = new ApplicationStart();
    applicationStart.Init();
    applicationStart.Independenceday();
});;
//'use strict';

class Share {
    //  a default constructor
    constructor(event, itemtype, title, image, base, articleId) {

        this.event = event;
        this.itemtype = itemtype;
        this.title = title;
        this.image = image;
        this.base = base;
        this.articleId = articleId;
    }

    Init(target) {
        this.shareItem(target);
    }

    urlParse(str, token) {
        for (let t in token) {
            str = str.replace(new RegExp('\\$\\{' + t + '\\}', 'g'), encodeURIComponent(token[t]));
        }
        return str;
    }

    openShare(sharer, url, title, text) {

        const pageInfo = {
            url: url,
            title: title,
            text: text
        };

        // social media link
        let popup, newUrl = this.urlParse(sharer, pageInfo);

        // open popup
        if (sharer.startsWith('http')) {

            let
                sw = screen.availWidth || 1024,
                sh = screen.availHeight || 700,
                pw = Math.min(600, (sw - 40)),
                ph = Math.min(600, (sh - 40)),
                px = Math.floor((sw - pw) / 2),
                py = Math.floor((sh - ph) / 2);

            popup = window.open(
                newUrl,
                'social',
                `width=${pw},height=${ph},left=${px},top=${py},\
          location=0,menubar=0,toolbar=0,personalbar=0,status=0,scrollbars=1,resizable=1`
            );
        }

        if (popup) popup.focus();
        else location.href = newUrl;
    }

    shareItem(target) {
        var self = this;
        let $c_article__share = !target ?
            $('.c-article .c-article__share, .c-article__share.is-closed') : $(target);

        $c_article__share.on('click', function (e) {

            e.preventDefault();

            let $c_article = $(this).parents('.c-article');
            let $c_article__share = typeof target !== 'undefined' ? $(target).find('.c-article__share') : $(this);
            let appendShareContent =
                `<div data-sharetype="mail"><img src="${$c_article__share.data('base')}Content/resources/images/icons/mail_share_icon.svg" title="שיתוף במייל" alt="שיתוף במייל" /></div>
                 <div data-sharetype="facebook"><img src="${$c_article__share.data('base')}Content/resources/images/icons/facebook_share_icon.svg" title="שיתוף בפייסבוק" alt="שיתוף בפייסבוק" /></div>
                 <div data-sharetype="whatsapp"><img src="${$c_article__share.data('base')}Content/resources/images/icons/whatsapp_share_icon.svg" title="שיתוף בוואטסאפ" alt="שיתוף בוואטסאפ" /></div>
                 <div data-sharetype="twitter"><img src="${$c_article__share.data('base')}Content/resources/images/icons/twitter_share_icon.svg" title="שיתוף בטוויטר" alt="שיתוף בטוויטר" /></div>`;

            let $c_article__share_elements = $c_article.find('.c-article__share-elements');

            let currentlyOpened = $c_article__share.hasClass('is-close-button');
            currentlyOpened ? $c_article__share.removeClass('is-close-button') : $c_article__share.addClass('is-close-button');

            let currentlyShown = $c_article__share_elements.hasClass('is-hidden');
            currentlyShown ? $c_article__share_elements.removeClass('is-hidden') : $c_article__share_elements.addClass('is-hidden');

            currentlyOpened ? $c_article__share_elements.html('') : $(appendShareContent).appendTo($c_article__share_elements);

            $c_article__share_elements.on('click', 'div[data-sharetype]', { articleSharedItem: $c_article__share }, function (e) {

                e.preventDefault();

                let articleSharedItem = e.data.articleSharedItem;
                let shareType = $(this).data('sharetype');

                this.itemtype = articleSharedItem.data('itemtype');
                this.title = articleSharedItem.data('title');
                this.image = articleSharedItem.data('image');
                this.base = "https://m.calcalist.co.il/";
                this.articleId = articleSharedItem.data('articleid');

                let sharedTemplateUrl;
                let sharedTemplateTitle = this.title;
                let sharedTemplateBase = this.base;
                let sharedTemplateLink = `Article.aspx?guid=${this.articleId}`;
                let sharedUtm = `&utm_source=${sharedTemplateBase.split('/')[2]}&utm_medium=Share&utm_term=${this.articleId}&utm_campaign=#campaign#`;
                let dataLayerLabel;
                let sharer;

                switch (shareType) {
                    //http://www.sharelinkgenerator.com/
                    case 'mail':
                        sharedUtm = sharedUtm.replace('#campaign#', 'email');
                        sharedTemplateUrl = `mailto:?subject=${sharedTemplateTitle}&body=${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}`;
                        dataLayerLabel = 'Email';
                        sharer = "mailto:?subject=${title}&body=${url}";
                        break;

                    case 'facebook':
                        sharedUtm = sharedUtm.replace('#campaign#', 'facebook');
                        sharedTemplateUrl = `https://m.facebook.com/sharer.php?u=${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}`;
                        dataLayerLabel = 'Facebook';
                        sharer = "https://www.facebook.com/sharer/sharer.php?u=${url}";
                        break;

                    case 'whatsapp':
                        sharedUtm = sharedUtm.replace('#campaign#', 'whatsapp');
                        //sharedTemplateUrl = `whatsapp://send?text=${sharedTemplateTitle}${String.fromCharCode(58, 32)}${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}`;
                        sharedTemplateUrl = `https://api.whatsapp.com/send?text=${sharedTemplateTitle}${String.fromCharCode(13)} ${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}`;
                        dataLayerLabel = 'WhatsApp';
                        sharer = "https://api.whatsapp.com/send?text=${title} ${url}";
                        break;

                    case 'twitter':
                        sharedUtm = sharedUtm.replace('#campaign#', 'twitter');
                        sharedTemplateUrl = `https://twitter.com/share?url=${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}&text=${sharedTemplateTitle}`;
                        dataLayerLabel = 'Twitter';
                        sharer = "https://twitter.com/intent/tweet?url=${url}&amp;text=${title}";
                        break;

                    case 'linkedin':
                        sharedUtm = sharedUtm.replace('#campaign#', 'linkedin');
                        sharedTemplateUrl = `https://www.linkedin.com/shareArticle?mini=true&url=${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}&title=${sharedTemplateTitle}&summary=${sharedTemplateTitle}`;
                        dataLayerLabel = 'Linkedin';
                        sharer = "https://www.linkedin.com/shareArticle?mini=true&url=${url}&amp;title=${title}";
                        break;

                    default:
                        break;
                }
                dataLayer.push({ 'event': 'share_events', 'Category': 'Share', 'Action': 'Article Main Image', 'Label': `${dataLayerLabel}` });
                sharedTemplateUrl = `${sharedTemplateBase}${sharedTemplateLink}${sharedUtm}`;
                self.openShare(sharer, sharedTemplateUrl, this.title, '');
            });
        });
    }
}

//  Initialization
$(function () {
    let share = new Share();
    share.Init();
});
;
class AnalyticsLoadState {
    constructor() {
        //this.player = document.getElementById('music');
    }
    Init() {
        this.BindEvents();
        this.Taboola();
    }
    BindEvents() {
        console.log('analytics loaded.');
        document.querySelectorAll('.c-menu__action, .c-menu__catogory')
            .forEach(item => {
                item.addEventListener('click', event => {
                    let getAction = event.target.closest('div').className === "c-menu__action" ? 'Left Side Menu' : 'Side Menu';
                    dataLayer.push({ 'event': 'GA_Event', 'Category': 'Navigation', 'Action': getAction, 'Label': event.target.closest('div').querySelector('a').title });
                });
            });
    }
    Taboola() {
        setTimeout(function () {
            let options = {};
            let firstTime = true;
            let observer = new IntersectionObserver(
                function handleTaboola(entries, observer) {
                    entries.forEach(function (entry) {
                        if (entry.isIntersecting && firstTime) {
                            firstTime = false;
                            dataLayer.push({
                                'event': 'GA_Event',
                                'taboolaFeedDisplay': '1',
                                'Category': 'Taboola',
                                'Action': 'Endless Feed',
                                'Label': 'Feed Displayed'
                            });
                            function pushVideo() {
                                let video_container = document.querySelector('._cm-video-ad._cm-ad-feed-manager');
                                if (video_container) {
                                    dataLayer.push({
                                        'event': 'GA_Event',
                                        'taboolaFeedDisplay': '1',
                                        'Category': 'Taboola',
                                        'Action': 'Endless Feed',
                                        'Label': 'Video Displayed'
                                    });
                                }
                            }
                            setTimeout(pushVideo, 1000);
                        }
                    });
                }, options);
            let taboolaElementCategory = document.querySelector("#taboola-mobile-below-main-column-thumbnails");
            let taboolaElementCategorydark = document.querySelector("#taboola-mobile-below-main-column-thumbnails-dark");
            let taboolaElementArticle = document.querySelector("#taboola-mobile-below-article-thumbnails");
            if (taboolaElementCategory) {
                observer.observe(taboolaElementCategory);
            } else if (taboolaElementCategorydark) {
                observer.observe(taboolaElementCategorydark);
            } else if (taboolaElementArticle) {
                observer.observe(taboolaElementArticle);
            }
        }, 1000);
    }
}
window.addEventListener('DOMContentLoaded', (event) => {
    let analytics = new AnalyticsLoadState();
    analytics.Init();
});;
class Login {
    constructor() {
        this.loggedInStatus = 'Guest User';
    }
    static async postData(url = '', data = {}) {
        const response = await fetch(url, {
            method: 'post',
            mode: 'cors',
            cache: 'no-cache',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json'
            },
            redirect: 'follow',
            referrerPolicy: 'no-referrer',
            body: JSON.stringify(data)
        });
        return response.text();
    }
    Analytics() {
        let purchaseButton = document.querySelector('#uxPurchaseButton');
        purchaseButton !== null ?
            purchaseButton.addEventListener('click', event => {
                dataLayer.push({
                    'event': 'GA_Events', 'Category': 'CalcalistPro - UserMenu', 'Action': this.loggedInStatus, 'Label': 'Purchase subscription'
                });
            }) : null;
        let newsletterButton = document.querySelector('#uxNewsletterButton');
        newsletterButton !== null ?
            newsletterButton.addEventListener('click', event => {
                dataLayer.push({
                    'event': 'GA_Events', 'Category': 'CalcalistPro - UserMenu', 'Action': this.loggedInStatus, 'Label': 'Newsletter'
                });
            }) : null;
        let contactButton = document.querySelector('#uxContactusButton');
        contactButton !== null ?
            contactButton.addEventListener('click', event => {
                dataLayer.push({
                    'event': 'GA_Events', 'Category': 'CalcalistPro - UserMenu', 'Action': this.loggedInStatus, 'Label': 'Contact'
                });
            }) : null;
    }
    Init() {
        this.loadLoginMenubyState();
    }
    loadEvents(isUserValid) {
        const self = this;
        let closeButton = document.querySelector('#uxCloseMenuButton');
        closeButton.addEventListener('click', (e) => {
            if (e.target.id === 'uxCloseMenuButton')
                document.getElementById("c-button-login-collapse").checked = false;
        });
        let loginButton = document.querySelector('#uxLoginButton');
        !isUserValid ? loginButton.addEventListener('click', (e) => {
            setTimeout(() => {
                this.Login();
                document.getElementById("c-button-login-collapse").checked = false;
            }, 500);
        }) : null;
        let logoutButton = document.querySelector('#uxLogoutButton');
        isUserValid ? logoutButton.addEventListener('click', (e) => {
            document.getElementById("c-button-login-collapse").checked = false;
            setTimeout(() => {
                dataLayer.push({
                    'event': 'Login_Events', 'Category': 'CalcalistPro - Logout', 'Action': 'CalcalistPro User icon', 'Label': 'Logout Successfully'
                });
                tp.pianoId.logout(() => {
                    console.log('User has logged out, reloading current window.');
                    window.location.reload();
                });
                //document.querySelector('.c-loginlayout').remove();
                //self.Init();
            }, 500);
        }) : null;

        let manageProfileButton = document.querySelector('#uxManageProfileButton');
        isUserValid ? manageProfileButton.addEventListener('click', (e) => {
            //window.location.href = baseUrl + 'MyAccount.aspx';
            if (isUserValid) {
                dataLayer.push({
                    'event': 'GA_Events', 'Category': 'CalcalistPro - UserMenu', 'Action': self.loggedInStatus, 'Label': 'Account management'
                });
                window.location.href = baseUrl + 'MyAccount.aspx';
            } else {
                window.loginCalcalist.Login();
            }
        }) : null;

    }
    loadLoginMenubyState() {
        let self = this;
        Analytics.userType = self.loggedInStatus;
        tp = window["tp"] || [];
        tp.push(["init", function () {
            let isUserValid = tp.pianoId.isUserValid();
            Login.postData(`${baseUrl}Login.aspx`, { IsLoggedIn: isUserValid })
                .then(data => {
                    const temporary = document.createElement('div');
                    temporary.innerHTML = data.trim();
                    document.querySelector('.c-container').append(temporary.querySelector('.c-loginlayout'));
                    setTimeout(() => {
                        self.loadEvents(isUserValid);
                        if (isUserValid) {
                            document.querySelector('.c-button-login-collapse img').src = `${baseUrl}Content/resources/images/login/userLoggedIcon.svg`;
                            document.querySelector('.c-loginMenu__item.--userProfile a strong').innerHTML = `${tp.pianoId.getUser().firstName.substring(0, 15)}`;
                            tp.api.callApi("/access/list", () => { }, (r) => {
                                if (r.total > 0) {
                                    document.querySelector('.c-loginlayout.--loggedin').classList.contains('--no-resources') ? document.querySelector('.c-loginlayout.--loggedin').classList.remove('--no-resources') : null;
                                    document.querySelector('.c-loginlayout.--loggedin').classList.add('--has-resources');
                                    document.querySelector('.c-loginMenu__item.--purchase').remove();
                                    self.loggedInStatus = 'Logged user with subscription';
                                    Analytics.userType = self.loggedInStatus;
                                }
                                else {
                                    document.querySelector('.c-loginlayout.--loggedin').classList.add('--no-resources');
                                    self.loggedInStatus = 'Logged user without subscription';
                                    Analytics.userType = self.loggedInStatus;
                                }
                            });
                        }
                        else {
                            document.querySelector('.c-button-login-collapse img').src = `${baseUrl}Content/resources/images/login/userLoginIcon.svg`;
                        }
                        document.querySelector('.c-button-login-collapse').classList.remove('--hide');
                        self.Analytics();
                    }, 500);

                });

        }]);
    }
    Login() {
        const self = this;
        //let loginMenu = document.querySelector('.c-loginlayout');
        //let loginMenu = document.getElementById('cLoginlayout');
        //tp = window.tp || [];
        tp.push(["init", function () {
            tp.pianoId.show({
                screen: 'login',
                loggedIn: function (data) {
                    console.log('user ', data.user, ' logged in with token', data.token);
                    document.getElementById('cLoginlayout').replaceWith(document.getElementById('cLoginlayout').cloneNode(true));
                    document.getElementById('cLoginlayout').remove();
                    self.Init();
                    dataLayer.push({ 'event': 'Login_Events', 'Category': 'CalcalistPro - Login', 'Action': 'Login Source', 'Label': 'CalcalistPro User icon' });
                },
                loggedOut: function () {
                    dataLayer.push({
                        'event': 'Login_Events', 'Category': 'CalcalistPro - Logout', 'Action': 'CalcalistPro User icon', 'Label': 'Logout Successfully'
                    });
                    console.log('user logged out');
                    document.getElementById('cLoginlayout').replaceWith(document.getElementById('cLoginlayout').cloneNode(true));
                    document.getElementById('cLoginlayout').remove();
                    window.location.reload();
                    //self.Init();
                }
            });
        }]);
    }
    loginDisplayed() {
        document.querySelector('.tp-iframe-wrapper.tp-active.piano-id-modal-ver-.piano-id-modal-ver-2 button').style = 'filter:invert(1);border:none;right:10px;top:-5px;opacity:1;';
    }
    Register() {
        tp.push(["init", function () {
            tp.pianoId.show({
                screen: 'register',
                loggedIn: function (data) {
                    console.log('user ', data.user, ' logged in with token', data.token);
                },
                loggedOut: function () {
                    console.log('user logged out');
                }
            });
        }]);
    }
}
$(function () {
    let login = new Login();
    window.loginCalcalist = login;
    login.Init();
});;
class CookieHelper {
    //  a default constructor
    constructor() {
    }

    //  short-hand method Stock
    CreateCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
            var expires = "; expires=" + date.toGMTString();
        }
        else expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    ReadCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    //EraseCookie(name) {
    //    CookieHelper.CreateCookie(name, "", -1);
    //}
};
class Video {
    constructor() {
    }
    createDimensions = (isLive, title, mediaId) => {
        const keysValue = ['Flowplayer', 0, title ? title : "", mediaId, isLive ? true : false, 'calcalist']
        const dimensions = {};
        const dimensionNumber = {
            videoType: 13,
            videoLen: 15,
            videoTitle: 16,
            videoId: 17,
            liveVideo: 24,
            videoCh: 23
        }
        let i = 0
        for (let key in dimensionNumber) {
            const dimKey = "dimension" + dimensionNumber[key]
            Object.assign(dimensions, { [dimKey]: keysValue[i] })
            i++
        }
        return dimensions
    }
    buildAdTagUrl() {
        dcPath.dxseg = '0mJNMic9,1yM2oax7,59GeXlyG,6jjFIBhv,9rx8qYLh,BSMlliz8,FcADKpAV,Im6K9Q12,Mp8p5GCq,MxKlNxsQ,PODLpJl0,QimtDxJG,S6i53J4x,SFPNO4yS,TdPvz55X,UZ80a2eV,VyJyRxFn,Wcdcxnrr,X4KBfLev,X57NA6W0,YTPJ4C3H,ZF4ZoHjq,awcTSkr7,bFHSdTVq,j0OxwZNF,jAxGp0gb,k0YKHkXU,k68oBgdb,lxZBEnHC,mqZmzXw7,nPJWUVY6,pSNoVd78,pp93P91D,pvNnUzAU,qkyQthwV,u3LrnN1X,we5fbBVX,wsfhiEQu,y6UuTBIi,zDDDMl3T'
        return dcPath.dcPath.indexOf('3847') > -1 || dcPath.dcPath.indexOf('5144') > -1 ? '' :
            'https://pubads.g.doubleclick.net/gampad/ads?iu=/' + dfpRoute + '/Network.video/video.calcalist/mobileweb/video.calcalist.vast&description_url=[placeholder]&tfcd=0&npa=0&sz=640x360%7C640x480' + '&cust_params=' + encodeURIComponent(Object.keys(dcPath).map(key => key + '=' + dcPath[key]).join('&')) + '&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=';
    }
    Init() {
        let ga_accounts = [];
        try {
            ga.getAll().forEach(element => ga_accounts.push(element.get('trackingId')));
            ga_accounts = ga_accounts.filter((data, index) => {
                return ga_accounts.indexOf(data) === index;
            });
        } catch (e) {

        }
        let videos = document.querySelectorAll('.fp-video');
        videos.forEach(v => {
            flowplayer(`#${v.id}`, {
                //type: 'application/x-mpegurl',
                token: yitvideotoken,
                src: v.dataset.src,
                poster: v.dataset.poster,
                ratio: v.dataset.ratio,
                //title: v.dataset.title,
                title: v.dataset.credit,
                lang: 'he',
                preload: 'none',
                start_quality: 1,
                //hls: {
                //    startLevel: -1,
                //    testBandwidth: true
                //},
                ima: {
                    ads:
                        [
                            { time: 0, adTag: this.buildAdTagUrl() },
                        ]
                },
                ga: {
                    ga_instances: ga_accounts,
                    media_title: `${v.id}#${v.title || v.credit || ""}`,
                    event_categories: {
                        live: "Video", videos: "Video"
                    },
                    event_actions: {
                        video_player_load: "Video Player Loaded",
                        fullscreen_enter: "Enter Fullscreen",
                        fullscreen_exit: "Exit Fullscreen",
                        video_start: "Play - Video Starts",
                        video_pause: "Pause",
                        video_resume: "Resume",
                        video_mute: "Mute",
                        video_unmute: "Unmute",
                        video_25_percent: "Played - 25%",
                        video_50_percent: "Played - 50%",
                        video_75_percent: "Played - 75%",
                        video_complete: "Video Completed",
                        live_start: "Play - Video Starts",
                        live_click_play: "Play - Video Starts ",
                        live_pause: "Pause",
                        live_resume: "Resume",
                        live_mute: "Mute",
                        live_unmute: "Unmute",
                        live_complete: "Video Completed",
                        ad_start_preroll: "Ad Start Preroll [x]",
                        ad_start_midroll: "Midroll Ad Start",
                        ad_start_postroll: "Ad Start Postroll [x]",
                        ad_completed_preroll: "Preroll Ad Completed",
                        ad_completed_midroll: "Mideroll Ad Completed",
                        ad_completed_postroll: "Postroll Ad Completed",
                        ad_skipped_preroll: "Preroll Ad Skipped",
                        ad_skipped_midroll: "Midroll Ad Skipped",
                        ad_skipped_postroll: "Postroll Ad Skipped",
                    },
                    custom_data: this.createDimensions(v.dataset.islive, v.dataset.title, v.dataset.mediaid),
                },

            });
            v.querySelector('.loader').remove();
        });
    }
}

//  Initialization
$(function () {
    let video = new Video();
    video.Init();
});;
