// noinspection SpellCheckingInspection
var overlays = {

    resizeHandler : null,

    dimensionalFields : {
        "top"           : {"h": ["top"]},
        "left"          : {"w": ["left"]},
        "width"         : {"w": ["width"]},
        "height"        : {"h": ["height"]},
        "font-size"     : {"h": ["font-size"]},
        "v-padding"     : {"h": ["padding-top","padding-bottom"]},
        "h-padding"     : {"w": ["padding-left", "padding-right"]},
        "border-radius" : {"w": ["border-radius","-webkit-border-radius","-moz-border-radius"]},
        "br-width"      : {"w": ["border-width"]}
    },

    nonDimensionalFields : {
        "text"  : {"all" : { set: function(elem,val) { elem.html(val)}}},
        "class" : {"all" : { set:function(elem,val){ elem.attr('class',val).addClass('cta-button')}}},
        "link" : {"button" : { set : function(elem,val) {elem.attr('href',val)}}},
        "link_target" : {"button" : { set : function(elem,val) {elem.attr('target',val)}}},
        "bg-color" : {"all" : { set:function(elem,val){ elem.css('background-color',val)}}},
        "fg-color" : {"all" : { set:function(elem,val){ elem.css('color',val)}}},
        "br-color" : {"all" : { set:function(elem,val){ elem.css('border-color',val)}}},
        "font" : {"all" : { set:function(elem,val){ elem.css('font-family',val)}}},
    },


    youtubeParser: function(url){
        // noinspection RegExpRedundantEscape
        var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
        var match = url.match(regExp);
        return (match&&match[7].length===11)? match[7] : false;
    },

    render : function(bgElem) {
        var container = bgElem.parent();

        //match video height if any
        var video = container.find('>.video');
        if (video.length > 0) {
            var h = bgElem.outerHeight();
            video.attr('height', h);
            bgElem.css({'visibility':'hidden'});
        }


        container.find('>[data-type]').each(function () {
            // noinspection JSCheckFunctionSignatures
            var elem = $(this);
            var imgHeight = bgElem.height();
            var imgWidth = bgElem.width();
            var view = JSON.parse(container.attr('data-size'));
            var dimensionalFieldKeys = Object.keys(overlays.dimensionalFields);
            for (var i = 0; i < dimensionalFieldKeys.length; i++) {
                var prop = dimensionalFieldKeys[i];
                var orig = elem.attr('data-' + prop);
                var dimensions = Object.keys(overlays.dimensionalFields[prop]);
                for (var dIndex = 0; dIndex < dimensions.length; dIndex++) {
                    var dimension = dimensions[dIndex];
                    var base = view[dimension];
                    var percent = (orig / base) * 100;
                    var newValue = (dimension === "w" ? imgWidth : imgHeight) * percent / 100;
                    var roundedValue = Math.round(newValue);
                    var domProps = overlays.dimensionalFields[prop][dimension];
                    for (var domPropIndex = 0; domPropIndex < domProps.length; domPropIndex++) {
                        elem.css(domProps[domPropIndex],roundedValue + "px");
                    }
                }
            }

            elem.css({'position': 'absolute', 'visibility': '1'}).hide();
            if (video.length === 0) {
                elem.fadeIn(); //for images only, for video the play event will make it show
            }

        });


    },

    createVideo : function(wrap, bgElem, data) {
        var videoId = data['video']['youtubeId'];
        wrap.find('.video').remove();
        // noinspection JSCheckFunctionSignatures
        var videoHolder = $('<div class="video" style="position: absolute; top:0; left: 0; z-index:0; width:100%"></div>');
        bgElem.before(videoHolder);
        bgElem.css({'position':'relative','opacity':'0'});

        var isInCarousel = wrap.is('.carousel .overlay-wrap');

        // noinspection JSUnresolvedVariable
        if (typeof YT !== 'undefined') {
            // noinspection ES6ModulesDependencies, JSUnresolvedVariable, JSUnresolvedFunction
            bgElem.get(0).player = new YT.Player(videoHolder.get(0), {
                height: bgElem.outerHeight(),
                width: '100%',
                videoId: videoId,
                playerVars : {
                    autoplay : 1,
                    cc_load_policy : 0,
                    controls : 0,
                    enablejsapi : 1,
                    iv_load_policy : 3,
                    modestbranding : 1,
                    mute: 1,
                    loop: 1,
                    playlist: videoId
                },
                events: {
                    'onReady': function(){
                        overlays.render(bgElem);
                    },
                    'onStateChange': function(event){
                        if (event.data === YT.PlayerState.ENDED) {
                            bgElem.fadeIn('fast',function(){
                                // noinspection JSCheckFunctionSignatures
                                $(this).css({'opacity':1,'display':'inline-block'});
                            });
                        }
                        if (event.data === YT.PlayerState.PLAYING) {
                            bgElem.fadeOut('fast',function(){
                                // noinspection JSCheckFunctionSignatures
                                $(this).css({'opacity':0,'display':'inline-block'});
                                wrap.find('[data-type]').fadeIn();
                            });
                            vidDur=0;
                            function repeater(){
                                vidDur=bgElem.get(0).player.getDuration();
                                ms = (Math.round(vidDur)-5)*1000;
                                setTimeout(playAgain,ms);
                            }
                            setTimeout(repeater,3000);
                        }
                    }
                }
            });
            var playAgain = function(){
                plyr=bgElem.get(0).player;
                plyr.nextVideo();
            };
        }
    },

    setupElem : function(bgElem) {
        if ((bgElem.attr('data-overlay-setup') || '') === '') {
            bgElem.attr('data-overlay-setup','true');


            bgElem.click(function(event){
                event.stopPropagation();
                event.preventDefault();
            });

            // noinspection JSCheckFunctionSignatures
            var wrap = $("<div class='overlay-wrap' style='position:relative; display:inline-block'></div>");
            if ((bgElem.attr('data-expand') || '') !== '') {
                wrap.attr('data-expand','true');
            }

            bgElem.before(wrap);
            wrap.append(bgElem);
            var data = JSON.parse(atob(bgElem.attr('data-overlay')));
            wrap.attr('data-size', JSON.stringify(data['dimensions']));

            if (typeof data['video'] !== 'undefined') {
                overlays.createVideo(wrap, bgElem, data);
            }

            var objects = data['objects'] || [];

            var typeMap = {
                'text' : '<p data-type="text"></p>',
                'button' : '<a class="btn btn-primary cta-button" data-type="button" data-link=""></a>'
            };

            // noinspection JSCheckFunctionSignatures
            $(objects).each(function () {

                var attrs = this;

                // noinspection JSCheckFunctionSignatures
                var elem = $(typeMap[attrs['type']]);
                var nonDimProps = Object.keys(overlays.nonDimensionalFields);
                for (var ndIdx = 0; ndIdx < nonDimProps.length; ndIdx++) {
                    var field = nonDimProps[ndIdx];
                    var root = overlays.nonDimensionalFields[field][attrs['type']] || overlays.nonDimensionalFields[field]['all'];
                    if (root) {
                        root.set(elem, atob(attrs[field] || ''));
                    }
                }

                var attrKeys = Object.keys(attrs);
                for (var i = 0; i < attrKeys.length; i++) {
                    var key = attrKeys[i];
                    var val = attrs[key];
                    if (key !== '0' && (typeof overlays.dimensionalFields[key] !== 'undefined' || typeof overlays.nonDimensionalFields[key])) {
                        elem.attr('data-' + key, val);
                    }
                }

                elem.css('visibility','0');
                wrap.append(elem);

            });

            overlays.render(bgElem);
        }
    },



    init: function (elems) {

        var is_iOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform), firstLoad = true;

        elems.each(function () {
            // noinspection JSCheckFunctionSignatures
            var bgElem = $(this);
            overlays.setupElem(bgElem);

            bgElem.on('load',function () {
                // noinspection JSCheckFunctionSignatures
                overlays.render($(this));
            });

            var tagName = bgElem.get(0).tagName;
            var inCarousel = bgElem.is('.carousel ' + tagName + '[data-overlay]');
            if (inCarousel) {
                var carousel = bgElem.parents('.carousel:first');
                var slideCount = carousel.find('.item').length;
                var videoCount = carousel.find('iframe.video').length;
                if ((carousel.attr('data-overlay-init') || '') === '') {
                    carousel.attr('data-overlay-init','true');
                    carousel.on('slide.bs.carousel', function () {
                        // noinspection JSCheckFunctionSignatures
                        $(this).find('.overlay-wrap [data-type]').fadeOut('fast');
                        // noinspection JSCheckFunctionSignatures
                        var elemsInside = $(this).find('.item:not(.active) [data-overlay]');
                        elemsInside.each(function () {
                            // noinspection JSCheckFunctionSignatures
                            var elem = $(this);
                            //play video if any
                            // noinspection JSUnresolvedVariable
                            if (typeof elem.get(0).player !== 'undefined' && typeof elem.get(0).player.pauseVideo === 'function') {
                                // noinspection JSUnresolvedFunction
                                //elem.get(0).player.pauseVideo();
                            }

                        });

                    });

                    var renderCurrent = function(carousel) {
                        // noinspection JSCheckFunctionSignatures, SpellCheckingInspection
                        var elemsInside = carousel.find('.item.active [data-overlay]');
                        elemsInside.each(function () {
                            // noinspection JSCheckFunctionSignatures
                            var elem = $(this);
                            overlays.render(elem);

                            //play video if any
                            if (typeof elem.get(0).player !== 'undefined') {
                                if (videoCount === 1 && slideCount > 1 && firstLoad) { // if iOS and first slide is the only video
                                    firstLoad = false;
                                    var videoIndex = carousel.find('iframe.video').parents('.item:first').index();
                                    if (videoIndex === 0 && is_iOS) { carousel.carousel('next'); }
                                }
                                // noinspection JSUnresolvedFunction
                                if (typeof elem.get(0).player.playVideo === 'function') { elem.get(0).player.playVideo(); }
                            }

                        });

                    };
                    carousel.on('slid.bs.carousel', function () {
                        // noinspection JSCheckFunctionSignatures
                        renderCurrent($(this));
                    });

                    renderCurrent(carousel);


                }
            }

        });

        // noinspection JSCheckFunctionSignatures
        $(window).on('resize',function(){
            elems.each(function () {
                // noinspection JSCheckFunctionSignatures
                var elem = $(this);
                var container = elem.parent();
                container.find('[data-type]').hide();
                var video = container.find('>.video');
                var h = elem.outerHeight();
                video.attr('height',h);
            });

            if (overlays.resizeHandler !== null) {
                clearInterval(overlays.resizeHandler);
            }
            overlays.resizeHandler = setTimeout(function(){
                elems.each(function () {
                    // noinspection JSCheckFunctionSignatures
                    overlays.render($(this));
                });
                elems.parent().find('[data-type]').fadeIn();
            },200);
        });

    }
};

onYouTubeIframeAPIReady = function () {
    // noinspection JSCheckFunctionSignatures
    overlays.init($('img[data-overlay]'));
};

function checkAPI() {
    // noinspection JSCheckFunctionSignatures
    if ($('script[src="https://www.youtube.com/iframe_api"]').length == 0) {
        if (typeof YT !== 'object') overlays.init($('img[data-overlay]'));
    }
} $(window).load(checkAPI);
