/**
 * @file
 * Javascript functionality for component food menu.
 */

(function ($, Drupal, once) {

  'use strict';

  Drupal.componentFoodMenu = Drupal.componentFoodMenu || {};
  Drupal.behaviors.food_menu = {
    attach: function (context) {
      Drupal.componentFoodMenu.food_menu(context);
    }
  }
  Drupal.componentFoodMenu.food_menu = function (context) {
    const $food_menu =  $(once('foodMenuItems', '.component-builder.component-wrapper--type-food_menu', context));
    if ($food_menu.length > 0) {
      $food_menu.each(function () {
        const $this = $(this);

        const count = $('.field--name-field-image > div').length;
        if (count > 1) {

          let slideIndex = 1;
          showSlides(slideIndex);

          function plusSlides(n) {
            showSlides(slideIndex += n);
          }

          function currentSlide(n) {
            showSlides(slideIndex = n);
          }

          function showSlides(n) {
            let i;
            let slides = document.getElementsByClassName("mySlides");
            let dots = document.getElementsByClassName("dot");
            if (n > slides.length) {slideIndex = 1}
            if (n < 1) {slideIndex = slides.length}
            for (i = 0; i < slides.length; i++) {
              slides[i].style.display = "none";
            }
            for (i = 0; i < dots.length; i++) {
              dots[i].className = dots[i].className.replace(" active", "");
            }
            slides[slideIndex-1].style.display = "block";
            dots[slideIndex-1].className += " active";
          }

          $this.find('.prev').click( function () {
              showSlides(slideIndex += -1);
            }
          )
          $this.find('.next').click( function () {
              showSlides(slideIndex += 1);
            }
          )

          for (let i = 0; i < count; i++) {
            $this.find('.dot-' + i).click( function () {
                showSlides(slideIndex = i + 1);
              }
            )
          }
        }
      })
    }
  }

})(jQuery, Drupal, once);
