var Scroll = (function() {

'use strict';

function AnimateOnScroll(element) {
  this.element = element;
  this.elementTopToPageTop = this.element.offset().top;
  this.windowInnerHeight = window.innerHeight;
  this.distanceFromBottomToAppear = this.elementTopToPageTop - ($(window).height() / 1.4);
}

AnimateOnScroll.prototype.update = function(wScroll) {
  var elementTopToWindowTop = this.elementTopToPageTop - wScroll;
  var elementTopToWindowBottom = this.windowInnerHeight - elementTopToWindowTop;

  if (wScroll > this.distanceFromBottomToAppear) {
    this.element.addClass('animateOnScroll--animating');
  } else if(elementTopToWindowBottom < 0) {
    this.element.removeClass('animateOnScroll--animating');
  }
};

function Scroll() {
  this.header = $('.header');
  this.navSearch = $('.navSearch');
  this.hasTransparentHeader = $('.header--transparent').length;
  this.hideNavSearch = $('.heroBanner__search').length;
  this.bannerHeight = $('.heroBanner').height();
  this.animateOnScroll = $('.animateOnScroll');
  this.animatedSections = [];
  this.latestKnownScrollTop = 0;
  this.ticking = false;

  this.initialize();
}

Scroll.prototype.initialize = function() {
  var self = this;

  $.each(this.animateOnScroll, function(index, value) {
    self.animatedSections.push(new AnimateOnScroll($(this)));
  });

  this.onScroll();
  this.bindEvents();
};

Scroll.prototype.bindEvents = function() {
  var self = this;

  window.addEventListener('scroll', function() {
    self.onScroll();
  });
};

Scroll.prototype.scrollNav = function(wScroll) {
  var scrollDistance = 100;

  if (wScroll > scrollDistance) {
    this.header.addClass('header--scrolled');
    this.navSearch.removeClass('navSearch--hidden');
    this.navSearch.removeClass('navSearch--light');

  } else {
    this.header.removeClass('header--scrolled');
    this.navSearch.addClass('navSearch--light');
    if (this.hideNavSearch) this.navSearch.addClass('navSearch--hidden');
  }
};

Scroll.prototype.onScroll = function() {
  this.latestKnownScrollTop = $(window).scrollTop();
  this.requestTick();
};

Scroll.prototype.update = function() {
  var wScroll = this.latestKnownScrollTop;
  var self = this;
  this.ticking = false;

  if (this.hasTransparentHeader) this.scrollNav(wScroll);
  $.each(this.animatedSections, function(index, value) {
    self.animatedSections[index].update(wScroll);
  });
};

Scroll.prototype.requestTick = function() {
  var self = this;

  if(!this.ticking) {
    requestAnimationFrame(function() {
      self.update();
    });
  }
  this.ticking = true;
};

return Scroll;

})();

$(function() {

var scroll = new Scroll;

});