/**
 * @file
 * Javascript functionality for component accordion.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentPlayList = Drupal.componentPlayList || {};
  Drupal.behaviors.playlist = {
    attach: function (context) {
      Drupal.componentPlayList.playlist(context);
    }
  }
  Drupal.componentPlayList.playlist = function (context) {
    const $playlist =  $(once('playlistItems', '.component-builder.component-item--type-playlist', context));
    if ($playlist.length > 0) {
      $playlist.each(function () {
        const $this = $(this);

        // Popup for image
        if ($this.find('.field--name-field-media-image').length) {
          const image = $this.find('.field--name-field-media-image > div > img');
          const link_image = image.attr('src');
          const title = $this.find('.field--name-title').text();
          $this.find('.link-to-media').attr('href', link_image);
          $this.find('.link-to-media').attr('title', title);

          $this.find('.link-to-media').magnificPopup({
            type: 'image',
            closeOnContentClick: true,
            closeBtnInside: false,
            fixedContentPos: true,
            mainClass: 'mfp-no-margins mfp-with-zoom', // class to remove default margin from left and right side
            image: {
              verticalFit: true
            },
            zoom: {
              enabled: true,
              duration: 300 // don't foget to change the duration also in CSS
            }
          });
        }

        // Popup for video
        if ($this.find('.field--name-field-media-video-file').length) {
          const link_video = $this.find('.field--name-field-media-video-file > div > video > source').attr('src');
          $this.find('.link-to-media').attr('href', link_video);

          $this.find('.link-to-media').magnificPopup({
            preloader: false,
            type:'iframe',
            tClose: 'X',
            iframe: {
              markup: '<div class="mfp-iframe-scaler">'+
                '<div class="mfp-close"></div>'+
                '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
                '</div>',
            },
            closeBtnInside: true,
            closeOnBgClick: false,
            fixedBgPos: false,
          });
        }

      })
    }
  }

})(jQuery, Drupal, once);
