/**
 * Application Methods 1.0
 *
 * 12.04.2011
 *
 * mediaman technology
 */

// Init Global Variables
var container, pages, windowHeight, documentHeight;
// React earlier than current scroll position
var OFFSET = -250;
// Init
function init() {
  // Position all animated elements to their starting position
  // and set opactiy
  $('.animElement').each(function(i){
    // Get Data Attributes for starting Position
    // and set Element to Pixel Values

    $(this).css('margin-left', $(this).data('start')[0]+'px');
    $(this).css('margin-top', $(this).data('start')[1]+'px');
    // Set Display according to opacity attribute, needs to be faded in later
    if($(this).data('opacity')==true) {
      //$(this).css('display','none');
      $(this).animate({opacity:0},0);
    }
  });
  // Get all Panels
  var panels = $('#panels').find('div.panel');

  var panelMargin=($(window).width()-$('div.panel').first().width())/2;
  panels.each(function(i) {
    // Store start value in Pixels as Data on Object
    $(this).data('offset', {
      top: $(this).offset().top-1
    });
    // Apply calculated margin to panels
    //$(this).css('margin-left',panelMargin+'px');
    //$.trace($(this).attr('id')+ " starts at : "+String($(this).data('offset').top),'info');
  });
}
// Easing Method. Explanation omitted, no previous comments
function ease(value, max) {
   return Math.sin((value / max - 1) * Math.PI / 2) * max + max;
};
// getPanelforOffset returns the index of the panel the user is currently viewing
// accepts an numerical offset in pixels
function getPanelforOffset(offset) {
  // Pages Collection
  var panels = $('#panels').find('div.panel');
  // Var for return value
  var value = "";
  // Parse through pages
  panels.each(function(i) {
    // Check for last panel
    if($(this).index() == panels.length-1 && $(this).data('offset').top < offset){
      // Set Return Value for last panel und return false to stop each-loop
      //$.trace("last panel",'info');
      value = panels.length-1;
      return false;
    }
    // Check for all other panels
    if($(this).data('offset').top > offset){
      // Set Return Value for panel und return false to stop each-loop
      //$.trace("some other panel",'info');
      value = i-1;
      return false;
    }
  });
  // Return the panel index
  return value;
}
// Animate Panel with given index
function animatePanel(panelIndex, currentPanel, scrollTop) {
    // Get the Panel Object
    var panel=$('.panel:eq('+panelIndex+')');
    // Find Offsets
//		var posPageStart 		= panel.data('offset').top + OFFSET/1.5;
//		var posPageFirstQuarter	= posPageStart + (panel.height()/4);
//		var posPageLastQuarter 	= posPageStart + ((panel.height()/4)*3) + OFFSET/1.5;
//		var posPageEnd 			= posPageStart + panel.height() - OFFSET * 1.5;

    var posPageStart 		= panel.data('offset').top + OFFSET;
    var posPageFirstQuarter		= posPageStart + (panel.height()/4);
    var posPageLastQuarter	    	= posPageStart + ((panel.height()/4)*3) + OFFSET/2;
    var posPageEnd 			= posPageStart + panel.height();


    // Dump Debug
    /*$.trace('-------------------------------------------','debug');
    $.trace('panelIndex: '+panelIndex,'debug');
    $.trace('scrollTop: '+scrollTop,'debug');
    $.trace('posPageStart: '+posPageStart,'debug');
    $.trace('posPageFirstQuarter: '+posPageFirstQuarter,'debug');
    $.trace('posPageLastQuarter: '+posPageLastQuarter,'debug');
    $.trace('posPageEnd: '+posPageEnd,'debug');
    $.trace('-------------------------------------------','debug');*/
    // Scrolltop is in Range of Panel Start and Panel End
    if (scrollTop >= posPageStart && scrollTop < posPageEnd) {
      // First Quarter in this page
      if (scrollTop < posPageFirstQuarter) {
        // Scrolled Amount in Quarter
        // Height of Quarter - End of First Quarter minus Scroll Position
        var scrolled=(posPageFirstQuarter-posPageStart)-(posPageFirstQuarter-scrollTop);
        // Calculate the percentage scrolled in Quarter
        var scrollPercent=scrolled/((posPageFirstQuarter-posPageStart)/100);
        panel.find('.animElement').each(function(){
          var animation=getAnimationData($(this), scrollPercent);
          // Stop previously running animations on this object and animate to the new destination
          $(this).stop(true, true).animate(animation,'fast');
        });
      }
      // Optimal / Original position, Middle 600px of page
      if (scrollTop >= posPageFirstQuarter && scrollTop < posPageLastQuarter) {
        var scrollPercent=100;
        panel.find('.animElement').each(function(){
          var animation=getAnimationData($(this), scrollPercent);
          // Stop previously running animations on this object and animate to the new destination
          $(this).stop(true, true).animate(animation,'fast');
        });
      }
      // Last Quarter in this page
      if (scrollTop >= posPageLastQuarter) {
        // Height of Quarter - End of Last Quarter minus Scroll Position
        var quarterHeight=posPageEnd-posPageLastQuarter;
        var scrolled=quarterHeight-(posPageEnd-scrollTop);
        // Calculate the INVERTED percentage scrolled in Quarter
        var scrollPercent=100-(scrolled/((posPageEnd-posPageLastQuarter)/100));
        panel.find('.animElement').each(function(){
          var animation=getAnimationData($(this), scrollPercent);
          // Stop previously running animations on this object and animate to the new destination
          $(this).stop(true, true).animate(animation,'fast');
        });
      }
    }
    else {
      // Reset Objects to their starting position and opacity
      var scrollPercent=0;
      panel.find('.animElement').each(function(){
      var animation=getAnimationData($(this), scrollPercent);
        $(this).animate(animation,1);
      });
    }

}
// Construct Animation Object
function getAnimationData(obj, percent) {
  // Get Length of Animation path for both axes
  var xLength=obj.data('end')[0]-obj.data('start')[0];
  var yLength=obj.data('end')[1]-obj.data('start')[1];
  // Calculate the percentage of the full Path�s Length
  var pixelX=obj.data('start')[0]+((xLength/100)*percent);
  var pixelY=obj.data('start')[1]+((yLength/100)*percent);
  // Get Opacity for Percentage
  var opacity=(1.0/100)*percent;
  // Create Jquery Animation Object
  var animationReturn={};
  // Add Margin Data
  animationReturn['margin-left']=pixelX+'px';
  animationReturn['margin-top']=pixelY+'px';
  // If Opacity is configured for this object, also return opacity
  if (obj.data('opacity')) animationReturn['opacity']=opacity;
  else animationReturn['opacity']=1;
  // Return JQuery Animation Object
  if (obj.hasClass('whitebg')) animationReturn['opacity'] = 1-animationReturn['opacity'];
  return animationReturn;
}
// Fires on Scroll
function position() {
  // contains current scroll position
  var scrollTop = $(window).scrollTop();
  // get Index for current panel in viewport
  var currentPanel = getPanelforOffset(scrollTop);
  // Get Number of Panels
  var panelLength=$('.panel').length;
  // Check Animation for all Panels
  for(var i=0; i<panelLength; i++) {
    animatePanel(i, currentPanel, scrollTop);
  }
};
// Modernizr touch init (not used atm)
function touchInit() {
  //$.trace('touch init fired','info');
  // Nothing here
};
