/**
 * mediabar jQuery plugin
 */
(function ($) {

    // limited value helper
    var limit = function (value, min, max) {
        return Math.min(Math.max(value, min), max);
    };

    /**
    * The Carousel class transforms a list of floated items into a scrollable carousel.
    *
    * @class LBi.Carousel
    * @constructor
    * @param {Node} node
    * @param {Object} settings See LBi.Carousel.Defaults
    */
    var Mediabar = function (node, settings) {

        this.isIE = /msie/i.test(navigator.userAgent);
        this.isMobile = ($(window).width() < 640);

        this.settings       = $.extend({}, Mediabar.Defaults, settings);
        this.root           = $(node);
        this.viewInserted   = false;
        this.init();
        this.clip.show();
        this.setupViews();
        this.setupNavigation();
        this.setupTips();
        this.setupControls();
        this.setupVideos();
        this.setupHitArea();
        this.initDragging();
        if (this.isMobile) {
            var mobileTopNavHeight = $('#header-mobile').outerHeight(true);
            this.mobileScrollTopRoot = this.root.parent().offset().top - mobileTopNavHeight + 10;
            this.setupMobile();
        }

        if (location.hash.indexOf('#!') > -1) {
          this.hashChanged();
        }
    };

    Mediabar.prototype = {

        constructor: Mediabar,

        /**
        * Initializes important settings & nodes
        * @private
        */
        init: function () {

            var settings    = this.settings;
            var isHovered   = false;
            var self        = this;

            $(window).hashchange(this.hashChanged.bind(this));

            this.clip   = this.root.find(settings.clipSelector);
            this.items  = this.root.find(settings.itemSelector);
            this.view   = this.root.find(settings.viewSelector);

            if(!this.view.length) {
                this.view = $('<div></div>');
                this.viewInserted = true;
            }

            this.originalHeight = 0;
            this.length         = this.items.length;
            this.index          = 0;
            this.position       = 0;
        },

        setupControls: function() {
            var self            = this;
            this.fadingControls = this.root.find('a.control');

            if (!this.isMobile) {
                this.root.hover(
                    function(e) {
                        if (self.root.hasClass('started')) {
                            self.isHovered = true;
                            self.fadingControls.fadeIn();
                        }
                    },
                    function(e) {
                        if (self.root.hasClass('started')) {
                            self.isHovered = false;
                            self.fadingControls.fadeOut();
                        }
                    }
                );
            }

            this.nextButton     = this.root.find('a.next');
            this.prevButton     = this.root.find('a.prev');
            this.startButton    = this.root.find('a.start');
            this.closeButton    = this.root.find('a.close');

            $('#overlay').click(this.overlayClicked.bind(this));
        },

        setupVideos: function() {
            var self = this;
            var l = this.items.length;
            var videoNode;
            this.videos = new Array(l);
            var i;
            for (i=0; i < l; i++) {
                videoNode = $(this.items[i]).find('video')[0];
                if (!videoNode) {
                    continue;
                }

                // init mediaplayer for the <video>
                this.videos[i] = new MediaElementPlayer(videoNode, {
                    success: function(media) {
                        media.addEventListener('play', function() {
                            window.location.hash = '#!slide-'+self.index;
                        }, true);
                        media.addEventListener('paused', function() {
                            media.currentTime = 0;
                        }, true);
                    }
                });
            }
        },

        setupViews: function() {
            // Set li width on mobile
            if (this.isMobile) {
                this.items.css({
                    width: $(window).width() + 'px'
                });
            }

            var total = 0;
            var width = 0;

            this.view.css({
                position: 'relative',
                overflow: 'hidden'
            });

            var l = this.items.length;
            var i;
            for (i = 0; i < l; i++) {
                var item = this.items[i];
                item.id = "slide-"+i;
                width = Math.max(width, item.offsetWidth);
                total += width;
            }

            this.clip.css({
                position: 'absolute',
                width: total + 'px',
                height: '100%',
                left: 0,
                top: 0
            });

            if (this.viewInserted) {
                this.view.append(this.clip);
                this.root.append(this.view);
            }

            if (this.originalHeight == 0) {
                this.originalHeight = this.view.height();
            }
            this.viewportWidth  = this.view[0].offsetWidth;  // width of viewport (visible area)
            this.itemsWidth     = this.clip[0].offsetWidth;  // width of OL (all LI's together)
            this.maxLeftPos     = this.viewportWidth - this.itemsWidth; // 'max scroll' for slider
        },

        setupNavigation: function() {
            var nav = $('<ol class="nav items"></ol>');
            this.nav = nav;
            this.root.append(this.nav);

            var l = this.items.length;
            var chapters = this.clip.find('li[data-new-chapter]');
            var tooltip;
            var i;

            if (chapters.length === 0) {
                for (i = 0; i < l; i++) {
                    tooltip = this.items.eq(i).attr('data-tooltip');
                    nav.append('<li class="item"><a data-tooltip="' + tooltip + '" href="#!slide-'+i+'"></a></li>');
                }
            } else {
                chapters.each(function() {
                    nav.append('<li class="chapter"><strong>'+$(this).attr("data-new-chapter")+'</strong><ol></ol></li>');
                });
                var chapterIndex = 0;
                var container = this.nav.find('li.chapter:first').addClass('current').find('ol');
                for (i = 0; i < l; i++) {
                    if ($(this.items[i]).attr("data-new-chapter")) {
                        container = nav.find('li.chapter:eq('+chapterIndex+') ol:first');
                        chapterIndex++;
                    }

                    tooltip = this.items.eq(i).attr('data-tooltip');
                    container.append('<li class="item"><a data-tooltip="' + tooltip + '" href="#!slide-'+i+'"></a></li>');
                }
            }

            this.nav.find('li.item:first').addClass("active");
            this.nav.find('ol:last').addClass("last");
        },

        setupTips: function() {
            this.tips = new MediaTips({
                template: '<div class="tooltip"><span class="body"/><div class="arrow"></div></div>',
                body: 'span.body',
                content: 'data-tooltip',
                target: document.body
            });

            this.tips.add(this.nav.find('li a'));
        },

        hashChanged: function(e) {
            var hash = window.location.hash;
            if (hash.indexOf('slide-') < 0) {
                this.stop();
                return;
            }
            var slideIndex = this.getIndexFromHash();
            this.animate(slideIndex);
            this.setFinished();
        },

        getIndexFromHash: function() {
            var hash = window.location.hash;
            var slideIndex = 0;
            try {
                slideIndex = parseInt(hash.split('-').pop(), 10);
            } catch (ex) {

            }
            return slideIndex;
        },

        pauseVideoAtIndex: function(index) {
            // Matt IE hack: onYouTubePlayerAPIReady never happens
            if(this.isIE && !window.vidsIndexed){
                onYouTubePlayerAPIReady();
            }

            if (this.videos[index] !== undefined) {
                this.videos[index].pause();
            }else if (window.youtubePlayers[index] !== undefined) {
                window.youtubePlayers[index].pauseVideo();
            }else if (window.vimeoPlayers[index] !== undefined) {
                window.vimeoPlayers[index].api('pause');
            }
        },

        playVideoAtIndex: function(index) {
            if (this.videos[index] !== undefined) {
                this.videos[index].play();
            }
            if (window.youtubePlayers[index] !== undefined) {
                window.youtubePlayers[index].playVideo();
            }
            if (window.vimeoPlayers[index] !== undefined) {
                window.vimeoPlayers[index].api('play');
            }
        },

        stopEmbeddedVideos: function() {
            var i, l = window.youtubePlayers.length;
            for (i = 0; i < l; i++) {
                try {
                    window.youtubePlayers[i].pauseVideo();
                } catch (ex) {}
            }
            var ii, ll = window.vimeoPlayers.length;
            for (ii = 0; ii < ll; ii++) {
                try {
                    window.vimeoPlayers[ii].api('pause');
                } catch (ex) {}
            }
        },

        /**
        * Animates the carousel items. The index parameter indicates the item that will be moved
        * to the beginning (left side) of the carousel. This method is called automatically by the
        * previous and next methods, and the auto scroll feature.
        *
        * @param {number} index Index of the item to move to the front.
        */
        animate: function (index) {

            if (index == 0) {
              this.stop();
            } else if (!this.root.hasClass("started")) {
              this.start();
            }

            // pause current video, if any
            this.pauseVideoAtIndex(this.index);

            var last = index == (this.length -1);
            this.root.toggleClass('last-slide', last);

            var l        = this.items.length;
            var settings = this.settings;
            var pos      = limit(index, 0, l);
            var target   = this.items[pos]; // LI at specified index
            var offset   = this.getClipLeftOffset(index);

            var self = this;
            this.clip.animate(
                {left: offset},
                500,
                function() {
                    // play video, if this slide has a video
                    // self.playVideoAtIndex(index);
                    if (index > 0) {
                        self.prevButton[0].href = "#!slide-"+(index-1);
                    }
                    if (index < l-1) {
                        self.nextButton[0].href = "#!slide-"+(index+1);
                    }
                    // Reset the view height on mobile
                    if (self.isMobile) {
                        self.resetViewHeight();
                        $('html,body').animate(
                            {scrollTop: self.mobileScrollTopRoot},
                            500
                        );
                    }
                }
            );

            this.nav.find('li.item.active').removeClass("active").parents('li.chapter').removeClass('current');
            this.nav.find('li.item:eq('+index+')').addClass("active").parents('li.chapter').addClass('current');

            if (offset !== this.position) {
                this.position   = offset;
                this.index      = pos;
            }

            // Stop YouTube and/or Vimeo videos
            this.stopEmbeddedVideos();

        },

        getClipLeftOffset: function(index) {
            var l        = this.items.length;
            var pos      = limit(index, 0, l);
            var target   = this.items[pos]; // LI at specified index
            var offset   = limit(-target.offsetLeft, this.maxLeftPos, 0);
            return offset;
        },

        stop: function() {
            this.startButton.get(0).hash = "#!slide-" + Math.max(1, this.index);
            this.fadingControls.hide();
            this.pauseVideoAtIndex(this.index);
            this.shrinkViewPort(function() {
                $.scrollTo({top: 0, left:0}, 1200);
            });
            this.root.removeClass("started").addClass("stopped");
            this.root.removeClass('stopped-slide-text');

            var currentSlide = $(this.items[this.index]);

            // Stop YouTube and/or Vimeo videos
            this.stopEmbeddedVideos();
        },

        start: function() {
            if(this.startButton.get(0).innerHTML.indexOf("Start") > -1){
                this.startButton.get(0).innerHTML = "Continue >";
            }
            this.expandViewPort();
            this.root.addClass("started").removeClass("stopped");
            this.playVideoAtIndex(this.index);
        },

        /**
        * make the viewport bigger
        * @method expandViewPort
        */
        expandViewPort: function() {
            var self = this;
            this.view.animate(
                {height:this.settings.expandedHeight + "px"},
                500,
                function() {
                    $('#overlay').css({height: self.getDocumentHeight() + "px"}).fadeIn();
                    self.root.parent().css(
                        {
                            border: "10px solid #333",
                            position: 'relative',
                            margin: "0 -10px",
                            "z-index": 9999
                        }
                    );
                    if (self.isMobile) {
                        self.closeButton.fadeIn();
                        self.resetViewHeight();
                    } else {
                        $.scrollTo(self.root.parent(), 500, {offset: {top: "-10px"}});
                        self.fadingControls.fadeIn();
                    }
                }
            );
        },

        /**
        * Make the viewport smaller
        * @method shrinkViewPort
        */
        shrinkViewPort: function(callback) {
            this.view.animate({height:this.originalHeight + 'px'}, 500, function() {
                if (callback) {
                    callback.call();
                }
            });
            this.root.parent().css({
                "border-width": 0,
                "margin": 0,
                "z-index": 0
            });
            $('#overlay').hide();
        },

        /**
        * Goes backward in the carousel, moving it by the amount of items as specified in the settings' "scroll" property.
        * @method previous
        */
        previous: function (e) {
            if (this.index > 0)  {
                //this.animate(this.index - this.settings.scroll);
                window.location.hash = '#!slide-' + (this.index - this.settings.scroll);
            }
            try {
                e.preventDefault();
            } catch (ex) { }
        },

        /**
        * Goes forward in the carousel, moving it by the amount of items as specified in the settings' "scroll" property.
        * @method next
        */
        next: function (e) {
            if (this.index+1 < this.items.length)  {
                //this.animate(this.index + this.settings.scroll);
                window.location.hash = '#!slide-' + (this.index + this.settings.scroll);
            }
            try {
                e.preventDefault();
            } catch (ex) { }
        },


        overlayClicked:function() {
            if (this.root.hasClass("started")) {
                window.location.hash = "#!close";
            }
        },

        /**
         * Calculates the page's height.
         * This method is called via toggle, and should not be called manually.
         * @private
         */
        getDocumentHeight:function() {
            var height = document.documentElement.scrollHeight || document.body.scrollHeight;
            var winHeight = window.innerHeight || document.documentElement.clientHeight;
            return (height < winHeight)? winHeight : height;
        },

        setupHitArea: function(){
            if(this.touch){
                this.hitArea = $("<div class=\"hitArea\"></div>");
                this.hitArea.css({
                    position    : "absolute",
                    width       : "960px",
                    height      : "500px"
                });
                this.root.append(this.hitArea);
            } else{
                this.hitArea = this.root.find('.mediabar-container');
            }
        },

        initDragging: function() {

            this._mousedown = this.handleMousedown.bind(this);
            this._mouseup = this.handleMouseup.bind(this);

            this.touch = this.touchEnabled();

            if(this.touch) {
                this.touch_node = this.hitArea[0];
                this.touch_node.addEventListener('touchstart', this._mousedown, false);
                this.touch_node.addEventListener('touchend', this._mouseup, false);
            } else {
                this.hitArea.bind('mousedown', this._mousedown);
                this.hitArea.bind('mouseup', this._mouseup);
            }
        },

        handleMousedown: function(e) {
            var event = this.getEvent(e);

            this.sX = event.clientX;
            this.cX = this.clip[0].offsetLeft;
        },

        handleMouseup: function(e) {
            var event = this.getEvent(e);

            this.eX = event.clientX;

            var dX = this.eX - this.sX;

            // Check if not on a video control
            if ($(e.target).parents('.mejs-controls').length > 0) {
                return;
            }

            if (dX < -100) {
                this.next();
            }
            if (dX > 100) {
                this.previous();
            }
        },

        getEvent: function(e) {
            var event = e;

            var touch = e.touches;
            var changed = e.changedTouches;

            if(touch && touch[0]) {
                event = touch[0];
            } else if(changed && changed[0]) {
                event = changed[0];
            }

            return event;
        },

        touchEnabled: function() {
            return !!('ontouchstart' in window);
        },

        getCurrentItem: function() {
            return $(this.items[this.index]);
        },

        setFinished: function() {
            var navItems = this.nav.find('li.item');
            for (var i = 0; i < navItems.length; i++) {
                var navItem = $(navItems[i]);
                if (i < this.index) {
                    navItem.addClass('finished');
                } else {
                    navItem.removeClass('finished');
                }
            }
        },

        /**
         * Setups the mobile adjustments for the mediabar.
         */
        setupMobile: function() {
            // Setup nav
            this.setupMobileNav();

            // Setup e-learning slides
            this.setEcmeSize();

            // On orientation change
            this.isLandscape = $(window).width() > $(window).height();
            $(window).bind('resize', this.changeMobileOrientation.bind(this));
        },

        /**
         * Sets the ecme question width.
         */
        setEcmeSize: function() {
            var itemWidth = this.items.first().width();

            // Set question wrapper size
            var questionWrapper = this.clip.find('.ecme-qa');
            questionWrapper.css('width', (itemWidth * 2) + 'px');

            // Set question size
            var question = this.clip.find('.ecme-question');
            var padding = question.outerWidth(true) - question.width();
            question.css('width', (itemWidth - padding) + 'px');

            // Set scroll
            for (var i = 0; i < questionWrapper.length; i++) {
                var parent = $(questionWrapper[i]).parent();
                var scrollLeft = parent.scrollLeft();
                if (scrollLeft > 0) {
                    parent.scrollLeft(question.outerWidth(true));
                }
            }
        },

        /**
         * Initializes the mobile navigation.
         */
        setupMobileNav: function() {
            // Add wrapper to be able to scroll the nav
            var wrapper = this.nav.wrap('<div class="navitems" />').parent();
            wrapper.css({
                position: 'absolute',
                overflow: 'hidden',
                width: '960px'
            });
            this.navWrapper = wrapper;

            // Set the width of the nav
            var navWidth = 0;
            var items = this.nav.children('li');
            for (var i = 0; i < items.length; i++) {
                navWidth += $(items[i]).outerWidth(true);
            }
            this.nav.css({
                position: 'relative',
                width: navWidth + 'px'
            });
            this.mNavWidth = navWidth;
            this.mNavWidthOriginal = navWidth;

            // Set touch area
            this.mNavHitArea = $('<div class="navhitarea"></div>');
            wrapper.append(this.mNavHitArea);
            this.mNavHitArea.css({
                position: 'absolute',
                height: '30px',
                top: 0,
                left: 0,
                'z-index': 9999
            });

            // Setup events
            this._mNavTouchStart = this.touchstartMobileNav.bind(this);
            this._mNavTouchEnd = this.touchendMobileNav.bind(this);
            this._mNavTouchMove = this.touchmoveMobileNav.bind(this);
            if (this.touch) {
                this.mNavHitArea[0].addEventListener('touchstart', this._mNavTouchStart, false);
                this.mNavHitArea[0].addEventListener('touchend', this._mNavTouchEnd, false);
            } else {
                this.mNavHitArea.bind('mouseover', this._mNavTouchStart);
                this.mNavHitArea.bind('mouseout', this._mNavTouchEnd);
            }

            // Set nav size
            this.setMobileNavSize();

            // Set the mobile nav
            this.setMobileNav();

            // Hide the next and previous buttons
            this.nextButton.hide();
            this.prevButton.hide();
        },

        /**
         * Handles the touch start on the mobile navigation.
         * @param {Event} e the event
         */
        touchstartMobileNav: function(e) {
            var event = this.getEvent(e);

            this.mNavX = event.clientX;
            this.mNavLeftX = this.nav[0].offsetLeft;

            if (this.touch) {
                this.mNavHitArea[0].addEventListener('touchmove', this._mNavTouchMove, false);
            } else {
                this.mNavHitArea.bind('mousemove', this._mNavTouchMove);
            }
        },

        /**
         * Handles the touch move on the mobile navigation.
         * @param {Event} e the event
         */
        touchmoveMobileNav: function(e) {
            var event = this.getEvent(e);

            // Move the nav
            var left = this.mNavLeftX + ((event.clientX - this.mNavX) * 3);
            var minLeft = 0;
            var maxLeft = -this.nav.width() + $(window).width();
            if (left > 0) {
                left = minLeft;
            } else if (left < maxLeft) {
                left = maxLeft;
            }
            this.nav.css("left", left + "px");
        },

        /**
         * Handles the touch end on the mobile navigation.
         * @param {Event} e the event
         */
        touchendMobileNav: function(e) {
            if (this.touch) {
                this.mNavHitArea[0].removeEventListener('touchmove', this._mNavTouchMove);
            } else {
                this.mNavHitArea.unbind('mousemove', this._mNavTouchMove);
            }
        },

        /**
         * Sets the mobile nav size to the width of the screen.
         */
        setMobileNavSize: function() {
            var width = $(window).width();
            // Set nav wrapper width
            this.navWrapper.css('width', width + 'px');
            if (this.mNavWidthOriginal < width) {
                this.nav.css('width', width + 'px');
                this.mNavWidth = width;
            } else {
                this.nav.css('width', this.mNavWidthOriginal + 'px');
                this.mNavWidth = this.mNavWidthOriginal;
            }
            // Scroll nav to fit
            var maxLeft = -this.mNavWidth + $(window).width();
            if (this.nav.position().left < maxLeft) {
                this.nav.css('left', maxLeft + 'px');
            }
            // Set hit area width
            width -= this.closeButton.width();
            this.mNavHitArea.css('width', width + 'px');
        },

        /**
         * Sets the mobile nav into the view when scrolling.
         */
        setMobileNav: function() {
            // Get the top value
            var top = 0;
            // Set the top of the nav
            this.navWrapper.css('top', top);
            this.closeButton.css('top', top);
        },

        /**
         * Called when changing the orientation of the screen.
         */
        changeMobileOrientation: function() {
            // Get orientation of screen
            var landscape = $(window).width() > $(window).height();
            if (landscape != this.isLandscape) {
                // Reset the view size
                this.resetViewSize();
                this.isLandscape = landscape;
            }
        },

        /**
         * Reset the view size.
         */
        resetViewSize: function() {
            this.setupViews();
            // Set the clip to the correct position
            this.clip.css('left', this.getClipLeftOffset(this.index));
            if (this.isMobile) {
                this.setMobileNavSize();
                this.resetViewHeight();
                this.setEcmeSize();
            }
        },

        /**
         * Reset the viwe height.
         */
        resetViewHeight: function() {
            if (this.index == 0) {
                this.view.css('height', this.originalHeight + 'px');
            } else {
                var height = this.getCurrentItem().outerHeight(true);
                this.view.css('height', height + 'px');
            }
        }
    };

    LBi.namespace('Mediabar', Mediabar);

    /**
    * Carousel Defaults
    *
    * @static
    * @class LBi.Carousel.Defaults
    */
    Mediabar.Defaults = {
        /**
        * Nodetype of carousel items
        * @property itemSelector
        * @type String
        * @default "li"
        */
        itemSelector: 'li',
        /**
        * Nodetype of carousel item container. This may not be the same element as the courousel's root node.
        * @property clipSelector
        * @type String
        * @default "ul"
        */
        clipSelector: 'ul.',
        /**
         * Selector of the view that contains the movable clip. If not found, it is dynamically inserted around the clip.
         * @property viewSelector
         * @type String
         * @default ".carousel-view"
         */
        viewSelector: '.mediabar-container',
        /**
        * Defines the amount of items that are scrolled at once.
        * @property scroll
        * @type number
        * @default 1
        */
        scroll: 1,
        /**
        * The delay (in seconds) between automatic scrolling of carousel items, use 0 or false to disable automatic scrolling. The carousel pauses when hovered.
        * @property delay
        * @type number
        * @default 0
        */
        delay: 0,
        /**
        * The height of the expanded viewport in pixels
        * @property expandedHeight
        * @type integer
        * @default 500
        */
        expandedHeight: 500
    };

    /**
    * Creates a Mediabar instance for all elements in the jQuery result. A settings object may be
    * passed to this method. Instances are added to the LBi.Mediabar.instances array, since the jQuery
    * call must maintain the jQuery chain.
    *
    * @for jQuery.functions
    * @method mediabar
    * @param {Object} settings
    * @return {jQuery} result
    */
    Mediabar.instances = $.registerPlugin('mediabar', Mediabar);



    /**
     * Mediabar tips
     *
     */
    var MediaTips = function(settings) {
        this.touch = this.touchEnabled();
        this.settings = settings;
        this.$node = $(settings.template);
        this.$body = this.$node.find(settings.body);
        $(settings.target).append(this.$node);
    };

    MediaTips.prototype = {
        add: function(nodes) {
            var handle = this.handleEvent.bind(this);
            nodes.bind('mouseenter', handle);
            nodes.bind('mouseleave', handle);
        },

        open: function() {
            var current = this.getCurrent();
            var origin = current.offset();

            this.$body.html(this.tip);

            var w = this.$node.width() - current.width();
            var h = this.$node.height();

            this.$node.animate({
                left: origin.left - w/2,
                top: origin.top - h
            });

            this.$node.fadeIn();
            // If this is a touch device close the tooltip after a timeout,
            // because the touch device does not have a mouse out event
            if (this.touch) {
                setTimeout(this.close.bind(this), 3000);
            }
        },

        close: function() {
            this.$node.fadeOut();
        },

        handleEvent: function(e) {

            var state;
            var type = e.type;

            switch (type) {
                case 'mouseenter':
                case 'mouseover':
                    state = this.open;
                break;
                case 'mouseleave':
                case 'mouseout':
                    state = this.close;
                break;
            }

            if(state) {
                this.setCurrent(e.target);
                if(this.getCurrent()) {
                    clearTimeout(this.stateChange);
                    this.stateChange = setTimeout(state.bind(this), 500);
                }
            }
        },

        setCurrent: function(node) {
            var $node = $(node);
            var tip = $node.attr(this.settings.content);
            if(tip) {
                this.current = $node;
                this.tip = tip;
            } else {
                this.current = null;
            }

        },

        getCurrent: function() {
            return this.current;
        },

        touchEnabled: function() {
            return !!('ontouchstart' in window);
        }
    };


})(jQuery);

function onYouTubePlayerAPIReady() {
    var nodes = $('#mediabar .slides > li'),
        i, l = nodes.length,
        node, iframe;

    for (i = 0; i < l; i++) {
        node = $(nodes[i]);
        if (node.hasClass('youtube')) {
            iframe = node.find('iframe')[0];
            iframe.id = 'youtube-' + i;
            window.youtubePlayers[i] = new YT.Player(iframe.id);
        }
    }
  window.vidsIndexed = true;
}

$(function() {
    var nodes = $('#mediabar .slides > li'),
        i, l = nodes.length,
        node, iframe;

    window.vimeoPlayers = new Array(l);
    window.youtubePlayers = new Array(l);

    for (i = 0; i < l; i++) {
        node = $(nodes[i]);
        if (node.hasClass('vimeo')) {
            iframe = node.find('iframe')[0];
            window.vimeoPlayers[i] = new Froogaloop(iframe);
        }
    }
});

