/*
Original Parallax
Author: Ian Lunn
Author URL: http://www.ianlunn.co.uk/
Demo URL: http://www.ianlunn.co.uk/demos/recreate-nikebetterworld-parallax/
Tutorial URL: http://www.ianlunn.co.uk/blog/code-tutorials/recreate-nikebetterworld-parallax/

License: http://creativecommons.org/licenses/by-sa/3.0/ (Attribution Share Alike). Please attribute work to Ian Lunn simply by leaving these comments in the source code or if you'd prefer, place a link on your website to http://www.ianlunn.co.uk/.

Dual licensed under the MIT and GPL licenses:
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl.html
*/

(function(){

	$(document).ready(function() { //when the document is ready...
		//save selectors as variables to increase performance
		var $window = $(window);	
		var windowHeight = $window.height(); //get the height of the window
		var $loadCount = 0;
		var $parallaxCount = $('.parallax').length;
		
		$('.parallax').each(function(){
			var $parallaxBox = $(this);
			
			listenForView( $parallaxBox ); //Listen for when box is in view
			
			$parallaxBox.css({ 'background-attachment': 'fixed' });
		
			//Get Background image URL
			var bgUrl = $parallaxBox.css('background-image').replace( 'url("' , '').replace( '")' , '' ).replace( 'url(' , '').replace( ')' , '' );
			$parallaxBox.data( 'bgHeight', 0 );
			
			if (bgUrl) {
				var bgImg = $('<img />');
				var imgHeight = 0;
				bgImg.hide();
				$('body').append(bgImg);
				bgImg.bind('load', function()
				{
					$parallaxBox.data( 'bgHeight', $(this).height() );
					$(this).remove();
					$loadCount++;
				});
				bgImg.attr('src', bgUrl);
			}
		});
			
		//Setup Listener on Parallax to add "inview" class
		function listenForView( $view ){
			$( $view ).bind('inview', function(event, visible) {
		 		if (visible == true) {
					$(this).addClass("inview");
				}else{
					$(this).removeClass("inview");
				}
		    });	
		}
		
		//function that is called for every pixel the user scrolls. Determines the position of the background
		/*arguments: 
			x = horizontal position of background
			windowHeight = height of the viewport
			pos = position of the scrollbar
			adjuster = adjust the position of the background
			inertia = how fast the background moves in relation to scrolling
		*/
		function newPos(parallaxBox, boxHeight, bgHeight, inertia){
			var pos = $window.scrollTop(); //position of the scrollbar
			var x = '50%';
			var y = '50%';
			
			var boxOffset = (parallaxBox.offset().top + boxHeight - pos) / (windowHeight + boxHeight);
			//console.log(parallaxBox.attr('class')+': '+(boxOffset) );
			//console.log(parallaxBox.attr('class')+': '+bgHeight+", "+windowHeight)
			if(bgHeight > (windowHeight + inertia)){
				y = (0 - (inertia - (inertia * boxOffset))) + "px";
				//console.log(parallaxBox.attr('class')+': '+ y);
			} else {
				var diff = windowHeight + inertia - bgHeight;
				y = (diff - ((diff+inertia) - ((diff+inertia) * boxOffset))) + "px";
			}
			//return x + "% " + (-((windowHeight + pos) - adjuster) * inertia)  + "px";
			//console.log(x + "% " + (-((windowHeight + pos) - adjuster) * inertia)  + "px");
			return x +" "+ y;
		}
		
		//function to be called whenever the window is scrolled or resized
		function move(){ 
			$('.parallax.inview, .inview .parallax').each(function(){
				var $parallaxBox = $(this);
				//console.log($parallaxBox.attr('class') +', '+$parallaxBox.bgHeight);
				var maxMove = 300;
				$parallaxBox.css({'backgroundPosition':newPos($parallaxBox, $parallaxBox.height(), $parallaxBox.data('bgHeight'), maxMove)});
			});
		}
		
		$window.resize(function(){ //if the user resizes the window...
			windowHeight = $window.height(); //get the height of the window
			move(); //move the background images in relation to the movement of the scrollbar
		});		
		
		$window.bind('scroll', function(){ //when the user is scrolling...
			move(); //move the background images in relation to the movement of the scrollbar
		});
		
		//When Done Loading, position
		(function initialPosition(){ if ($loadCount < $parallaxCount) setTimeout( initialPosition, 1000); else move(); })();
	});

})();
