global.jQuery = require('jquery');
global.sliderPro = require('slider-pro');
global.lightGallery = require('lightgallery');

(function ( $ ) {

    var screensizes = {
        small: 480,
        medium: 768,
        large: 1024
    }

    var _mediaplayers = {};

    function _getLightGalleryMedia(_mediaplayer) {

        var _media = $(_mediaplayer).data('media');

        var lgmedia = [];
        _media.forEach(function(item) {

            var lgmediaitem = {};
            lgmediaitem.thumb = item.thumbnail;
            lgmediaitem.subHtml = '<h4>' + item.meta.title + '</h4><p>' + item.meta.description + '</p>';
            lgmediaitem.responsive = [
                item.sourceset.small + ' ' + screensizes.small,
                item.sourceset.medium + ' ' + screensizes.medium,
                item.sourceset.large + ' ' + screensizes.large,
            ].join();
            lgmediaitem.src = item.sourceset.original;

            lgmedia.push(lgmediaitem);

        });

        return lgmedia;

    }

    function _addlightGallery(mediaplayer_slide) {

        var _mediaplayer = $(mediaplayer_slide).closest('.slider-pro');
        var mediaplayer_id = $(_mediaplayer).attr('id');

        $(mediaplayer_slide).lightGallery({
            dynamic: true,
            downloadUrl: false,
            index: _getMediaplayer(mediaplayer_id).getSelectedSlide(),
            dynamicEl: _getLightGalleryMedia(_mediaplayer)
        }).on('onAfterSlide.lg',function(event, prevIndex, index, fromTouch,fromThumb){
            _getMediaplayer(mediaplayer_id).gotoSlide(index)
        });

    };

    function _init_photo_player(_mediaplayer) {

        var _mediaplayer_id = $( _mediaplayer ).attr('id');

        $(_mediaplayer).addClass('slider-pro');

        _getMedia(_mediaplayer, function(_media) {

            $(_mediaplayer).data('media', _media);

            _media.forEach(function(element) {
                $template = $($(_mediaplayer).find('template[name="slide"]').html());//

                $template.find('.sp-image').attr('src', element.sourceset.default);

                // Add conditional images
                $template.find('.sp-image').attr('data-small', element.sourceset.small);
                $template.find('.sp-image').attr('data-medium', element.sourceset.medium);
                $template.find('.sp-image').attr('data-large', element.sourceset.large);

                $template.find('.sp-thumbnail-image').attr('src', element.thumbnail);
                $template.find('.sp-thumbnail').css('background-image', 'url('+element.thumbnail+')');
                $template.find('.sp-thumbnail-text').attr('src', element.meta.title);

                var html = $template.html();
                $.each( element.meta, function( key, value ) {
                    var re = new RegExp('{'+key+'}',"g");
                    html = html.replace(re, value);
                });
                $template.html(html);

                $(_mediaplayer).find('.sp-slides').append($template);

            });

            $(_mediaplayer).find('template').remove();

            $( _mediaplayer ).sliderPro({
                arrows: true,
                autoplay: false,
                buttons: false,
                width: '100%',
                height: 438,
                autoHeight: true,
                loop: false,
                smallSize: screensizes.small,
                mediumSize: screensizes.medium,
                largeSize: screensizes.large,
                thumbnailHeight: 120,
                thumbnailWidth: 180,
                thumbnailArrows: true,
                thumbnailPointer: true,
                fadeThumbnailArrows: true,
                centerSelectedSlide: true,
            });

            _addMediaplayer(_mediaplayer_id, $( _mediaplayer ).data( 'sliderPro' ));

            if (_media.length == 1) {
                $(_mediaplayer).find('.sp-thumbnails-container').hide();
            }

            $( _mediaplayer ).find('.sp-image').on( 'dblclick', function() {
                _addlightGallery(this);
            })

        });

    };

    function _load_new_video(mediaplayer, mediaitem, autoplay) {

        if (typeof(autoplay) == 'undefined') {
            autoplay = false;
        }

        var source = 'http://player.vimeo.com/video/{video_id}?color=CC0000&portrait=0&title=0&badge=0&byline=0&api=1';

        if (autoplay) {
            source += '&autoplay=1';
        }

        source = source.replace(/{video_id}/g, mediaitem.uuid);

        $(mediaplayer).find('.js-video').attr('src', source);

        $(mediaplayer).find('.js-list .active').removeClass('active');
        $(mediaplayer).find('.js-list .js-item-' + mediaitem.meta.id).addClass('active');

    }

    function _init_video_player(_mediaplayer) {

        var template = _getTemplate('video');
        var template_playlist = $(_mediaplayer).find('template[name="playlist"]').html();

        _getMedia(_mediaplayer, function(_media) {

            $(_mediaplayer).data('media', _media);

            $(_mediaplayer).html(template);

            var active_media_id = $(_mediaplayer).data('active-media-id');
            var activeitem = null;
            _media.forEach(function(item) {

                var temp = template_playlist;
                temp = temp.replace(/{title}/g, item.meta.title);
                temp = temp.replace(/{description}/g, item.meta.description);
                temp = temp.replace(/{duration}/g, _format_duration(item.meta.duration));
                temp = temp.replace(/{id}/g, item.meta.id);
                temp = temp.replace(/{thumbnail}/g, item.thumbnail);

                temp = '<li class="video-player__list-item js-item-'+ item.meta.id +'">' + temp + '</li>';

                $(_mediaplayer).find('.js-list').append(temp);
                $(_mediaplayer).find('.js-list .js-item-' + item.meta.id).click(function() {
                    _load_new_video(_mediaplayer, item, true);
                });

                if (active_media_id == item.meta.id) {
                    activeitem = item;
                }

            });

            if (!activeitem) {
                activeitem = _media[0];
            }

            _load_new_video(_mediaplayer, activeitem);

        });

    }

    function _format_duration(seconds) {

        var sec_num = parseInt(seconds, 10);
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}

        if (parseInt(hours)) {
            return hours+':'+minutes+':'+seconds;
        }

        return minutes+':'+seconds;

    }

    $.fn.mediaplayer = function() {
        return this.each(function() {

            var _mediaplayer = this;
            var _mediaplayer_type = $( _mediaplayer ).data('media-type');

            if (_mediaplayer_type == 'photo') {
                _init_photo_player(_mediaplayer);
            }

            if (_mediaplayer_type == 'video') {
                _init_video_player(_mediaplayer);
            }

        });

    };

    function _addMediaplayer(mediaplayer_id, mediaplayer) {
        _mediaplayers[mediaplayer_id] = { sliderpro: mediaplayer};
    }

    function _getMediaplayer(mediaplayer_id) {
        return _mediaplayers[mediaplayer_id].sliderpro;
    }

    function _getTemplate(name) {

        switch(name) {

            case 'video':
                return '<div class="video-player">' +
                            '<div class="video-player__stage">' +
                                '<div class="video-responsive video-responsive-16by9" >' +
                                    '<iframe class="video-responsive-item js-video" src="//player.vimeo.com/video/{vimeo_id}?color=CC0000&amp;portrait=0&amp;title=0&amp;badge=0&amp;byline=0&amp;api=1&amp;player_id=vimeoplayer" width="720" height="405" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>' +
                                '</div>' +
                            '</div>' +
                            '<ul class="video-player__list js-list"></ul>' +
                        '</div>';
                break;

        }

    }

    function _getMedia(_mediaplayer, success, failure) {

        var source = $(_mediaplayer).data('media-src')

        $.getJSON(source).done(success)

        .fail(function( jqxhr, textStatus, error ) {
            if (typeof(failure) != 'undefined') {
                failure( jqxhr, textStatus, error );
            }
        });

    }

}( jQuery ));

// ** ---------------------------------------------
