var Schneider = {};
Schneider.animation = window.Schneider.animation || {};

/* Object to hold all the animation information for each module */
Schneider.animation.animationSteps = {
  'module-1' : [],
  'module-2' : ['0 0', '0 -506px', '0 -1012px', '0 -1518px', '0 -2024px', '0 -2530px', '0 -3036px', '0 -3542px',
      '0 -3036px', '0 -2530px', '0 -2024px', '0 -1518px', '0 -1012px', '0 -506px', '0 0'],
  'module-3' : ['0 0', '0 -430px', '0 -860px', '0 -1290px', '0 -1720px', '0 -2150px', '0 -2580px', '0 -3010px', '0 -3440px', '0 -3870px', '0 -4300px', '0 -4730px',
      '0 -4300px', '0 -3870px', '0 -3440px', '0 -3010px', '0 -2580px', '0 -2150px', '0 -1720px', '0 -1290px', '0 -860px', '0 -430px', '0 0'],
  'module-4' : ['0 0', '0 -505px', '0 -1010px', '0 -1515px', '0 -2020px', '0 -2525px', '0 -3030px', '0 -3535px', '0 -4040px',
      '0 -3535px', '0 -3030px', '0 -2525px', '0 -2020px', '0 -1515px', '0 -1010px', '0 -505px', '0 0'],
  'module-5' : ['0 0', '0 -505px', '0 -1010px', '0 -1515px', '0 -2020px', '0 -2525px', '0 -3030px',
      '0 -2525px', '0 -2020px', '0 -1515px', '0 -1010px', '0 -505px', '0 0'],
  'module-6' : ['0 0', '0 -505px', '0 -1010px', '0 -1515px', '0 -2020px', '0 -2525px', '0 -3030px', '0 -3535px', '0 -4040px',
      '0 -3535px', '0 -3030px', '0 -2525px', '0 -2020px', '0 -1515px', '0 -1010px', '0 -505px', '0 0'],
  'module-7' : ['0 0', '0 -220px', '0 -440px', '0 -660px', '0 -880px', '0 -1100px', '0 -1320px', '0 -1540px', '0 -1760px', '0 -1980px', '0 -2200px', '0 -2420px', '0 -2640px', '0 -2860px', '0 -3080px',
      '0 -2860px', '0 -2640px', '0 -2420px', '0 -2200px', '0 -1980px', '0 -1760px', '0 -1540px', '0 -1320px', '0 -1100px', '0 -880px', '0 -660px', '0 -440px', '0 -220px', '0 0'],
  'module-8' : ['0 0', '0 -505px', '0 -1010px', '0 -1515px', '0 -2020px', '0 -2525px', '0 -3030px', '0 -3535px',
      '0 -3030px', '0 -2525px', '0 -2020px', '0 -1515px', '0 -1010px', '0 -505px', '0 0'],
  'module-9' : ['0 0', '0 -425px', '0 -850px', '0 -1275px', '0 -1700px', '0 -2125px', '0 -2550px', '0 -2975px',
    '0 -3400px', '0 -3825px', '0 -4250px', '0 -4675px', '0 -5100px', '0 -5525px', '0 -5950px', '0 -6375px', '0 -6800px', '0 -7225px', '0 -7650px',
    '0 -8075px', '0 -7650px', '0 -7225px', '0 -6800px', '0 -6375px', '0 -5950px', '0 -5525px', '0 -5100px', '0 -4675px', '0 -4250px', '0 -3825px', '0 -3400px', '0 -2975px', '0 -2550px', '0 -2125px', '0 -1700px', '0 -1275px', '0 -850px', '0 -425px', '0 0'],
  'module-10' : ['0 0', '0 -440px', '0 -880px', '0 -1320px', '0 -1760px', '0 -2200px', '0 -2640px', '0 -3080px',
      '0 -2640px', '0 -2200px', '0 -1760px', '0 -1320px', '0 -880px', '0 -440px', '0 0'],
  'module-11' : ['0 0', '0 -205px', '0 -410px', '0 -615px', '0 -820px', '0 -1025px', '0 -1230px', '0 -1435px', '0 -1640px',
      '0 -1435px', '0 -1230px', '0 -1025px', '0 -820px', '0 -615px', '0 -410px', '0 -205px', '0 0'],
  'module-12' : ['0 0', '0 -430px', '0 -860px', '0 -1290px', '0 -1720px', '0 -2150px', '0 -2580px', '0 -3010px', '0 -3440px',
      '0 -3870px', '0 -4300px', '0 -4730px', '0 -5160px', '0 -5590px', '0 -6020px', '0 -6450px', '0 -6880px', '0 -7310px',
      '0 -7740px', '0 -8170px', '0 -8600px', '0 -9030px', '0 -9460px'],
  'module-13' : ['0 0', '0 -505px', '0 -1010px', '0 -1515px', '0 -2020px', '0 -2525px', '0 -3030px', '0 -3535px', '0 -4040px',
      '0 -3535px', '0 -3030px', '0 -2525px', '0 -2020px', '0 -1515px', '0 -1010px', '0 -505px', '0 0'],
  'module-14' : []
};

/* Initialize */
Schneider.animation.init = function(){
  $('#bottom, #special-schueler').show();

  visibleModule = $('#module-1');
  visibleAnimation = false; nextModuleBorder = false; prevModuleBorder = false; prevModuleUpperBorder = false;
  arrowShowTrigger = false; arrowHideTrigger = false;
  mainHeight = 0;
  oldTop = 0; newTop = 0; transitionToNextStarted = false; transitionToPrevStarted = false;
  scrollOffset = 0; orientationTimeout = false; arrowShowing = true; navTimeout = false;
  animateAnchor = '.animate';
  //instantiate object to hold the animation offsets, gets populated in getAnimationSteps
  animationOffsets = {};
  mode = 'production';
  isFindActiveModuleRunning = false;
  //declared like this because of an ie7/8 problem with the scopes
  window.arrow = $('#arrow');
  window.arrowH = window.arrow.innerHeight();
  window.windowH = parseInt($(window).innerHeight());
  window.dotNav =  $('#dot-navigation');
  window.arrowPosition = false;
  arrowTreshold = 200; aspectRatio = 1.3333;

  Schneider.animation.getContext();
  Schneider.animation.padTextFields();
  Schneider.animation.gatherModuleData();
  Schneider.animation.setupModuleParams();
  Schneider.animation.checkOrientation();
  Schneider.animation.positionAnimationContainer();
  Schneider.animation.getAnimationSteps();
  Schneider.animation.buildDotNav();
  Schneider.animation.positionArrow();
  Schneider.animation.animateArrow();
}

/* looks for the animationTriggers control-text elements and binds there offsets to the animated
modules, the triggers are then hidden (not removed as we need them again for any resizes) */
Schneider.animation.getAnimationSteps = function() {
  var anchors = $(animateAnchor);
  if(anchors.length){
    anchors.css('display', 'block');
    anchors.each(function (index, element){
      var module_id = $(this).closest('.module').attr('id');
      if(module_id.length){
        animationOffsets[module_id]['offsets'].push($(this).offset().top);
      }
    });
    if(mode != 'debug'){
      anchors.css('display', 'none');
    }
  }
}


/* Bind Event-Handler */
Schneider.animation.bind = function() {
  /* Normalize Scroll behavior across browser - depedent on jquery.mousewheel */
  $(document).on('mousewheel', Schneider.animation.mouseWheelHandler);
  $(window).on('scroll', Schneider.animation.scrollHandler);

  var timeout = false;
  $(window).on('resize', function() {
    if(timeout !== false){
      clearTimeout(timeout);
    }
    timeout = setTimeout(Schneider.animation.adaptToResize, 200);
  });

  $('#dot-navigation a').click(function(e){
    //unbind scroll handler to not trigger the find-functions
    if(navTimeout !== false){
      clearTimeout(navTimeout);
    }
    $(window).off('scroll');
    $(document).off('mousewheel').on('mousewheel', Schneider.animation.killMouseWheel);
    e.preventDefault();
    var targetObj = $($(this).attr('href'));
    Schneider.animation.loosenVisibleAnimation();
    transitionToNextStarted = false; transitionToPrevStarted = false;
    arrow.css('display', 'none');
    var scrollTarget = targetObj.offset().top - headerH;
    if(scrollTarget < mainHeight){
      scrollTarget = 0;
    }
    $(window).stop(true, true).scrollTo(scrollTarget, 400, {onAfter:function (){
      visibleModule = targetObj;
      Schneider.animation.setupModuleParams();
      Schneider.animation.animatePreviousModules();
      Schneider.animation.resetFollowingModules();
      Schneider.animation.fixVisibleAnimation();
      Schneider.animation.positionArrow();
      $('#dot-navigation .active').removeClass('active').parent().find('a[href="#' + visibleModule.attr('id') + '"]').addClass('active').parent().css('z-index', '15');
      newTop = $(window).scrollTop();
      arrowShowing = true;
      Schneider.animation.positionArrow();

      arrow.fadeIn(150, function() {
        Schneider.animation.animateArrow();
      });
      navTimeout = window.setTimeout(function() {
        $(window).on('scroll', Schneider.animation.scrollHandler);
        $(document).off('mousewheel').on('mousewheel', Schneider.animation.mouseWheelHandler);
        navTimeout = false;
      }, 600);
    }});
  });

  $('#dot-navigation a').hover(function(e) {
    var obj = $(this);
    var liftUp = true;
    var asides = visibleAnimation.find('.aside');
    var pageX = e.pageX;
    var pageY = e.pageY;

    asides.each(function(index, context){
      var coords = $(this).offset();
      var asideLeftBound = coords.left;
      var asideRightBound = asideLeftBound + $(this).outerWidth();
      var asideTopBound = coords.top;
      var asideBottomBound = asideTopBound + $(this).outerHeight();

      if(pageX <= asideRightBound && pageY >= asideTopBound && pageY <= asideBottomBound){
        liftUp = false
      }
    });

    if(liftUp === true){
      $(this).parent().css('z-index', '25');
      if($.browser.msie && $.browser.version < 9){
        obj.addClass('nojquery');
      }
    }else{
      if($.browser.msie && $.browser.version < 9){
        obj.removeClass('nojquery');
      }
    }
  }, function(e) {
      $(this).parent().css('z-index', '15');
      if($.browser.msie && $.browser.version < 9){
        $(this).addClass('nojquery');
      }
  });
}

Schneider.animation.killMouseWheel = function(event, delta){
  event.preventDefault();
  return false;
}

Schneider.animation.mouseWheelHandler = function(event, delta) {
  var treshold = 29;

  if(delta > 2.5) {delta = 2.5}  else if(delta < -2.5) {delta = -2.5}
  window.scrollBy(0, -1 * treshold * delta);
  event.preventDefault();
  return false;
}

/* the basic scroll Handler */
Schneider.animation.scrollHandler = function(){
  oldTop = newTop;
  newTop = $(window).scrollTop();
  //calculate difference
  var scrollOffset = Math.abs(newTop - oldTop);

  /*you used the scrollbar didn't you? / but you didn't hit space / adapt treshold if necessary */
  if(scrollOffset > 800 && scrollOffset != windowH){
    //prevent function cascading
    if(orientationTimeout !== false){
      window.clearTimeout(orientationTimeout);
      orientationTimeout = false;
    }
    if(orientationTimeout === false){
      orientationTimeout = window.setTimeout(Schneider.animation.findActiveModule, 500);
    }
  }else{
    Schneider.animation.animate();
    Schneider.animation.checkModuleTransition();
  }
}

/* get the height of the visible window / plus information on additional fixed elements */
Schneider.animation.getContext = function() {
  /* this application was written with a fixed header and footer in mind
  * the intention is to keep that functionality. look for reference to $('#head') and
  * $('#bottom_wrapper') in code below to see how the height of both is accounted for
  * in the calculations for the first and last module
  * */
  headerH = 0;//parseInt($('#head').outerHeight());
  footerH = 0; //parseInt($('#bottom_wrapper').outerHeight());
  mainHeight = windowH - headerH - footerH;
  arrowPosition = parseInt(windowH - footerH - arrowH - 25);
}

/* the basic resize handler */
Schneider.animation.adaptToResize = function() {
  Schneider.animation.getContext();
  Schneider.animation.padTextFields();
  Schneider.animation.gatherModuleData();
  Schneider.animation.setupModuleParams();
  Schneider.animation.checkOrientation();
  Schneider.animation.positionAnimationContainer();
  Schneider.animation.getAnimationSteps();
  Schneider.animation.findActiveModule();
  Schneider.animation.positionArrow();
  Schneider.animation.positionNav();
}

/* initiate a special behavior if user resizes window to width < height
* this is only damage control as it is an edge case */
Schneider.animation.checkOrientation = function () {
  if(parseInt($(window).innerWidth()) / windowH  < aspectRatio){
    $('.fullscreen').addClass('portrait');
  }else{
    $('.fullscreen').removeClass('portrait');
  }
}

/* get information about the size and animation properties of all the modules to control the animations */
Schneider.animation.gatherModuleData = function() {
  var fullscreen = $('.fullscreen');
  fullscreen.each(function(index, element) {
    //make sure each module has minimum height at all times
    if(index == 0){
      $(this).addClass('first');
      $(this).height(mainHeight - parseInt($('#head').outerHeight()));
    }else if(parseInt($(this).height()) < mainHeight){
      $(this).height(mainHeight);
    }else{
      $(this).height($(this).height());
    }

    if(index == (fullscreen.length - 1)){
      $(this).addClass('last');
    }

    if($(this).is('.module')){
      //make sure the module is long enough to allow each animation to complete no matter the res
      var nextModule = $(this).next();
      if(nextModule.length){
        var lastAnimationEl = $(this).find('.control-text .animate:last');

        if(lastAnimationEl.length){
          var distToBottom = nextModule.offset().top - (lastAnimationEl.offset().top + lastAnimationEl.height());
          if(distToBottom < mainHeight){
            $(this).height(parseInt($(this).innerHeight()) + (mainHeight - distToBottom) + 150);
          }
        }
      }
      Schneider.animation.bindAppearanceData($(this));
      /* this is a working approach if the aspect ratio of all module backgrounds is not identical */
      //Schneider.animation.bindOrientationData($(this));
      //instantiate object properties for animationOffset-Object
      var id = $(this).attr('id');
      animationOffsets[id] = {};
      animationOffsets[id].offsets = [];
    }
  });
}

/* add padding to the text fields to start the animation without text being visible */
Schneider.animation.padTextFields = function() {
  $('.text').each(function(index, element){
    if($(this).parent().is(':not(.container)')){
      var container = $(this);
      var control = $(this).parent().find('.control-text');
      var minHeight = (2 * mainHeight) + container.height();

      if(control.height() < minHeight){
        control.height(minHeight);
      }
      //added treshold to make animation start slightly earlier / you can adjust this
      container.css({
        'padding-top' : parseInt(mainHeight + 150) + 'px',
        'padding-bottom' : mainHeight + 'px'
      });
    }
  });
}

/* build the navigation */
Schneider.animation.buildDotNav = function() {
  $('.module').each(function(index, element){
    var a = $('<a>&nbsp</a>');
    var span = $('<span></span>');
    a.attr('href', '#' + $(this).attr('id')).addClass('nojquery');
    if(index === 0){
      a.addClass('active');
    }

    var headline = '';
    $(this).find('h1').each(function(){
      if(headline.length){
        headline += ' / ';
      }
      headline += $(this).text();
    });

    span.text(headline)
    dotNav.append(a.append(span)).append('<br/>');
  });

  Schneider.animation.positionNav();
}

/* center the navigation */
Schneider.animation.positionNav = function () {
  var offset = (mainHeight + headerH)/2 - (parseInt(dotNav.innerHeight())/2);
  dotNav.css('top', offset);
}

/* position the transition arrow */
Schneider.animation.positionArrow = function() {
  arrow.clearQueue().css({'position' : 'fixed', 'top' : arrowPosition + 'px'});
}

/* animate the transition arrow */
Schneider.animation.animateArrow = function() {
  arrow.stop().css({'display' : 'block', 'opacity' : 1}).animate({'top' : '-=6'}, {'duration' : 100, 'easing' : 'linear', 'complete' : function() {
    arrow.stop().animate({'top' : '+=16'}, {'duration' : 300, 'easing' : 'linear','complete' : function() {
      arrow.stop().animate({'top' : '-=10'}, {'duration' : 300, 'easing' : 'linear','complete' : Schneider.animation.animateArrow});
    }})
  }});
}

/*Schneider.animation.bindOrientationData = function (elem){
  var url = elem.css('background-image');
  url = url.substr(5, (url.length - 7));
  console.log(url);
  var img = new Image();
  img.src = url;
  var aspectRatio = img.width / img.height;
  elem.data('aspectRatio', aspectRatio);
}*/


/* calculate and bind data about when modules first appear and finally disappear in relation to scroll values */
Schneider.animation.bindAppearanceData = function(elem) {
  $(elem).data('appearAt', ($(elem).offset().top > mainHeight) ? parseInt($(elem).offset().top - (mainHeight + headerH)) : $(elem).offset().top);
  $(elem).data('disappearAt', parseInt(($(elem).offset().top - headerH) + parseInt($(elem).outerHeight())));
}

/* calculate a centering-offset for all animations and position them initially */
Schneider.animation.positionAnimationContainer = function() {
  var elementSet = $('.animation, .container')
  elementSet.each(function(index, element){
    var referenceHeight = mainHeight;
    if(index == 0) {
      referenceHeight = windowH - $('#head').innerHeight();
    }else if(index ==  (elementSet.length - 1)){
      //referenceHeight = $(window).innerHeight() - $('#bottom_wrapper').innerHeight();
    }
    var offset = referenceHeight/2 - (parseInt($(this).height())/2);
    if(offset < 0){
        offset = 0;
    }
    $(this).data('centeringOffset', offset);

    if($(this).is(visibleAnimation)){
      visibleAnimation.css({
        'position' : 'fixed',
        'top' : offset + headerH
      });
    }else{
      $(this).css('top', offset);
    }
  });
};

/* calculate number of active animation-steps and trigger animation */
Schneider.animation.animate = function() {
  var activeAnimationStep = 0;
  var id = visibleModule.attr('id');

  for(var i = 0; animationOffsets[id]['offsets'][i]; i++){
      if(animationOffsets[id]['offsets'][i] < newTop){
        activeAnimationStep++;
      }
  }

  Schneider.animation.setAnimationStep(activeAnimationStep);
}

/* execute animation either main or standalone one */
Schneider.animation.setAnimationStep = function(step) {
  var id = visibleModule.attr('id');
  if(Schneider.animation.animationSteps.hasOwnProperty(id)){
    var animationSteps = Schneider.animation.animationSteps[id];
    var standaloneAnim = visibleModule.find('.independent-animation');

    if(step > animationSteps.length - 1){
      step = animationSteps.length - 1;
    }

    if(standaloneAnim.length){
      standaloneAnim.css('background-position', animationSteps[step]);
    }else{
      visibleAnimation.css('background-position', animationSteps[step]);
    }
  }
}

/* on scrolls and reorientation set all preceding modules in final animation state */
Schneider.animation.animatePreviousModules = function(){
  var saveActiveModule = visibleModule;
  var prevModules = visibleModule.prevAll('.module');
  prevModules.each(function(index, element){
    visibleModule = $(this); visibleAnimation = visibleModule.find('.animation');
    var id = visibleModule.attr('id');
    Schneider.animation.loosenVisibleAnimationBottom();
    Schneider.animation.setAnimationStep((Schneider.animation.animationSteps[id].length -1));
  });
  //and reset
  visibleModule = saveActiveModule; visibleAnimation = visibleModule.find('.animation');
}

/* on scrolls and reorientation set all following modules in initial animation state */
Schneider.animation.resetFollowingModules = function() {
  var saveActiveModule = visibleModule;
  var nextModules = visibleModule.nextAll('.module');
  nextModules.each(function(index, element){
    visibleModule = $(this); visibleAnimation = visibleModule.find('.animation');
    var id = visibleModule.attr('id');
    Schneider.animation.loosenVisibleAnimation();
    Schneider.animation.setAnimationStep(0);
  });
  //and reset
  visibleModule = saveActiveModule; visibleAnimation = visibleModule.find('.animation');
}

/* if user uses scrollbar, reloads or tries to break the site / find your way home */
Schneider.animation.findActiveModule = function() {
  clearTimeout(orientationTimeout);
  if(isFindActiveModuleRunning === false){
    arrow.css('display', 'none');
    Schneider.animation.positionArrow();
    isFindActiveModuleRunning = true;
    newTop = $(window).scrollTop();
    var foundActiveModule = false;
    var targetDiff = 10000; var diff = false;
    if(newTop < $('.first').next().data('appearAt')){
      visibleModule = $('.first');
      Schneider.animation.setupModuleParams();
      Schneider.animation.fixVisibleAnimation();
    }else{
      $('.module').each(function(index, element){
        var diff = newTop - $(this).data('appearAt');
        if((diff >= 0 && diff < targetDiff)) {
          targetDiff = diff;
          visibleModule = $(this);
          Schneider.animation.setupModuleParams();
          Schneider.animation.fixVisibleAnimation();
        }else if(diff < 0){
          foundActiveModule = true;
        }
      });
    }

    Schneider.animation.animatePreviousModules();
    Schneider.animation.resetFollowingModules();
    //set navigation
    $('#dot-navigation .active').removeClass('active').parent().find('a[href="#' + visibleModule.attr('id') + '"]').addClass('active').parent().css('z-index', '15');

    $(window).off('scroll');
    var scrollTarget = visibleModule.offset().top - headerH;
    if(scrollTarget < mainHeight){
      scrollTarget = 0;
    }
    $.scrollTo(scrollTarget, 200, {
      'onAfter' : function(){
        $(window).on('scroll', Schneider.animation.scrollHandler);
        //set into correct transition mode
        transitionToPrevStarted = false;
        transitionToNextStarted = false;
        //and "action!"
        $(window).scroll();
        orientationTimeout = false;
        arrowShowing = true;
        Schneider.animation.positionArrow();

        arrow.fadeIn(150, function() {
          Schneider.animation.animateArrow();
        });
        window.setTimeout('isFindActiveModuleRunning = false;', 2000);
      }
    });
  }
}

Schneider.animation.setupModuleParams = function() {
  visibleAnimation = visibleModule.find('.animation');
  nextModuleBorder = visibleModule.next().data('appearAt');
  arrowShowTrigger = nextModuleBorder - arrowTreshold;
  arrowHideTrigger = nextModuleBorder + arrowTreshold;
  if(!visibleModule.hasClass('first')){
    prevModuleBorder = visibleModule.prev().data('disappearAt');
    prevModuleUpperBorder = visibleModule.offset().top - mainHeight;
  }else{
    prevModuleBorder = 0;
    prevModuleUpperBorder = 0;
  }
}

/* check if next module is coming up / control Transition */
Schneider.animation.checkModuleTransition = function() {
  //check if arrow is supposed to be showing
  if((newTop >= arrowShowTrigger || newTop < arrowTreshold || (newTop > prevModuleBorder && (newTop < prevModuleBorder + arrowTreshold && !visibleModule.hasClass('last')))) && arrowShowing === false && transitionToNextStarted === false && !visibleModule.hasClass('first')){
    arrowShowing = true;
    Schneider.animation.positionArrow();

    arrow.fadeIn(150, function() {
      Schneider.animation.animateArrow();
    });
  }

  if(arrowShowing === true && ((newTop <= arrowShowTrigger && newTop > arrowTreshold && newTop > (prevModuleBorder + arrowTreshold)) || newTop >= arrowHideTrigger || newTop < prevModuleBorder)){
    arrow.stop(true, true).fadeOut(300, function() {
      $(this).css('display', 'none');
      Schneider.animation.positionArrow();
    });
    arrowShowing = false;
  }



  /* scroll down / next Module starts showing */
  if(newTop > nextModuleBorder &&  transitionToNextStarted === false){
    Schneider.animation.loosenVisibleAnimationBottom();
    transitionToNextStarted = true;

    arrow.clearQueue().css({
      'position' : 'absolute',
      'top' : function() {return (visibleModule.offset().top + visibleModule.innerHeight()) - arrowH - 25; }
    });
    Schneider.animation.animateArrow();
		return true;
  }

  /* scroll up / next Module was showing / reattach current Animation */
  if(newTop < nextModuleBorder && transitionToNextStarted === true){
    Schneider.animation.fixVisibleAnimation();
    transitionToNextStarted = false;
		return true;
  }

  /* scroll down / current Module disappeard / switch to next module */
  if(newTop >= visibleModule.data('disappearAt') && transitionToNextStarted === true){
    if(!visibleModule.is($('.module:last'))){
      visibleModule = visibleModule.next();
      Schneider.animation.setupModuleParams();
      //make new menupoint active
      var nav = $('#dot-navigation a[href="#' + visibleModule.attr('id') + '"]');
      nav.addClass('active').prev().prev().removeClass('active');
    }

    Schneider.animation.fixVisibleAnimation();
    transitionToNextStarted = false;
		return true;
  }

  /* scroll up / previous module starts showing */
  if(newTop < prevModuleBorder && transitionToPrevStarted === false){
    Schneider.animation.loosenVisibleAnimation();
    transitionToPrevStarted = true;
		return true;
  }

  /* scroll down / previous module was showing / reattach current animation */
  if(newTop > prevModuleBorder && transitionToPrevStarted === true){
    Schneider.animation.fixVisibleAnimation();
    transitionToPrevStarted = false;
		return true;
  }

  /* scroll up / current module disappeared / switch to previous module */
  if(newTop <= prevModuleUpperBorder && transitionToPrevStarted === true){
    if(!visibleModule.hasClass('first')){
      visibleModule = visibleModule.prev();
      Schneider.animation.setupModuleParams();

      //make new menupoint active
      var nav = $('#dot-navigation a[href="#' + visibleModule.attr('id') + '"]');
      nav.addClass('active').next().next().removeClass('active');
    }

    Schneider.animation.fixVisibleAnimation();
    transitionToPrevStarted = false;
  }
}

/* set animation and background in fixed state no other modules visible */
Schneider.animation.fixVisibleAnimation = function (domObj) {
  if(domObj instanceof jQuery){
    var moduleObj = domObj;
    var animationObj = moduleObj.find('.animation');
  }else{
    moduleObj = visibleModule;
    animationObj = visibleAnimation;
  }

  if($.browser.msie && $.browser.version < 9){
    if(!moduleObj.hasClass('last') && !moduleObj.hasClass('first')){
      moduleObj.find('.bg').css({
        'position': 'fixed',
        'top' : '0'
      });
    }
  }else{
    moduleObj.css({
      'background-attachment' : 'fixed',
      'background-position' : 'top center'
    });
  }

  animationObj.css({
    'position' : 'fixed',
    'top' : visibleAnimation.data('centeringOffset') + headerH
  });
}

/* set animation and background in initial scroll mode */
Schneider.animation.loosenVisibleAnimation = function (domObj) {
  if(domObj instanceof jQuery){
      var moduleObj = domObj;
      var animationObj = moduleObj.find('.animation');
    }else{
      moduleObj = visibleModule;
      animationObj = visibleAnimation;
    }

  if($.browser.msie && $.browser.version < 9){
    moduleObj.find('.bg').css({
      'position' : 'absolute',
      'top' : '0'
    });
  }else{
    if(!moduleObj.hasClass('portrait')){
      moduleObj.css({
        'background-attachment' : 'scroll',
        'background-position' : 'top center'
      });
    }
  }

  animationObj.css({
    'position' : 'absolute',
    'top' : visibleAnimation.data('centeringOffset')
  });
}

/* set animation and background in end scroll mode (transition to next module is iminent) */
Schneider.animation.loosenVisibleAnimationBottom = function (domObj) {
  if(domObj instanceof jQuery){
    var moduleObj = domObj;
    var animationObj = moduleObj.find('.animation');
  }else{
    moduleObj = visibleModule;
    animationObj = visibleAnimation;
  }
  offset = (moduleObj.outerHeight() - mainHeight - headerH);

  animationObj.css({
    'position' : 'absolute',
    'top' : offset + visibleAnimation.data('centeringOffset')
  });

  if($.browser.msie && $.browser.version < 9){
    moduleObj.find('.bg').css({
      'position' : 'absolute',
      'top' : offset
    });
  }else{
    if(!moduleObj.hasClass('portrait')){
      moduleObj.css({
        'background-attachment' : 'scroll',
        'background-position' : 'center ' + offset + 'px'
      });
    }
  }
}

/* fake full size background for ie8 and ie7 / if this looks smoother to the naked eye,
 * be warned that it is cpu intensive */
Schneider.animation.fullFrameBgIE = function () {
  $('.module').each(function(index, context){
    $(this).find('.bg').remove();
    var container = $('<div class="bg"></div>').css({'width' : $(window).innerWidth() + 'px', 'height' : windowH + 'px'});
    var url = $(this).css('background-image');
    //7 to chars at the end - the 5 we cut in front totals 2 chars cut at the end
    url = url.substr(5, (url.length - 7));
    var img = $('<img />').attr('src', url);
    img.appendTo(container);
    container.appendTo($(this));
  });
}

$(function(){
  if(!$.browser.msie){
    jQuery.fx.interval = 85;
  }
  Schneider.animation.init();
  Schneider.animation.bind();
  if($.browser.msie && $.browser.version < 9){
    Schneider.animation.fullFrameBgIE();
    $(window).off('resize').on('resize', function() {
      Schneider.animation.adaptToResize();
      Schneider.animation.fullFrameBgIE();
    });
  }
  Cufon.replace('h1', {'fontFamily' : 'Frutiger Next Pro 700'});
  Cufon.replace('h2', {'fontFamily' : 'Frutiger Next Pro 300'});
  Cufon.replace('.text span, #module-14 p', {'fontFamily' : 'Frutiger Next Pro 300'});
});
