/**
 * Bootstrap Carousel Swipe v1.1
 *
 * jQuery plugin to enable swipe gestures on Bootstrap 3 carousels.
 * Examples and documentation: https://github.com/maaaaark/bcSwipe
 *
 * Licensed under the MIT license.
*/
(function($) {
  $.fn.bcSwipe = function(settings) {
    var config = { threshold: 50 };
    if (settings) {
      $.extend(config, settings);
    }

    this.each(function() {
      var stillMoving = false;
      var start;

      if ('ontouchstart' in document.documentElement) {
        this.addEventListener('touchstart', onTouchStart, false);
          console.log("-------------- touch start added --------------");
      }
      function onTouchStart(e) {
          var isMobile = /Android|webOS|iPhone|BlackBerry/i.test(navigator.userAgent) ? true : false;

        if (isMobile && e.touches.length == 1) {
          start = e.touches[0].pageX;
          stillMoving = true;
          this.addEventListener('touchmove', onTouchMove, false);
            console.log("--------touched---------");
        }else{
            return false;
        }
      }

      /*function onTouchStart(e) {
        if (e.touches.length == 1) {
          start = e.touches[0].pageX;
          stillMoving = true;
          this.addEventListener('touchmove', onTouchMove, false);
            console.log("--------touched---------");
        }
      }*/

      function onTouchMove(e) {
        if (stillMoving) {
          var x = e.touches[0].pageX;
          var difference = start - x;
          if (Math.abs(difference) >= config.threshold) {
            cancelTouch();
            if(isCarouselEmpty($(this))) return;
            if (difference > 0) {
              $(this).carousel('next');
                console.log("carousel.next");
            }
            else {
              $(this).carousel('prev');
                console.log("carousel.prev");
            }
          }
        }
      }
      
      function isCarouselEmpty(carousel){
          console.log("is carousel empty?");
	       return carousel.find(".item.active").length < 1
      }

      function cancelTouch() {
        this.removeEventListener('touchmove', onTouchMove);
        start = null;
        stillMoving = false;
      }
    });

    return this;
  };
})(jQuery); 