require("lib.owlcarousel");
$ = require('jquery');

var Slider = function (sliderName, speed, pagination, navigation_buttons) {
    this.sliderName = sliderName;
    this.speed = speed;
    this.pagination = Boolean(pagination);
    this.navigation_buttons = Boolean(navigation_buttons);
    this.$container = $("#carousel-" + this.sliderName).closest('.js-tile-body-container');

    this.init();
};

Slider.prototype.init = function()
{
    var owl = this.$container.find(".carousel-inner");
    // Calculates how many slides there are in a slider so functionality can be blocked if it is 1
    var slideCount = owl.children().size();

    function initCarousel(speedSetting, paginationSetting, navigationSetting) {
        owl.owlCarousel({
            autoplay: true,
            mouseDrag: slideCount > 1,
            touchDrag: slideCount > 1,
            autoplayTimeout: speedSetting,
            lazyLoad: true,
            lazyLoadEager: 2,
            items: 1,
            loop: true,
            autoplayHoverPause: true,
            dots : paginationSetting,
            nav : navigationSetting,
            navText: ['<ion-icon class="d-block" name="chevron-back"></ion-icon>','<ion-icon class="d-block" name="chevron-forward"></ion-icon>']
        });
    }

    initCarousel(this.speed, this.pagination, this.navigation_buttons);

    // Adds class to sliders with pagination dots so the overlay positon can be altered
    $('.owl-dots').not('.disabled').parents('.owl-carousel').addClass('pagination-dots');

    this.calcDisplaySize();

    var self = this;

	// re-init when Pages starts up
	$('body').on('pages-started', function()
	{
		self.calcDisplaySize();
	});

	// Listen to Pages events to re-init when a tile is resized
	owl.closest('.js-tile').on('pages-tile-resize', function(event, element)
	{
		setTimeout(function()
		{
            // Reinitialises owl carousel when the componenet is resized
            owl.owlCarousel('destroy');
            initCarousel(this.speed, this.pagination, this.navigation_buttons);

			self.calcDisplaySize();
		}, 600);
	});
};

Slider.prototype.calcDisplaySize = function()
{
    // Resize image container to remove scrollbars
    var container = this.$container;
    if (container.length > 0)
    {
        var fullHeight = container.height();
        container.find('.carousel .item').height(fullHeight);
    }
};

module.exports = Slider;
