// source --> https://www.staging.boldinternet.co.uk/wp-content/plugins/clever-youtube-plugin/cyp.js?ver=4.243 
;(function(window, $) {
	'use strict';

    $.fn.selectRange = function(start, end) {
        if (end === undefined) {
            end = start;
        } 
        return this.each(function() {
            if ('selectionStart' in this) {
                this.selectionStart = start;
                this.selectionEnd = end;
            } else if (this.setSelectionRange) {
                this.setSelectionRange(start, end);
            } else if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
        });
    };

    $.fn.cypDialog = function( options ) {
        var settings = $.extend({
            title: 'Clever YouTube Plugin',
            autoOpen: false,
            closeText: '',
            dialogClass: 'cyp-dialog cyp-dialog-confirmation',
            modal: true,
            resizable: false,
            draggable: false,
            buttons: {
                'OK': function() {
                    $(this).dialog('close');
                }
            },
        }, options );
        
        return this.dialog(settings);
    };

    window.cyp = {};
    window.cyp.audio = {};
    window.cyp.audio.play = function (path) {
        var audio = new Audio(WPURLS.cypurl + '/' + path);
        audio.play();
        return audio;
    };
    window.cyp.audio.load = function (path) {
        var audio = new Audio(WPURLS.cypurl + '/' + path);
        audio.preload = 'auto';
        return audio;
    };
    window.cyp.youtube = {};
    window.cyp.youtube.parseUrl = function (url) {
        var youTubeIdLength = 11;

        if (url && typeof url === 'string') {
            var tests = [
                parseByParam,
                parseByShortUrl,
                parseByEmbed,
                parseById
            ];

            for (var i = 0; i < tests.length; i++) {
                var result = tests[i](url);

                if (result) {
                    return result;
                }
            }
        }
        
        return false;

        function parseByParam(url) {
            return parseByNeedle(url, 'v=');
        }
        function parseByShortUrl(url) {
            return parseByNeedle(url, 'youtu.be/');
        }
        function parseByEmbed(url) {
            return parseByNeedle(url, 'youtube.com/embed/');
        }
        function parseById(url) {
            if (url.length === youTubeIdLength) {
                return url;
            } else {
                return false;
            }
        }
        function parseByNeedle(url, needle) {
            var index = url.indexOf(needle);

            if (index > -1) {
                var start = index + needle.length;
                var end = start + youTubeIdLength;
                var str = url.substring(start, end);

                if (str.length === youTubeIdLength) {
                    return str;
                }
            }
            
            return false;
        }
    };

})(window, jQuery);
// source --> https://www.staging.boldinternet.co.uk/wp-content/plugins/clever-youtube-plugin/cyp-client.js?ver=4.243 
var CleverYouTubePluginHelper;

var cypObjects = Array();

var cypseekhltimer;

var cyppopupobject;

var cyp_hover_images = [];

var cyp_registry = {};



// Animation for the play buttons

jQuery.fn.throb = function(options, ignoreMargin) {

    // always stop current animations

    this.stop();



    if (this.data("start-width")) {

        this.width(this.data("start-width"));

        this.height(this.data("start-height"));

        

        if ((typeof options === 'undefined') ||

        (jQuery.isPlainObject(options) && options.adjustMargin) ||

        (options === 'stop' && !ignoreMargin)) {

            this.css('margin-left', -0.5 * this.width());

            this.css('margin-top', -0.5 * this.height());

        }

    }



    if (options !== "stop") {

        var $element = this;



        if (!$element.height()) {

            $element.width(120);

            $element.height(60);

        } else {
            if ($element.width() && $element.width() !== 2 * $element.height()) {
                $element.height($element.width() * 0.5);
            }
        }

        var settings = jQuery.extend({

                duration: 1000,

                scale: 0.5,

                adjustMargin: true

            }, options);

        var start = {

            width: $element.width(),

            height: $element.height()

        };

        var end = {

            width: start.width * settings.scale,

            height: start.height * settings.scale

        };

        

        if (settings.adjustMargin) {

            start.marginLeft = -0.5 * $element.width();

            start.marginTop = -0.5 * $element.height();

            end.marginLeft = -0.5 * (start.width * settings.scale);

            end.marginTop = -0.5 * (start.height * settings.scale);

        }

        var animation = function () {

            $element.animate(

                end,

                settings.duration,

                function() {

                    $element.animate(

                        start,

                        settings.duration,

                        function() {

                            animation();

                        });

                });

        };

        this.data("start-width", start.width);

        this.data("start-height", start.height);

        animation();

    }

        

    return this;

};



// hearts animation

jQuery.fn.heartsEffect = function(options) {

    var defaults = {

        numberOfHearts: 5, // number of hearts to animate

        motionMax: 60, // maximum pixels moved away from source

        motionSpeed: 1000, // milliseconds of animation duration,

        center: true,

    };

    var $element = this;

    var settings;

    init();

    return $element;

    

    function init() {

        if (options === 'stop') {

            stop();

        } else {

            settings = jQuery.extend({}, defaults, options);

            start();

        }

    }

    function stop() {

        clearInterval($element.heartsTimer);

        $element.heartsTimer = 0;

    }

    function animate() {

        // create animation divs

        var css = {

            // center hearts to button

            marginLeft: ( -18 / 2) + 'px',

            marginTop: ( -18 / 2) + 'px',

        };

        

        if (settings.center) {

            css.left = '50%';

            css.top = '50%';

        }

        for (var i = 0; i < settings.numberOfHearts; i++) {

            $element.parent()

                .append("<div class='cyp-heart'></div>")

                .children(':last')

                .css(css)

                .animate({

                    marginLeft: (Math.round(Math.random())*2-1) * (Math.random() * settings.motionMax) + 'px',

                    marginTop: (Math.round(Math.random())*2-1) * (Math.random() * settings.motionMax) + 'px',

                    opacity: 0.75,

                    width: '24px',

                    height: '24px',

                    backgroundSize: '16px'

                }, settings.motionSpeed * (4/5), 'linear', function() {

                    jQuery(this).animate(

                        {

                            opacity: 0,

                            width: '18px',

                            height: '18px',

                            backgroundSize: '10px'

                        },

                        settings.motionSpeed * ( 1 / 5 ),

                        'swing',

                        function() {

                            // destroy the div

                            jQuery(this).remove();

                        }

                    );

                });

        }	

    }

    function start() {

        animate(); // animate at the beginning too



        // stop last timer

        if ($element.heartsTimer !== 0) {

            stop();

        }



        // set continuous animation

        $element.heartsTimer = setInterval(function() {

            animate();

        }, 400);

    }

};



CleverYouTubePluginHelper = {

    loadYouTubeiFrameAPI: function() {

        // Create tag element

        var tag = document.createElement("script");

        tag.src = "//www.youtube.com/iframe_api";

        

        // Add tag element before first script element in page

        var firstScriptTag = document.getElementsByTagName("script")[0];

        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    },



    checkResize: function() {

        jQuery(".cyp-video-object.cyp-responsive").each(function(i, j) {

            var $this = jQuery(this);

            var $parent = $this.parent();

            var $parentParent = $parent.parent().parent();

            var count = $parent.attr("data-count");

            var parentparentTF = $parentParent.innerWidth() / 32;

            var currentTF = $this.outerWidth() / 32;

            if (currentTF != parentparentTF) {
                if ($this.hasClass("border")) {
                    parentparentTF = parentparentTF - 1;
                }
                var updateSize = parentparentTF;
                resize($parent, updateSize, count);
            }
        });

        CleverYouTubePluginHelper.fixPosition();

        CleverYouTubePluginHelper.resizeDescription();

        

        function resize($element, size, count) {

            var change = {

                "font-size": size + "px"

            };

            $element.find(".cyp-w-change").css(change);

            CleverYouTubePluginHelper.resetImageContainers(count);

            CleverYouTubePluginHelper.resetSonar(count);

        }

    },



    tweakStaticBar: function(num, playing) {

        mobile = (/iPhone|iPod|iPad|Android|BlackBerry/).test(navigator.userAgent);



        if (mobile) {

            return;

        }



        // if not autohide, we need to add or subtract 35px from the height

        if (!cypObjectOptions[num].autohide) {

            if (playing) {

                // add 35px

                transformFactor = parseFloat(jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object").css("font-size"));

                newheight = 18 + (35 / transformFactor);

                jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object").css({

                    "height": newheight + "em"

                });

                CleverYouTubePluginHelper.resetImageContainers(num);

            } else {

                // remove 35px

                jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object").css({

                    "height": "18em"

                });

                CleverYouTubePluginHelper.resetImageContainers(num);

            }

        }

    },



    nonResponsiveSizeReset: function() {

        // not responsive

        jQuery(".cyp-video-object").each(function(i, j) {

            if (!jQuery(this).hasClass("responsive")) {

                var $parent = jQuery(this).parent();

                var count = $parent.attr("data-count");

                var css = {

                    "font-size": cypObjectOptions[count].transformFactor + "px"

                };

                $parent.find(".cyp-w-change").css(css);

            }

        });

    },



    removeWrappers: function() {

        jQuery(".fluid-width-video-wrapper > *").unwrap();

    },



    hideBackPanes: function() {

        jQuery(".cyp-video-object-holder .cyp-video-object-after-html").hide();

        jQuery(".cyp-video-object-holder .cyp-video-object-after-image").hide();

    },



    proccessObjects: function() {

        jQuery(".cyp-video-object-holder").each(function(i, j) {

            cypObjects.push(CleverYouTubePluginObject(this));

        });

    },



    resetAllImages: function() {

        jQuery(".cyp-video-object-holder").each(function(i, j) {

            element = jQuery(this);

            count = element.attr("data-count");

            CleverYouTubePluginHelper.resetImageContainers(count);

        });

    },



    resetPadding: function() {

        jQuery(".cyp-video-object-image-container img").each(function(i, j) {

            jQuery(this).css({

                "margin": 0,

                "padding": 0,

                "border": "none"

            });

        });

        CleverYouTubePluginHelper.resetImageContainers();

    },



    resetImageContainers: function(num) {

        // Not really image related but remove video containers

        jQuery(".fluid-width-video-wrapper > *").unwrap();

        jQuery(".cyp-video-object-video").css({

            "height": "inherit",

            "width": "inherit"

        });

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-image-container").each(function(i, j) {

            imagecontainer = jQuery(this);

            image = jQuery(this).find("img");

            image.css({

                "width": "auto",

                "height": "auto"

            });

            container_height = imagecontainer.height();

            container_width = imagecontainer.width();

            image_height = image.height();

            image_width = image.width();

            new_image_height = 0;

            new_image_width = 0;

            var src = image.attr('src');

            var isFromYouTube = (src.toLowerCase().indexOf('youtube.com') > -1);

            

            if (isFromYouTube) {

                if ((image_height / image_width) > (container_height / container_width)) {

                    // fit width

                    new_image_width = Math.ceil(container_width);

                    new_image_height = Math.ceil(image_height * new_image_width / image_width);

                } else {

                    // fit height

                    new_image_height = Math.ceil(container_height);

                    new_image_width = Math.ceil(image_width * new_image_height / image_height);

                }

                image_left = Math.floor((container_width - new_image_width) / 2);

                image_top = Math.floor((container_height - new_image_height) / 2);

                

                if (isNaN(image_left)) {

                    image_left = 0;

                }

                

                // compensate for youtube black bars showing because of image shrinking artifacts

                image_top = image_top - 2;

                new_image_height = new_image_height + 4;

                

                if (new_image_height == "0" || new_image_height == "") {

                    image.css({

                        "height": "auto",

                        "width": new_image_width + "px",

                        "left": image_left + "px",

                        "top": image_top + "px"

                    });

                } else {

                    image.css({

                        "height": new_image_height + "px",

                        "width": new_image_width + "px",

                        "left": image_left + "px",

                        "top": image_top + "px"

                    });

                }

            } else {

                new_image_width = container_width;

                new_image_height = container_height;

                image.css({

                    "height": new_image_height + "px",

                    "width": new_image_width + "px"

                });

            }

        });

    },



    resetPanels: function(num) {

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-play-button").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-repeat-button").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-sonar").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-html").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-image").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-html").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-image").show();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-video").show();

    },



    resetSonar: function(count) {

        if (cypObjectOptions[count].has_sonar && cypObjectOptions[count].responsive) {

            element = jQuery(".cyp-video-object-holder[data-count=" + count + "] .cyp-video-object-sonar-inner");

            new_element = element.clone(true);

            element.before(new_element);

            element.remove();

        }

    },



    add_hover: function(num, original_image, hover_image) {

        var element = ".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-play-button";

        var hoverElement = element;

        

        if (cypObjectOptions[num].hasDescription) {

            hoverElement = hoverElement + ' .img_cyp_playbutton';

        }

        cyp_hover_images.push([num, original_image, hover_image]);



        jQuery(hoverElement)

            .mouseover(function() {

                var $button = jQuery(element).find(".img_cyp_playbutton");



                if (cypObjectOptions[num].animatedbutton) {

                    $button.throb("stop");

                }

                $button.attr("src", hover_image);

            })

            .mouseout(function() {

                var $button = jQuery(element).find(".img_cyp_playbutton");

                $button.attr("src", original_image);



                if (cypObjectOptions[num].animatedbutton) {

                    $button.throb();

                }

            });

    },
    playVideo: function(num) {

        if (typeof cypObjectOptions[num].youtubeobject !== "undefined") {
            //CleverYouTubePluginHelper.playCallback(num);
            cypObjectOptions[num].youtubeobject.playVideo();
        }

    },

    playCallback: function(num) {
        if (!cypObjectOptions[num].playCallback || cypObjectOptions[num].playCallbackPlayed) {
            return;
        }
        cypObjectOptions[num].playCallbackPlayed = true;
        
        if (cypObjectOptions[num].playCallback.startsWith('cyp_tab_play_button_click(')) {
            if (typeof cyp_tab_play_button_click !== 'function') {
                return;
            }
        }
        setTimeout(function () {
            try {
                eval(cypObjectOptions[num].playCallback);
            } catch (e) {
                console.error(e);
            }
        }, 0);
    },

    playClicked: function(num) {
        //CleverYouTubePluginHelper.playCallback(num);
        CleverYouTubePluginHelper.lastPlayClicked = num;

        // Check to see if "after HTML" exists and if it is visible
        // In which case we will not play the video
        if (cypObjectOptions[num].hasafterHTML) {
            var afterHtml = jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-html");

            if (afterHtml.is(':visible')) {
                // Ignore clicks if "after HTML" is visible
                return;
            }
        }

        if (cypObjectOptions[num].youtubeobject) {

            // video already exists, just play it

            if (typeof cypObjectOptions[num].youtubeobject.playVideo === 'function') {

                cypObjectOptions[num].youtubeobject.playVideo();

            }

        } else {

            // Bring in the video
            CleverYouTubePluginHelper.createVideo(num);

        }



        // Set height

        CleverYouTubePluginHelper.tweakStaticBar(num, true);



        // Hide the other panels

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-play-button").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-repeat-button").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-sonar").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-html").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-image").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-html").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-image").hide();

        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-description").hide();

        jQuery(document).focus();

    },



    pauseAll: function() {

        if (typeof cypObjectOptions !== 'undefined') {

            // loop through all cyp objects

            for (var i = 1; i <= cypObjectOptions.length; i++) {

                // check if video object exists, and pause if playing

                if (typeof cypObjectOptions[i] !== "undefined" &&
                    cypObjectOptions[i].youtubeobject !== null &&
                    typeof cypObjectOptions[i].youtubeobject.getPlayerState === "function" &&
                    cypObjectOptions[i].youtubeobject.getPlayerState() !== CleverYouTubePluginHelper.states.ended
                ) {

                    // pause video

                    cypObjectOptions[i].youtubeobject.pauseVideo();

                }

            }

        }

    },



    createVideo: function(num, callback) {

        var show_annotations = 1;



        if (cypObjectOptions[num].show_annotations == 0 || cypObjectOptions[num].show_annotations == 3) {

            show_annotations = 3;

        }

        // YouTube API Variables

        // https://developers.google.com/youtube/player_parameters

        var tempPlayer = new YT.Player("cyp-video-" + num, {

            playerVars: {

                enablejsapi: 1,

                iv_load_policy: show_annotations,

                modestbranding: 0,

                suggestedQuality: cypObjectOptions[num].quality,

                vq: cypObjectOptions[num].quality,

                theme: cypObjectOptions[num].theme,

                showinfo: 0,

                controls: cypObjectOptions[num].controls,

                wmode: 'opaque',

                autoplay: 1,

                rel: 0,

                start: cypObjectOptions[num].starttime,

                end: cypObjectOptions[num].endtime,

                autohide: cypObjectOptions[num].autohide,

                cc_load_policy: cypObjectOptions[num].closedcaptions

            },

            height: Math.round(cypObjectOptions[num].transformFactor * 18),

            width: Math.round(cypObjectOptions[num].transformFactor * 32),

            videoId: cypObjectOptions[num].videoid,

            events: {

                'onStateChange': CleverYouTubePluginHelper.onPlayerStateChange,

                'onReady': CleverYouTubePluginHelper.onPlayerReady

            }

        });

        cypObjectOptions[num].youtubeobject = tempPlayer;



        // highlight the timeseek timers
        if (jQuery(".cyp-time-seek[video='" + cypObjectOptions[num].videoid + "']").length > 0 ||
            jQuery('a[id^="CleverTimeLink-"][id$="' + cypObjectOptions[num].videoid + '"]').length > 0) {

            cypObjectOptions[num].cyptimeseektimer = CleverYouTubePluginHelper.createInterval(CleverYouTubePluginHelper.timeseek_highlight_timer, num, 50);

        }



        // remove title tag

        jQuery("#cyp-video-" + num).attr("title", "");

    },



    createInterval: function(func, param, interval) {

        setInterval(function() {

            func(param);

        }, interval);

    },



    clearTimeZoomHighlights: function() {

        jQuery(".cyp-time-seek .highlight").each(function() {

            jQuery(this).removeClass("highlight");

        });
        jQuery('a[id^="CleverTimeLink-"].highlight').removeClass('highlight');

    },



    clearTimeZoomHighlightsNow: function() {

        jQuery(".cyp-time-seek .highlight").each(function() {

            jQuery(this).addClass("no-transition").removeClass("highlight").removeClass("no-transition");

        });

        jQuery('a[id^="CleverTimeLink-"].highlight').each(function() {
            jQuery(this)
                .addClass('no-transition')
                .removeClass('highlight')
                .removeClass('no-transition');
        });

    },



    clearTimeZoomSpinners: function() {

        // to see the spinner.gif wait for a half sec before clear it

        setTimeout(function() {

            jQuery(".cyp-time-seek").removeClass("clicked");
            jQuery('.clevertimelink-spinner').remove();

        }, 500);

    },



    timeZoom: function(videoId, text, startPaused) {

        var time = 0;

        ms = 0;



        if (typeof String(text).split(".")[1] !== "undefined") {

            ms = parseInt(String(text).split(".")[1]);

        }

        text = String(text).split(":");

        mut = 1;



        while (text.length > 0) {

            time += mut * parseInt(text.pop(), 10);

            mut *= 60;

        }

        time = time + (ms / 1000);



        if (!isNaN(time)) {

            // loop through all the cyp objects

            for (var i = 1; i <= cypObjectOptions.length; i++) {

                // check if video id matches

                if (cypObjectOptions[i] != null && cypObjectOptions[i].videoid == videoId) {

                    // check if seekTo exists (means video is loaded) 

                    if (cypObjectOptions[i].youtubeobject !== null &&

                        typeof cypObjectOptions[i].youtubeobject.seekTo === "function" &&

                        cypObjectOptions[i].youtubeobject.getPlayerState() !== CleverYouTubePluginHelper.states.ended
                    ) {

                        // seek to given time

                        cypObjectOptions[i].youtubeobject.seekTo(time);



                        // pause video (resets controls)

                        cypObjectOptions[i].youtubeobject.pauseVideo();



                        // play video to trigger the showing of controls

                        if (!startPaused) {

                            CleverYouTubePluginHelper.playVideo(i);

                            CleverYouTubePluginHelper.clearTimeZoomHighlights();

                        }

                        CleverYouTubePluginHelper.clearTimeZoomSpinners();

                    } else {

                        // create video

                        CleverYouTubePluginHelper.playClicked(i);

                        // register callback in registry

                        cyp_registry["onPlay_" + i] = function(j, k) {

                            return function() {

                                CleverYouTubePluginHelper.timeZoom(j, k, startPaused);

                            };

                        }(videoId, time);

                    }

                }

            }

        }



        return false;

    },

    

    convertQuality: function (quality) {

        if (quality == "small" || quality == "medium" || quality == "large" || quality == "hd720" || quality == "hd1080") {

            return quality;

        } else {

            switch(quality) {

                case '240p': return 'small';

                case '360p': return 'medium';

                case '480p': return 'large';

                case '720p': return 'hd720';

                case '1080p': return 'hd1080';

                default: return 'default';

            }

        }

    },

    /**
     * duration duration for animation
     * $insidePopup inside popup jquery element
     * $popup   popup jquery element
     * $origin   origin jquery element
     * $wrapper popup wrapper jquery element
     */
    showPopupAnimation: function(options) {
        var duration = options.duration || 350;
        var $insidePopup = options.$insidePopup || jQuery('.cyp-popup-object-close, .cyp-popup-object-video-wrapper, .cyp-popup-video-size-wrapper');
        var $origin = options.$origin;
        var $popup = options.$popup || jQuery('.cyp-popup-object');
        var $wrapper = options.$wrapper || jQuery('.cyp-popup-object-wrapper');

        $insidePopup.fadeTo(0, 0);

        var popupWidth = $popup.width();
        var popupHeight = $popup.height();

        var originPosition = $origin.offset();
        var originDisplay = $origin.css('display');
        $origin.css('display', 'inline-block');
        var originDimensions = {
            width: $origin.outerWidth(),
            height: $origin.outerHeight(),
        };
        $origin.css('display', originDisplay);
        var originCenter = {
            x: originPosition.left + 0.5 * originDimensions.width,
            y: originPosition.top + 0.5 * originDimensions.height
        };
        
        $wrapper.data('origin-x', originCenter.x);
        $wrapper.data('origin-y', originCenter.y);

        var $window = jQuery(window);
        $popup.css({
                border: 'solid 3px black',
                background: 'transparent',
                position: 'absolute',
                top: originCenter.y - $window.scrollTop() + 'px',
                left: originCenter.x - $window.scrollLeft() + 'px',
                width: 0,
                height: 0
            })
            .animate({
                width: popupWidth + 'px',
                height: popupHeight + 'px',
                left: '50%',
                top: '50%',
                'margin-left': '-' + 0.5 * popupWidth + 'px',
                'margin-top': '-' + 0.5 * popupHeight + 'px'
            }, {
                duration: duration,
                complete: function() {
                    $popup.css({
                        border: '',
                        background: '',
                        position: '',
                        left: '',
                        top: '',
                        width: '',
                        height: '',
                        'margin-left': '',
                        'margin-top': ''
                    });
                    $insidePopup.fadeTo(duration, 1);
                    $wrapper.animate({ backgroundColor: 'rgba(0, 0, 0, 0.5)' }, duration / 2);
                }
            });
    },
    hidePopupAnimation: function(options, complete) {
        var duration = options.duration || 350;
        var $insidePopup = options.$insidePopup || jQuery('.cyp-popup-object-close, .cyp-popup-object-video-wrapper, .cyp-popup-video-size-wrapper');
        var $popup = options.$popup || jQuery('.cyp-popup-object');
        var $video = options.$video || jQuery('.cyp-popup-object-video');
        var $wrapper = options.$wrapper || jQuery('.cyp-popup-object-wrapper');

        var originCenter = {
            x: parseFloat($wrapper.data('origin-x')),
            y: parseFloat($wrapper.data('origin-y'))
        };
        var popupWidth = $popup.width();
        var popupHeight = $popup.height();
        $insidePopup.fadeTo(0, 1);
        $wrapper.animate({ backgroundColor: 'rgba(0, 0, 0, 0)' }, duration / 2);
        var $window = jQuery(window);
        $popup.css({
                border: 'solid 3px black',
                background: 'transparent',
                position: 'absolute',
                width: popupWidth + 'px',
                height: popupHeight + 'px',
                left: '50%',
                top: '50%',
                'margin-left': '-' + 0.5 * popupWidth + 'px',
                'margin-top': '-' + 0.5 * popupHeight + 'px'
            });
        $video.hide();
        $popup.animate({
                top: originCenter.y - $window.scrollTop() + 'px',
                left: originCenter.x - $window.scrollLeft() + 'px',
                width: 0,
                height: 0,
                'margin-left': 0,
                'margin-top': 0
            }, {
                duration: duration,
                easing: 'linear',
                complete: complete
            });
    },
    createPopoutVideo: function(videoid, width, quality, origin) {
        CleverYouTubePluginHelper.pauseAll();
        var transformFactor = width / 32;
        // make transformFactor <= page width / 32
        pageTF = jQuery(document).width() / 32;

        if (pageTF < transformFactor) {
            transformFactor = pageTF - 2;
            // we subtract 2 because we want to fit in the border.
        }
        quality = CleverYouTubePluginHelper.convertQuality(quality);

        if (jQuery("#cyp-popup-object-video").length == 0) {

            // create div
            var closeBtnSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAQAAAB+puRPAAAAwklEQVQoz22QuwrCUBBEJxEj0Yil4F8IFvaCvY2NRRDERkHBxt5SEASL4DflR4KIpLA+FnneG6ea3bOwOytJkgjUEJ3KjjnjWHjOsrBT4MUO38CQcmQgXArdaddwplB4XPLiQ4hr4ARPEn1uZSsycK/aucVWHUt0iQz8NrAk4RgDo+ZbJsbArEikRrBvea7/DyccSr8p8KJ+OQHPsr4yFC07GC5r0ry3Eh5HOzceDwBiXEn4nKy3CJ89cS1J4y3CyfAPLRYdoq2OAD4AAAAASUVORK5CYII=';
            var popup = 
                '<div class="cyp-popup-object-wrapper" style="background: transparent; font-size: ' + transformFactor + 'px;">' + 
                    '<div class="cyp-popup-object">' + 
                        '<div class="cyp-popup-object-close">' +
                            '<img alt="close" src="' + closeBtnSrc + '" />' +
                        '</div>' +
                        '<div class="cyp-popup-object-video-wrapper">' +
                            '<div class="cyp-popup-object-video" id="cyp-popup-object-video"></div>' +
                        '</div>' +
                        '<div class="cyp-popup-video-size-wrapper">' +
                            'Video Size: <span class="cyp-popup-video-size"></span>' +
                        '</div>' +
                    '</div>' +
                '</div>';

            // animate popup
            jQuery(popup).appendTo('body');
            CleverYouTubePluginHelper.showPopupAnimation({
                $origin: jQuery(origin),
            });

            // set click options
            jQuery(document).mouseup(function(e) {
                if (e.target.className != "cyp-popup-object") {
                    CleverYouTubePluginHelper.destroyPopopPlayer();
                }
            });

            jQuery(".cyp-popup-object-close").mousedown(function(e) {
                CleverYouTubePluginHelper.destroyPopopPlayer();
            });
        }

        // YouTube API Variables
        // https://developers.google.com/youtube/player_parameters
        var tempPlayer = new YT.Player("cyp-popup-object-video", {
            playerVars: {
                enablejsapi: 1,
                iv_load_policy: 3,
                modestbranding: 0,
                suggestedQuality: quality,
                vq: quality,
                theme: "dark",
                showinfo: 0,
                controls: true,
                wmode: 'opaque',
                autoplay: 1,
                rel: 0,
                start: 0,
                end: 0,
                autohide: 1
            },
            height: Math.round(transformFactor * 18),
            width: Math.round(transformFactor * 32),
            videoId: videoid,
            events: {
                'onStateChange': CleverYouTubePluginHelper.onPopupPlayerStateChange
            }
        });
        CleverYouTubePluginHelper.updatePopupSizeLabel();
        cyppopupobject = tempPlayer;

        // Bind esc key
        jQuery(document).on("keyup.cyp-popup-esc", function(e) {
            if (e.keyCode == 27) {
                CleverYouTubePluginHelper.destroyPopopPlayer();
            }
        });
    },



    onPopupPlayerStateChange: function(newState) {

        if ((newState.data == CleverYouTubePluginHelper.states.ended) ||
            (newState.data == CleverYouTubePluginHelper.states.cued)
        ) {

            var theNameOfTheDiv = newState.target.a.id;

            // free video player from memory

            newState.target.destroy();

            CleverYouTubePluginHelper.destroyPopopPlayer();

        }

        CleverYouTubePluginHelper.updatePopupSizeLabel();

    },



    destroyPopopPlayer: function() {
        // unbind esc key
        jQuery(document).unbind("keyup.cyp-popup-esc");

        // remove popup
        CleverYouTubePluginHelper.hidePopupAnimation({}, function() {
            jQuery(".cyp-popup-object-wrapper").remove();
            jQuery('.cyp-popup-video-size-wrapper').hide();
        });
    },



    getElementNumberFromNewState: function(newState) {

        var target = newState.target;

        var id = false;

        

        for (var i = 65; i <= 90; i++) {

            var letter = String.fromCharCode(i).toLowerCase();

            

            if (typeof target[letter] !== 'undefined' && 

            typeof target[letter].id !== 'undefined') {

                id = target[letter].id;

                break;

            }

        }

        

        if (id) {

            return parseInt(id.replace(/[^0-9]/g, ''));

        } else {

            console.error('Unable to determine video ID from target', target);

        }

    },

    getBeforeVideoThumbnail: function (num) {
        var selector = ".cyp-video-object-holder[data-count=" + num + "] " +
            ".cyp-video-object-before-image " + 
            ".cyp-video-object-video-container " +
            "video";
        return jQuery(selector);
    },
    
    startBeforeVideoThumbnail: function (num) {
        var $video = CleverYouTubePluginHelper.getBeforeVideoThumbnail(num);

        if ($video.length) {
            var video = $video[0];
            video.play();
            $video.parent().show();
        }
    },

    stopBeforeVideoThumbnail: function (num) {
        var $video = CleverYouTubePluginHelper.getBeforeVideoThumbnail(num);

        if ($video.length) {
            var video = $video[0];
            video.pause();
            video.currentTime = 0;
        }
    },

    onPlayerStateChange: function(newState) {
        if ((newState.data == CleverYouTubePluginHelper.states.ended) ||
            (newState.data == CleverYouTubePluginHelper.states.cued)
        ) {

            var theNumberOfTheDiv = CleverYouTubePluginHelper.getElementNumberFromNewState(newState);

            CleverYouTubePluginHelper.videoEnded(theNumberOfTheDiv, newState);
            // free video player from memory

            cypObjectOptions[theNumberOfTheDiv].youtubeobject = null;

            newState.target.destroy();

        } else if (newState.data == CleverYouTubePluginHelper.states.playing) {
            // video is playing
            var number = CleverYouTubePluginHelper.getElementNumberFromNewState(newState);
            CleverYouTubePluginHelper.lastPlayClicked = number;

            if (newState.target.j) {
                if (typeof cyp_registry["onPlay_" + number] === "function") {
                    cyp_registry["onPlay_" + number].call();
                    delete cyp_registry["onPlay_" + number];
                }

                // try to force quality
                cypObjectOptions[number].youtubeobject.setPlaybackQuality(cypObjectOptions[number].quality);
            }
            CleverYouTubePluginHelper.playCallback(number);
            CleverYouTubePluginHelper.stopBeforeVideoThumbnail(number);

        } else if (newState.data == CleverYouTubePluginHelper.states.paused) {

            // video is paused

            if (newState.target.d) {

                var number = CleverYouTubePluginHelper.getElementNumberFromNewState(newState);

                CleverYouTubePluginHelper.timeseek_highlight_timer(number);

            }

        }

    },



    videoEnded: function(num) {

        var showBefore = false;

        

        // Set height
        cypObjectOptions[num].playCallbackPlayed = false;

        CleverYouTubePluginHelper.tweakStaticBar(num, false);



        // reset highlight timer

        clearTimeout(cypObjectOptions[num].cyptimeseektimer);

        cypObjectOptions[num].cyptimeseektimer = null;



        if (cypObjectOptions[num].hasafterHTML) {

            // after html

            jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-html").show();

        } else {

            if (cypObjectOptions[num].showrepeatbutton) {

                // show repeat button

                jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-repeat-button").show();

                CleverYouTubePluginHelper.fixPosition();

                showBefore = true;

                var isMSIE = /*@cc_on!@*/ 0;



                if (!isMSIE) {

                    jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-repeat-button").unbind("mousedown").off("mousedown").on("mousedown", function() {

                        CleverYouTubePluginHelper.playClicked(num);

                    });

                }

            }

        }



        if (cypObjectOptions[num].afterpic) {

            // show after pic

            jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-after-image").show();

            showBefore = false;

        }

        

        if (!cypObjectOptions[num].afterpic && !cypObjectOptions[num].hasafterHTML && !cypObjectOptions[num].showrepeatbutton) {

            showBefore = true;

        }

        

        if (showBefore) {
            CleverYouTubePluginHelper.showBefore(num);

        }

    },

    showBefore: function (num) {
        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-image").show();
        jQuery(".cyp-video-object-holder[data-count=" + num + "] .cyp-video-object-before-image .cyp-video-object-image-container").show();
        CleverYouTubePluginHelper.startBeforeVideoThumbnail(num);
    },



    onPlayerReady: function(event) {

        var num = CleverYouTubePluginHelper.getElementNumberFromNewState(event);

        
        if (cypObjectOptions[num].autoplay) {
            event.target.mute();
        } else {
            if (cypObjectOptions[num].forceVolume) {
    
                if (event.target.isMuted()) {
    
                    event.target.unMute();
    
                }
    
                
    
                if (event.target.getVolume() < 50) {
    
                    
    
                    event.target.setVolume(65);
    
                }
    
            }
        }


        if (cypObjectOptions[num].interruptNext) {
            cypObjectOptions[num].youtubeobject.stopVideo();
        }

    },



    showSonar: function() {

        if ((/iPhone|iPod|iPad|Android|BlackBerry/).test(navigator.userAgent)) {

            // don't show sonar since device is mobile

            jQuery(".cyp-video-object-sonar-inner").remove();

        } else {

            jQuery(".cyp-video-object-sonar-inner").show();

        }

    },



    timeseek_highlight_timer: function(num) {

        current_time = 0;

        video_id = cypObjectOptions[num].videoid;



        // get current time

        if (cypObjectOptions[num].youtubeobject != null && typeof cypObjectOptions[num].youtubeobject.getCurrentTime === "function") {

            playerState = cypObjectOptions[num].youtubeobject.getPlayerState();



            if (playerState == CleverYouTubePluginHelper.states.unstarted ||
                playerState == CleverYouTubePluginHelper.states.ended ||
                playerState == CleverYouTubePluginHelper.states.paused ||
                playerState == CleverYouTubePluginHelper.states.cued
            ) {

                // dont highlight if not unstarted, ended, paused, or queued

                CleverYouTubePluginHelper.clearTimeZoomHighlights();

                return;

            }

            current_time = cypObjectOptions[num].youtubeobject.getCurrentTime();

        }



        // loop through all .cyp-time-seek

        jQuery(".cyp-time-seek[video='" + video_id + "']").each(function() {
            var $element = jQuery(this);
            var $span =  $element.find('span');
            var time =  $element.text();
            toggleHighlight($span, time);
        });
        
        jQuery('a[id^="CleverTimeLink-"][id$="' + video_id + '"]').each(function() {
            var $element = jQuery(this);
            var id = $element.attr('id');
            var timelink = CleverYouTubePluginHelper.parseTimeLinkId(id);
            toggleHighlight($element, timelink.time);
        });

        function toggleHighlight($element, time) {
            var seektime = getSeektime(time);
            var epsilon = 3.0;
            var diff = current_time - seektime;

            if (isNumber(seektime) && diff > 0 && diff <= epsilon) {
                $element.addClass('highlight');
            } else {
                $element.removeClass('highlight');
            }

            function isNumber(n) {
                return !isNaN(n);
            }
            function getSeektime(time) {
                var seektime = 0;
                var epsilon = 3.0; // this is the margin of error for the highlight timer in seconds
                var millisecond = time.split('.')[1];
                time = time.split(':');
                var mut = 1;

                while (time.length > 0) {
                    seektime += mut * parseInt(time.pop(), 10);
                    mut *= 60;
                }

                if (typeof millisecond === 'string') {
                    seektime += parseInt(millisecond, 10) / 1000;
                }
                
                return seektime;
            }
        }
    },



    animatedButtons: function() {

        jQuery(".cyp-video-object-holder").each(function(i, j) {

            var $element = jQuery(this);

            var count = $element.attr("data-count");



            if (cypObjectOptions[count].animatedbutton) {

                $element.find(".img_cyp_playbutton").throb();

            }

        });

    },

    

    resizeDescription: function() {

        setup();

        return;

        

        function setup() {

            jQuery(".cyp-video-object-holder").each(function(i, j) {

                var $element = jQuery(this);

                var count = $element.attr("data-count");

                

                if (cypObjectOptions[count].hasDescription) {

                    var $button = jQuery('.cyp-video-object-play-button', $element);

                    var $img = jQuery('.img_cyp_playbutton', $button);

                    var startHeight = $img.data('start-height');

                    var height = (startHeight ? startHeight : $button.height());

                    var margin = (cypObjectOptions[count].animatedbutton ? 0 : 10);

                    var $description = jQuery('.cyp-video-object-description', $element);

                    

                    if (cypObjectOptions[count].descriptionPosition === 'top') {

                        //var buttonTop = $button.position().top - 0.5 * $button.height();

                        var buttonBottom = $button.position().top - $button.outerHeight(true);

                        var buttonHeight = (startHeight ? startHeight : $img.height());

                        var minBottom = buttonBottom + buttonHeight + margin;

                        $description.css('bottom', ''); // remove current bottom first so that we can calculate it correctly

                        var currentBottom = $element.outerHeight(true) - $description.outerHeight(true); 

                        

                        if (currentBottom < minBottom) {

                            $description.css('bottom', minBottom);

                        } else {

                            $description.css('bottom', '');

                        }

                    } else {

                        var minTop = $button.position().top + height + margin;

                        var currentTop = $description.css('top', '').position().top; // remove current top first so that we can calculate it correctly

                        

                        if (currentTop < minTop) {

                            $description.css('top', minTop);

                        } else {

                            $description.css('top', '');

                        }

                    }

                }

            });

        }

    },

    

    fixPosition: function() {

        jQuery(".cyp-video-object-holder").each(function(i, j) {

            var $element = jQuery(this);

            var count = $element.attr("data-count");



            if (!cypObjectOptions[count].animatedbutton) {

                var $img = $element.find(".img_cyp_playbutton");

                $img.css('margin-left', -0.5 * $img.width());

                $img.css('margin-top', -0.5 * $img.height());

            }

            var $repeatImg = $element.find(".cyp-video-object-repeat-button img");

            $repeatImg.css('margin-left', -0.5 * $repeatImg.width());

            $repeatImg.css('margin-top', -0.5 * $repeatImg.height());

        });

    },

    

    setupHeartsEffect: function() {

        jQuery('.cyp-video-object-holder').each(function(i, j) {

            var $element = jQuery(this);

            var count = $element.attr("data-count");



            if (cypObjectOptions[count].has_hearts) {

                $element.find('.img_cyp_playbutton').heartsEffect({

                    center: !cypObjectOptions[count].hasDescription

                });

            }

        });

    },

    autoplay: function() {
        // Run through the array of videos, and play the ones that have "autoplay" on.
        if (typeof cypObjectOptions != "undefined") {
            cypobjectlength = cypObjectOptions.length;

            for (var i = 1; i < cypobjectlength; i++) {
                if (cypObjectOptions[i] && cypObjectOptions[i].autoplay == true) {
                    CleverYouTubePluginHelper.playClicked(i);
                }
            }
        }
    },

    handlePopoutLinks: function() {
        var match = 'CleverPopOut-';
        var selector = 'a[id^="' + match + '"]';
        jQuery(selector).click(onClick);
        jQuery(selector.toLowerCase()).click(onClick);

        function onClick() {
            var id = jQuery(this).attr('id').substring(match.length);

            if (id) {
                CleverYouTubePluginHelper.createPopoutVideo(id, 480, 'default', this);
            }

            return false;
        }
    },

    updatePopupSizeLabel: function() {
        var $video = jQuery('#cyp-popup-object-video');

        if ($video && $video.length) {
            jQuery('.cyp-popup-video-size-wrapper').show();
            var width = $video.width();
            var height = $video.height();
            jQuery('.cyp-popup-video-size').text(width + 'x' + height);
        }
    },

    parseTimeLinkId: function(id) {
        var regex = /CleverTimeLink\-([0-9:.]+)\-([^#\&\?]+)/;
        var matches = id.match(regex);

        if (matches && matches.length === 3) {
            var time = matches[1];
            var videoId = matches[2];

            return {
                time: time,
                videoId: videoId
            };
        }
    },

    handleTimeLinks: function() {
        var selector = 'a[id^="CleverTimeLink-"]';
        jQuery(selector).click(onClick);

        function onClick() {
            var $this = jQuery(this);
            var id = $this.attr('id');
            var timelink = CleverYouTubePluginHelper.parseTimeLinkId(id);

            if (timelink) {
                $this.after('<span class="clevertimelink-spinner"></span>');
                CleverYouTubePluginHelper.clearTimeZoomHighlightsNow();
                CleverYouTubePluginHelper.timeZoom(timelink.videoId, timelink.time, false);
            }

            return false;
        }
    },
    
    interupt: function (num) {
        if (typeof cypObjectOptions !== 'undefined' &&
            typeof cypObjectOptions[num] !== 'undefined'
        ) {
            if (!!cypObjectOptions[num].youtubeobject &&
                typeof cypObjectOptions[num].youtubeobject.getPlayerState === "function" &&
                cypObjectOptions[num].youtubeobject.getPlayerState() !== CleverYouTubePluginHelper.states.ended
            ) {
                if (cypObjectOptions[num].youtubeobject.getPlayerState() !== CleverYouTubePluginHelper.states.paused) {
                    if (!CleverYouTubePluginHelper.lastInterrupted || num === CleverYouTubePluginHelper.lastPlayClicked) {
                        CleverYouTubePluginHelper.lastInterrupted = num;
                    }
                }
                cypObjectOptions[num].youtubeobject.pauseVideo();
    
            } else {
                cypObjectOptions[num].interruptNext = true;
            }
        }
    },

    interruptAll: function() {
        CleverYouTubePluginHelper.lastInterrupted = false;

        if (typeof cypObjectOptions !== 'undefined') {
            for (var i = 1; i <= cypObjectOptions.length; i++) {
                CleverYouTubePluginHelper.interupt(i);
            }
        }
    },

    resume: function (num) {
        CleverYouTubePluginHelper.playClicked(num);
    },

    resumeLast: function() {
        if (CleverYouTubePluginHelper.lastInterrupted) {
            CleverYouTubePluginHelper.resume(CleverYouTubePluginHelper.lastInterrupted);
        }

        if (typeof cypObjectOptions !== 'undefined') {
            for (var i = 1; i <= cypObjectOptions.length; i++) {
                if (typeof cypObjectOptions[i] !== 'undefined') {
                    cypObjectOptions[i].interruptNext = false;
                }
            }
        }
    },
    
    states: {
        'unstarted': -1,
        'ended': 0,
        'playing': 1,
        'paused': 2,
        'buffering': 3,
        'cued': 5
    }

};

function cyp_interrupt() {
    CleverYouTubePluginHelper.interruptAll();
}

function cyp_resume() {
    CleverYouTubePluginHelper.resumeLast();
}



var CleverYouTubePluginObject = function(newelement) {

    var element = jQuery(newelement);

    var count = element.attr("data-count");

    var isResponsive = cypObjectOptions[count].responsive;

    init();



    function init() {
        CleverYouTubePluginHelper.checkResize();
        cypObjectOptions[count].quality = CleverYouTubePluginHelper.convertQuality(cypObjectOptions[count].quality);

        // Change quality if needed
        if (isResponsive) {
            the_width = element.find(".cyp-video-object").width();

            switch (cypObjectOptions[count].quality) {
                case "small":
                    break;
                case "medium":
                    if (the_width < 260) {
                        cypObjectOptions[count].quality = "small";
                    }
                    break;
                case "large":
                    if (the_width < 260) {
                        cypObjectOptions[count].quality = "small";
                    } else if (the_width < 470) {
                        cypObjectOptions[count].quality = "medium";
                    }
                    break;
                case "hd720":
                    if (the_width < 260) {
                        cypObjectOptions[count].quality = "small";
                    } else if (the_width < 470) {
                        cypObjectOptions[count].quality = "medium";
                    } else if (the_width < 700) {
                        cypObjectOptions[count].quality = "large";
                    }
                    break;
                case "hd1080":
                    if (the_width < 260) {
                        cypObjectOptions[count].quality = "small";
                    } else if (the_width < 470) {
                        cypObjectOptions[count].quality = "medium";
                    } else if (the_width < 700) {
                        cypObjectOptions[count].quality = "large";
                    } else if (the_width < 1070) {
                        cypObjectOptions[count].quality = "hd720";
                    }
                    break;
                case "highres":
                    if (the_width < 260) {
                        cypObjectOptions[count].quality = "small";
                    } else if (the_width < 470) {
                        cypObjectOptions[count].quality = "medium";
                    } else if (the_width < 700) {
                        cypObjectOptions[count].quality = "large";
                    } else if (the_width < 1070) {
                        cypObjectOptions[count].quality = "hd720";
                    } else if (the_width >= 1070) {
                        cypObjectOptions[count].quality = "hd1080";
                    }
                    break;
                case "default":
                    cypObjectOptions[count].quality = "default";
                    break;
                default:
                    cypObjectOptions[count].quality = "medium";
            }
        }

        jQuery(".cyp-video-object-holder[data-count=" + count + "] .cyp-video-object")
            .attr("onclick", "")
            .unbind("mousedown")
            .off("mousedown")
            .click(function() {
                CleverYouTubePluginHelper.playClicked(count);
            });

        // Fix the images in the cyp-video-object-image-container
        CleverYouTubePluginHelper.resetImageContainers(count);
    }

    

    function playClicked() {

        CleverYouTubePluginHelper.playClicked(count);

    }

};







jQuery(document).ready(function() {

    CleverYouTubePluginHelper.loadYouTubeiFrameAPI();
    CleverYouTubePluginHelper.handlePopoutLinks();
    CleverYouTubePluginHelper.handleTimeLinks();
    jQuery(window).resize(CleverYouTubePluginHelper.updatePopupSizeLabel);

    window.onYouTubePlayerAPIReady = function (id) {
        CleverYouTubePluginHelper.resizeDescription();
        CleverYouTubePluginHelper.animatedButtons();
        CleverYouTubePluginHelper.removeWrappers();
        CleverYouTubePluginHelper.resetPadding();
        CleverYouTubePluginHelper.hideBackPanes();
        CleverYouTubePluginHelper.checkResize();
        CleverYouTubePluginHelper.setupHeartsEffect();
        CleverYouTubePluginHelper.autoplay();

        jQuery(".cyp-video-object-after-html").hide();
        jQuery(".cyp-video-object-after-image").hide();
        
        jQuery('.cyp-description-close').click(function () {
            jQuery(this).parent('.cyp-video-object-description').hide();
        });
        jQuery('.cyp-video-object-description').scroll(function() {
            var $this = jQuery(this);
            $this.children('.cyp-description-close').css('top', $this.scrollTop() + 2);
        });
    };
});



jQuery(window).on("load", function() {

    // Check Queue

    if (typeof cleveryoutube_queue != "undefined") {

        for (var i = 0; i < cleveryoutube_queue.length; i++) {

            CleverYouTubePluginHelper.playClicked(cleveryoutube_queue[i]);

        }

    }



    // Remove loading indicator & onmouseup method

    jQuery(".cyp-video-object-play-button-loading").remove();

    jQuery(".cyp-video-object-play-button").attr("onmouseup", "");



    // Responsive

    jQuery(window).resize(CleverYouTubePluginHelper.checkResize);

    var cypresponsivetimer = setInterval(CleverYouTubePluginHelper.checkResize, 10 * 1000);

    CleverYouTubePluginHelper.proccessObjects();

    CleverYouTubePluginHelper.nonResponsiveSizeReset();

    CleverYouTubePluginHelper.resetAllImages();

    CleverYouTubePluginHelper.showSonar();

    CleverYouTubePluginHelper.checkResize();



    jQuery(".cyp-time-seek").click(function(event) {
        paused = jQuery(event.target).hasClass("pause");

        height = jQuery(this).height();

        jQuery(this).addClass("clicked");

        jQuery(this).find(".cyp-spinner").css({

            "height": (0.8 * height) + "px"

        });

        target = jQuery(this).attr("video");

        time = jQuery(this).text();


        if (paused) {

            CleverYouTubePluginHelper.timeZoom(target, time, true);

            return;

        }

        // clear all other highlights

        CleverYouTubePluginHelper.clearTimeZoomHighlightsNow();

        CleverYouTubePluginHelper.timeZoom(target, time, false);

    });

});
// source --> https://www.staging.boldinternet.co.uk/wp-content/plugins/clever-youtube-plugin/cbpFWTabs.js?ver=4.243 
/**
 * cbpFWTabs.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2014, Codrops
 * http://www.codrops.com
 */
;( function( window ) {
	
	'use strict';

	function extend( a, b ) {
		for( var key in b ) { 
			if( b.hasOwnProperty( key ) ) {
				a[key] = b[key];
			}
		}
		return a;
	}

	function CBPFWTabs( el, options ) {
		this.el = el;
		this.options = extend( {}, this.options );
  		extend( this.options, options );
  		this._init();
	}

	CBPFWTabs.prototype.options = {
		start : 0
	};

	CBPFWTabs.prototype._init = function() {
		// tabs elemes
		this.tabs = [].slice.call( this.el.querySelectorAll( 'nav > ul > li' ) );
		// content items
		this.items = [].slice.call( this.el.querySelectorAll( '.cyp-tabs-content > section' ) );
		// current index
		this.current = -1;
		// show current content item
		this._show();
		// init events
		this._initEvents();
	};

	CBPFWTabs.prototype._initEvents = function() {
		var self = this;
		this.tabs.forEach( function( tab, idx ) {
			tab.addEventListener( 'click', function( ev ) {
				ev.preventDefault();

				if (!this.dataset.disabled) {
					self._show( idx );
				}
			} );
		} );
	};

	CBPFWTabs.prototype._show = function( idx ) {
		if( this.current >= 0 ) {
			this.tabs[ this.current ].className = '';
			this.items[ this.current ].className = '';
		}
		// change current
		this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
		this.tabs[ this.current ].className = 'tab-current';
		this.items[ this.current ].className = 'content-current';
	};

	// add to global namespace
	window.CBPFWTabs = CBPFWTabs;

})( window );
// source --> https://www.staging.boldinternet.co.uk/wp-content/plugins/clever-youtube-plugin/cyp-tabs.js?ver=4.243 
;(function(window, $) {
	'use strict';
    
    $(document).ready(function() {
        applyNumbers();
        var dontClickAudio = window.cyp.audio.load('sounds/dont-click.mp3');
        $('.cyp-tabs').each(function () {
            var $this = $(this);
            var selected = $this.data('selected');
            new CBPFWTabs(this, { start: selected });
        });
        $('.cyp-tabs nav > ul > li').click(function (e) {
            var $this = $(this);

            if ($this.data('disabled')) {
                var $span = $this.find('a > span');

                if ($span.is(':visible')) {
                    $span.effect('shake', { times: 2, distance: 10 }, 500);
                } else {
                    $this.find('a')
                        .effect('shake', { times: 2, distance: 5 }, 500);
                }
                dontClickAudio.play();
            } else {
                CleverYouTubePluginHelper.pauseAll();
                CleverYouTubePluginHelper.checkResize();
                CleverYouTubePluginHelper.animatedButtons();
            }
        });
    });
    $(window).resize(function () {
        applyNumbers();
    });

    function applyNumbers() {
        var $collections = $('.cyp-tabs');
        $collections.removeClass('cyp-tabs-numbers');
        $collections.each(function () {
            var $this = $(this);
            var maxHeight = 0;
            
            $this.find('nav > ul > li').each(function () {
                var height = $(this).outerHeight();
                maxHeight = Math.max(height, maxHeight);
            });
            
            if (maxHeight > 160) {
                $this.addClass('cyp-tabs-numbers');
            }
        });
    }

})(window, jQuery);