/**
 *  Initialize parallaxModules
 */
var parallaxModules = (function () {

  var pub = {}; // public facing functions

  pub.init = function () {
    var jarallaxElem = document.querySelectorAll('.jarallax');
    if (jarallaxElem.length > 0) {
      pub._listenForMobileImages(jarallaxElem);
      pub._handleJarallaxResizing(jarallaxElem);

      jarallax(jarallaxElem, {
        speed: 0.6,
        disableVideo: function () {
          return /iPad|iPhone|iPod|Android/.test(navigator.userAgent);
        }
      });
    }

    pub._listenForVideoElements('.jarallax video');
    pub._listenForVideoElements('.background__video');
  };

  /**
   * Initialize event listener for resizing parallax modules, this will check for mobile image fall backs.
   *
   * @param jarallaxElem
   */
  pub._handleJarallaxResizing = function (jarallaxElem) {
    window.addEventListener('resize', function () {
      setTimeout(function () {
        pub._listenForMobileImages(jarallaxElem);
      }, 1000);
    });
  };

  /**
   * Check parallax elements for mobile background settings and swap out if our viewport is below desktop.
   */
  pub._listenForMobileImages = function (jarallaxElem) {
    for (var i = 0; i < jarallaxElem.length; i++) {
      var jarallaxImage = jarallaxElem[i].querySelector('.jarallax-img');
      // check that we have an image to evaluate
      if (jarallaxImage) {
        var jarSrc = jarallaxImage.getAttribute('data-src'),
          jarMobile = jarallaxImage.getAttribute('data-mobile');

        // check if our current image has a mobile url set
        if (jarMobile) {

          // check our viewport width for image source
          if (window.innerWidth < 768) {
            jarallaxImage.setAttribute('src', jarMobile);
          } else {
            jarallaxImage.setAttribute('src', jarSrc);
          }
        }
      }
    }
  };

  /**
   * Add ready states to video elements for fade in effect once they've started playing media.
   */
  pub._listenForVideoElements = function (videoElement) {
    // add loading class to jarallax video once it begins play
    var videos = document.querySelectorAll(videoElement);
    if (videos.length > 0) {
      for (var i = 0; i < videos.length; i++) {
        videos[i].addEventListener('playing', function (e) {
          if (this.readyState === 4) {
            this.classList.add('video--ready');
          }
        }, false);
      }
    }
  };

  return pub;

}());