/* Minification failed. Returning unminified contents.
(517,31): run-time error JS1004: Expected ';'
(572,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();
    }

    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)
        })("//cdn.piano.io/api/tinypass.min.js");
    }
    //  short-hand method Stock
    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');

        });

        $('#c-menu__accessibility').on('click', function (e) {

            //https://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
            function loadScript(url, callback) {

                var script = document.createElement("script");
                script.type = "text/javascript";
                script.setAttribute("data-cfasync", "true");
                script.setAttribute("integrity", "sha512-JkluHARviIJeTsvupKh9gkG6AsMbbBOkfg9zPQvZwxJtslc0NTDhdQrVX+qg45fEyM97XrW07Gb8wmh/vwlITA==");
                script.setAttribute("crossorigin", "anonymous");
                script.setAttribute("defer", "true");

                if (script.readyState) {  //IE
                    script.onreadystatechange = function () {
                        if (script.readyState === "loaded" ||
                            script.readyState === "complete") {
                            script.onreadystatechange = null;
                            callback();
                        }
                    };
                } else {  //Others
                    script.onload = function () {
                        callback();
                    };
                }

                script.src = url;
                document.getElementsByTagName("head")[0].appendChild(script);
            }

            if (window.interdeal !== null && typeof window.interdeal !== 'undefined') {
                setTimeout(() => {
                    let Ishidden = Boolean($('#INDmenu').attr('aria-hidden'));
                    $('#INDmenu').attr('aria-hidden', !Ishidden);
                }, 250);
            }
            else {
                window.interdeal = { sitekey: 'ee4d8d8ceda67bd43f0b2a64a2426430', Position: 'Left', Menulang: 'HE', domains: { js: "https://js.nagich.co.il/", acc: "https://access.nagich.co.il/" } };
                loadScript('https://js.nagich.co.il/core/2.1.9/accessibility.js', function () {
                    setTimeout(() => { $('#INDmenu-btn').trigger('click'); }, 1000);
                });
            }

        });
        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(2022, 9, 4, 7, 0, 0),
                'maxdate': new Date(2022, 9, 5, 19, 0, 0),
                'className': 'KippurFlag',
            },
            {
                'mindate': new Date(2022, 8, 25, 10, 0, 0),
                'maxdate': new Date(2022, 8, 27, 17, 0, 0),
                'className': 'ShanaTovaFlag',
            },
            {
                'mindate': new Date(2022, 4, 4, 16, 0, 0),
                'maxdate': new Date(2022, 4, 5, 20, 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(2022, 9, 9, 16, 0, 0),
                'maxdate': new Date(2022, 9, 17, 20, 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() {
    }
    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();
    }
    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(() => {
                tp.pianoId.logout();
                //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) {
                window.location.href = baseUrl + 'MyAccount.aspx';
            } else {
                window.loginCalcalist.Login();
            }
        }) : null;

    }
    loadLoginMenubyState() {
        let self = this;
        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();
                                }
                                else {
                                    document.querySelector('.c-loginlayout.--loggedin').classList.add('--no-resources');
                                }
                            });
                        }
                        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');
                    }, 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();
                },
                loggedOut: function () {
                    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);
    //}
};
