(function () {
    // temp vars, needed for loading only. use window[wj][hash][embedConfig] when needed
    var wjEmbedConfig = {"hash":"74l2qhz1","memberId":214314,"webinarId":227,"embedType":"button","dependencies":{"js":"https:\/\/event.webinarjam.com\/js\/registration_embed.js","css":"https:\/\/event.webinarjam.com\/css\/registration_embed.css"},"routes":{"convertDates":"https:\/\/event.webinarjam.com\/register\/74l2qhz1\/convert-dates","trackVisitor":"https:\/\/event.webinarjam.com\/register\/74l2qhz1\/visitor","registrationForm":"https:\/\/event.webinarjam.com\/register\/227\/74l2qhz1\/form?ts=1618562147"},"translations":{"Text_days":"DAYS","Text_hours":"HOURS","Txt_instant_replay":"Watch yesterday\u0027s replay now","MSG_minutes":"Minutes","MSG_seconds":"Seconds","Txt_connecting_to_server":"Checking availability...","Txt_join_event_in_progress":"Join event in progress"},"iframeOverlayHtml":"\u003Cdiv class=\u0022wj_registration-overlay\u0022 style=\u0022top: 0px; display: none;\u0022\u003E\n    \u003Cdiv id=\u0022wj_registration_frame_holder\u0022 style=\u0022margin: 0 auto; max-width: 700px;\u0022\u003E\n        \u003Cdiv style=\u0022height: 270px;\u0022\u003E\n            \u003Cdiv class=\u0022wj_overlay-loading-screen\u0022 style=\u0022display:;\u0022\u003E\n                \u003Cdiv class=\u0022wj_overlay_inner\u0022\u003E\n                    \u003Cdiv class=\u0022wj_css_spinner_coghweel n_s wj_mb-4\u0022\u003E\n                        \u003Cdiv\u003E\n                            \u003Ci\u003E\u003C\/i\u003E\n                            \u003Ci\u003E\u003C\/i\u003E\n                        \u003C\/div\u003E\n                    \u003C\/div\u003E\n                    \u003Cspan\u003E\u003Clang data-tag=\u0022Txt_connecting_to_server\u0022\u003E{{Txt_connecting_to_server}}\u003C\/lang\u003E\u003C\/span\u003E\n                \u003C\/div\u003E\n            \u003C\/div\u003E\n            \u003Ciframe src=\u0022\u0022 id=\u0022wj_registration_frame\u0022 frameborder=\u00220\u0022 name=\u0022wj_registration_frame\u0022 scrolling=\u0022no\u0022 style=\u0022display:none; height: 270px; max-width: 700px; width: 100vw; z-index: 1000000; -webkit-overflow-scrolling: touch\u0022\u003E\u003C\/iframe\u003E\n        \u003C\/div\u003E\n    \u003C\/div\u003E\n\u003C\/div\u003E"},
        webinarHash = wjEmbedConfig['hash'],
        embedType = wjEmbedConfig['embedType'];

    wjEmbedConfig['timezoneOffset'] = -(new Date()).getTimezoneOffset();


    if (typeof window['wj'] !== 'undefined' && typeof window['wj'][webinarHash] !== 'undefined') {
        return;
    }

    window['wj'] = 'undefined' === typeof window['wj'] ? [] : window['wj'];
    window['wj'][webinarHash] = 'undefined' === typeof window['wj'][webinarHash] ? {} : window['wj'][webinarHash];
    window['wj'][webinarHash]['embedConfig'] = wjEmbedConfig;
    window['wj'][webinarHash]['embedType'] = embedType;

    var jsJquery    = document.createElement("script");
    jsJquery.type   = "text/javascript";
    jsJquery.onload = init;
    jsJquery.src    = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js";
    document.body.appendChild(jsJquery);

    var ua     = window.navigator.userAgent,
        iOS    = !!ua.match(/iP(ad|od|hone)/i),
        webkit = !!ua.match(/WebKit/i),
        isiOS  = iOS && webkit;

    function init() {
        if (embedType === 'bar') {
            document.body.insertAdjacentHTML('beforeend', window['wj'][webinarHash]['embedConfig'].barHtml);
        }

        loadDependencies();
    };

    function loadDependencies() {
        var wjCssId = 'wjCss-' + webinarHash;
        if (!document.getElementById(wjCssId)) {
            var head  = document.getElementsByTagName('head')[0];
            var link  = document.createElement('link');
            link.id   = wjCssId;
            link.rel  = 'stylesheet';
            link.type = 'text/css';
            link.href = wjEmbedConfig.dependencies.css;
            link.media = 'all';
            head.appendChild(link);
        }

        var wjJsId = 'wjJs-' + webinarHash;
        if (!document.getElementById(wjJsId)) {
            var script  = document.createElement('script');
            script.id   = wjJsId;
            script.type = 'text/javascript';
            script.onload = realInit;
            script.src = wjEmbedConfig.dependencies.js;
            document.body.appendChild(script);
        }
    }

    function realInit() {
        if (embedType === 'bar') {
            return initBottomBar();
        }

        if (embedType === 'button') {
            return initButton();
        }
    }

    function initBottomBar() {
        window['wj'][webinarHash]['jQuery'] = jQuery.noConflict(true);
        window['wj'][webinarHash]['jQuery'].ajaxSetup({
            xhrFields: {
               withCredentials: true
            },
            crossDomain: true
        });
        var jQ = window['wj'][webinarHash]['jQuery'];

        jQ(document).ready(function() {
            var $html = jQ('html'),
                $body = jQ('body');

            var barBgColor = tinycolor(wjEmbedConfig.barBgColor);
            barBgColor.setAlpha(wjEmbedConfig.barBgOpacity);

            var buttonBgColor = tinycolor(wjEmbedConfig.buttonBgColor);
            buttonBgColor.setAlpha(wjEmbedConfig.buttonBgOpacity);

            var data = {
                offset: wjEmbedConfig.timezoneOffset,
                limit: 3,
                source: "bar",
            };
            var datesString = '';
            var datesXhr = jQ.post(wjEmbedConfig.routes.convertDates, data);
            datesXhr.done(function (response) {
                if (response.registrationDates.length === 0) {
                    if (typeof response.pendingChanges !== 'undefined' && response.pendingChanges === true)  {
                        jQ('.wj_red_overlay_title').text(wjEmbedConfig.translations.Txt_webinar_not_ready_yet);
                        jQ('.wj_red_overlay_desc').text(wjEmbedConfig.translations.Txt_preparing_webinar);
                    } else {
                        jQ('.wj_red_overlay_title').text(wjEmbedConfig.translations.Txt_this_webinar_expired);
                        jQ('.wj_red_overlay_desc').text(wjEmbedConfig.translations.Txt_webinar_already_taken_place);
                    }
                    jQ('.wj_red_overlay_content').removeClass('wj_hide');
                }
                jQ.each(response.registrationDates, function (index, date) {
                    var template = jQ("#wj-templates #wj-template-date-new").clone();
                    template.find('li.js_date_container').text(date.text);
                    datesString += template.html();
                });

                var timezoneCities = response.timezone.cities;

                // replacements for dates, colors, text, countdown
                jQ('ul.js_all_schedules').html(datesString);
                jQ('.js_register_text').text(wjEmbedConfig.buttonText);
                jQ('.js_bottom_bar_bg').css("background-color", barBgColor);
                jQ('.js_wj_register_button').css("background-color", buttonBgColor);
                jQ('.js_wj_register_button').attr('data-webinarHash', webinarHash);
                jQ('.js_wj_timezone_text').text(timezoneCities);

                // start countdown
                var countdownOptions = {
                    fontFamily: '"Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
                    displayDays: 2,
                    displayCaptions: true,
                    fontSize: 26,
                    captionSize: 10,
                    countdown: true,
                }
                if (response.countdownSeconds > 0) {
                    countdownOptions.seconds = response.countdownSeconds;
                    var countdownDays = Math.floor(countdownOptions.seconds/86400);
                    if (countdownDays >= 100) {
                        countdownOptions.displayDays = 3;
                    }
                } else {
                    countdownOptions.timeTo = new Date();
                    countdownOptions.start = false;
                }
                jQ('.js_countdown').timeTo(countdownOptions);

                jQ('.js_countdown figcaption:eq(0)').html('<lang data-tag="Text_days">{{Text_days}}</lang>');
                jQ('.js_countdown figcaption:eq(1)').html('<lang data-tag="Text_hours">{{Text_hours}}</lang>');
                jQ('.js_countdown figcaption:eq(2)').html('<lang data-tag="MSG_minutes">{{MSG_minutes}}</lang>');
                jQ('.js_countdown figcaption:eq(3)').html('<lang data-tag="MSG_seconds">{{MSG_seconds}}</lang>');

                // show bar
                jQ('.wj_embed_wrapper').fadeIn();

                // init registration modal
                replaceLang();
                initRegistrationModal();
                trackVisitor();
            });
            datesXhr.fail(function () {
                console.error('Could not get dates from WJ server');
            })
        });
    }

    function initButton() {
        window['wj'][webinarHash]['jQuery'] = jQuery.noConflict(true);
        window['wj'][webinarHash]['jQuery'].ajaxSetup({
            xhrFields: {
               withCredentials: true
            },
            crossDomain: true
        });
        var jQ = window['wj'][webinarHash]['jQuery'];

        jQ(document).ready(function() {
            var $html = jQ('html'),
                $body = jQ('body');

            initRegistrationIframeOverlay();

            // init registration modal
            replaceLang();
            initRegistrationModal();
            trackVisitor();
        });
    }

    function replaceLang()
    {
        var jQ = window['wj'][webinarHash]['jQuery'],
            wjEmbedConfig = window['wj'][webinarHash]['embedConfig'];

        // replace any translations
        jQ('lang').each(function (key, item) {
            var $item = jQ(item);
            var tag = $item.attr('data-tag');
            $item.text(wjEmbedConfig.translations[tag]);
        });
    }

    function initRegistrationIframeOverlay()
    {
        var jQ = window['wj'][webinarHash]['jQuery'],
            wjEmbedConfig = window['wj'][webinarHash]['embedConfig'];

        if (jQ('.wj_registration-overlay').length) {
            return ;
        }

        if (typeof wjEmbedConfig.iframeOverlayHtml === 'undefined') {
            return ;
        }

        document.body.insertAdjacentHTML('beforeend', wjEmbedConfig.iframeOverlayHtml);
    }

    function initRegistrationModal() {
        var jQ = window['wj'][webinarHash]['jQuery'];

        jQ(document).ready(function() {
            var $html = jQ('html'),
                $body = jQ('body');

            window['wj'][webinarHash]['real_loaded'] = false;
            window['wj'][webinarHash]['fake_loaded'] = false;

            if (isiOS) {
                window['wj'][webinarHash]['wj_lock_scroll'] = false;
                window['wj'][webinarHash]['wj_touch_on']    = false;

                window['wj'][webinarHash]['wj_original_padding_bot'] = $body.css('paddingBottom');
            }

            window.removeEventListener('message', window['wj']['wjOnIframeMessage'], true);
            window.addEventListener('message', window['wj']['wjOnIframeMessage'], false);
            
            // registration button click
            jQ('[data-webinarHash='+webinarHash+']').off().on('click', function () {

                $body.addClass("wj_body_reset");
                $html.css('overflow', 'hidden');

                var $self  = jQ(this),
                    webinarHash = $self.attr('data-webinarHash'),
                    wjEmbedConfig = window['wj'][webinarHash]['embedConfig'];

                if (isiOS) {
                    $html.addClass('wj_body_reset_safari_ios');
                    $body.addClass('wj_body_reset_safari_ios');
                    jQ('.wj_registration-overlay')
                        .addClass('wj_overflow_touch')
                        .css({
                            'paddingTop': jQ(window).scrollTop()
                        });

                    window['wj'][webinarHash]['wj_lock_scroll'] = true;

                    jQ(window, 'iframe').off('touchend').off('touchstart')
                        .on('touchend', function() {
                            window['wj'][webinarHash]['wj_touch_on'] = false;
                            rePosition(webinarHash);
                        }).on('touchstart', function () {
                            window['wj'][webinarHash]['wj_touch_on'] = true;
                        });

                    jQ(window).off('scroll').on('scroll', function() {
                        if (!window['wj'][webinarHash]['wj_touch_on'] &&
                            window['wj'][webinarHash]['wj_lock_scroll']) {
                            rePosition(webinarHash);
                        }
                    });
                }

                jQ('.wj_registration-overlay').show();
                var iframeSrc = wjEmbedConfig.routes.registrationForm + '&offset=' + wjEmbedConfig.timezoneOffset;
                jQ('#wj_registration_frame').attr('src', iframeSrc);

                setTimeout(function() {
                    hideLoader(webinarHash, 'fake');
                }, 3000);
            });
        });
    }

    function trackVisitor() {
        var jQ = window['wj'][webinarHash]['jQuery'];

        jQ(document).ready(function() {
            var $html = jQ('html'),
                $body = jQ('body'),
                hasVisitorCookie = window.wjHasCookie(wjEmbedConfig.memberId, webinarHash),
                visitorCookie = window.wjTrackingCookie(wjEmbedConfig.memberId, webinarHash);

            if (!hasVisitorCookie) {
                jQ.post(wjEmbedConfig.routes.trackVisitor, {});
                window.wjSetVisitorCookie(wjEmbedConfig.memberId, webinarHash);
            }
        });
    }

    window['wj']['wjOnIframeMessage'] = function (message) {
        if ('undefined' === typeof message.data) {
            return;
        }

        var webinarHash = message.data.hash;

        if ('undefined' === typeof webinarHash) {
            return;
        }

        var jQ = window['wj'][webinarHash]['jQuery'],
            $html = jQ('html'),
            $body = jQ('body');

        switch (message.data['func']) {
            case 'loaded':
                hideLoader(webinarHash, 'real');
                break;
            case 'resize':
                adjustFrameSize(webinarHash, message.data['height'] + 'px');
                break;
            case 'resizeWidth':
                adjustFrameWidth(webinarHash, message.data['width'] + 'px');
                break;
            case 'toTop':
                jQ(window).scrollTop(0);
                break;
            case 'redirect':
                recursiveRedirect(window.parent, message.data['url']);
                break;
            case 'close':
                window['wj'][webinarHash]['real_loaded'] = false;
                window['wj'][webinarHash]['fake_loaded'] = false;

                // hide the whole popup
                // show the loader inside the hidden popup
                // hide the iframe inside the hidden popup
                jQ('.wj_registration-overlay').hide();
                jQ('.wj_overlay-loading-screen').show();
                jQ('#wj_registration_frame').hide();

                $html.css('overflow','auto');
                $body.css('height','').removeClass('wj_body_reset');

                if (isiOS) {
                    jQ(window, 'iframe').off('touchend').off('touchstart');
                    jQ(window).off('scroll');

                    window['wj'][webinarHash]['wj_lock_scroll'] = false;

                    $html.removeClass('wj_body_reset_safari_ios');
                    $body.removeClass('wj_body_reset_safari_ios');
                    $body.css('paddingBottom', window['wj'][webinarHash]['wj_original_padding_bot']);
                    jQ('.wj_registration-overlay').removeClass('wj_overflow_touch');
                }

                adjustFrameSize(webinarHash, '270px');
                break;
            case 'lockscroll':
                if (isiOS) {
                    window['wj'][webinarHash]['wj_lock_scroll'] = message.data['locked'];
                    window['wj'][webinarHash]['wj_lock_scroll'] && rePosition(webinarHash);
                }
                break;
            case 'touchstart':
                if (isiOS) {
                    window['wj'][webinarHash]['wj_touch_on'] = true;
                }
                break;
            case 'touchend':
                if (isiOS) {
                    window['wj'][webinarHash]['wj_touch_on'] = true;
                    rePosition(webinarHash);
                }
                break;
        }
    }

    function recursiveRedirect(parent, url) {
        try {
            parent.location = url;
        } catch(err) {
            parent = parent.parent;
            recursiveRedirect(parent, url);
        }
    }

    function hideLoader(webinarHash, version) {
        var jQ = window['wj'][webinarHash]['jQuery'];

        window['wj'][webinarHash][version + '_loaded'] = true;

        if (window['wj'][webinarHash]['real_loaded'] && window['wj'][webinarHash]['fake_loaded']) {
            jQ('.wj_overlay-loading-screen').hide();
            jQ('#wj_registration_frame').show();

            // @todo
            var theFrame = document.getElementById('wj_registration_frame').contentWindow;
            theFrame.postMessage({
                'func': 'childResize',
            }, '*')
        }
    }

    function adjustFrameSize(webinarHash, height) {
        var jQ = window['wj'][webinarHash]['jQuery'],
            $theFrame = jQ('#wj_registration_frame');

        $theFrame.css('height', height);
        $theFrame.parent().css('height', height);

        if (isiOS && window['wj'][webinarHash]['real_loaded']) {
            jQ('body').css('paddingBottom', height);
        }
    }

    function adjustFrameWidth(webinarHash, width) {
        var jQ = window['wj'][webinarHash]['jQuery'];
        jQ('#wj_registration_frame_holder').css('max-width', width)
        jQ('#wj_registration_frame').css('max-width', width)
    }

    function rePosition(webinarHash) {
        if (!window['wj'][webinarHash]['wj_lock_scroll']) {
            return false;
        }

        var jQ            = window['wj'][webinarHash]['jQuery'],
            $htmlBody     = jQ('html,body'),
            scrollTop     = jQ(window).scrollTop(),
            screenY       = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
            scrollBottom  = jQ(window).scrollTop() + screenY,
            marginTop     = screenY * 0.2, // 20% of screen size
            marginBot     = screenY * 0.5, // 50% of screen size
            modalOverlay  = jQ('.wj_registration-overlay'),
            modalPadding  = parseInt(modalOverlay.css('paddingTop')),
            iframeHeight  = jQ('#wj_registration_frame').outerHeight(),
            height        = screenY > iframeHeight ? screenY : iframeHeight,
            frameBot      = modalPadding + height;

        if (scrollTop < modalPadding - marginTop) {
            $htmlBody.stop().animate({scrollTop: modalPadding}, 50, 'swing');
            return true;
        } else if (scrollBottom > frameBot + marginBot) {
            $htmlBody.stop().animate({scrollTop: frameBot - screenY}, 50, 'swing');
            return true;
        }

        return false;
    }
})();