var gone_fixed = false;
var refresh_queued = false;
var lastYOffset = 0;
var lastInnerHeight = 0;
var lastMaxScroll = 0;
var lastWindowPercent = 0;
var nearDiv = 0;
var farDiv = 0;
var fillerDiv = 0;
var birdDiv = 0;
var siloDiv = 0;

function queueRefresh() {
  lastYOffset = window.pageYOffset;
  lastInnerHeight = window.innerHeight;
  docHeight = window.scrollMaxY;
  lastMaxScroll = lastInnerHeight / 3;
  lastWindowPercent = lastYOffset / lastMaxScroll;

  if (!refresh_queued) {
    refresh_queued = true;
    requestAnimationFrame(setBkgnds);
  }
}

function setBkgnds() {
  refresh_queued = false;

  var nearTop = lastInnerHeight * 0.60;
  var farTop = lastInnerHeight * 0.20;
  var birdTop = lastInnerHeight * 0.10;
  var siloTop = lastInnerHeight * 0.60;
    
  if (lastYOffset < lastMaxScroll ) {
    if (gone_fixed) {
      nearDiv.removeClass('near-fixed');
      farDiv.removeClass('far-fixed');
      nearDiv.addClass('near-scroller');
      farDiv.addClass('far-scroller');
      gone_fixed = false;
    }
    nearTopFinal = (nearTop - ((nearTop - lastMaxScroll - 50) * lastWindowPercent));
    farTopFinal = (farTop - ((farTop - lastMaxScroll + 10) * lastWindowPercent));

    fillerDiv.css({'top': nearTopFinal + (0.40 * lastInnerHeight), 'height': lastInnerHeight * 0.60});
    nearDiv.css('top', nearTopFinal + 'px' );
    nearDiv.css('height', lastInnerHeight - (nearTopFinal - lastYOffset) + 'px' );
    siloDiv.css('top', nearTopFinal - 300 + 'px' );
    farDiv.css('top', farTopFinal + 'px' );
    birdDiv.css({'top': (birdTop - (birdTop* lastWindowPercent)), 'opacity': (1 - lastWindowPercent)});
  
  } else {
    if (!gone_fixed) {
      gone_fixed = true;
      nearDiv.addClass('near-fixed');
      farDiv.addClass('far-fixed');
      nearDiv.removeClass('near-scroller');
      farDiv.removeClass('far-scroller');
      nearDiv.css('height', lastInnerHeight - 50 + 'px' );
      nearDiv.css('top', '0px' );
      farDiv.css('top', '0px' );
    }
  }
}


$( document ).ready(function(){
  nearDiv = $('.near');
  farDiv = $('.far');
  fillerDiv = $('.filler');
  birdDiv = $('.birds');
  siloDiv = $('.silos');

  window.onscroll = queueRefresh;
  window.onresize = queueRefresh;
});
