//Init
jQuery(function($){
	
		//setup for vars for different platforms.
		$.Body = $('body');
		$.Window = $(window);
		$.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
		
		//Grab each section and instatiate the scroll rates
		$('[data-controller]').Instantiate();
		
		$('#nav a').click(function(e){
			$self = $(this);
			$id = $self.parent().attr('data-id');
			$('body').triggerHandler($.Events.SCROLL_TO, $id);
			e.preventDefault();
		});
	}
);



//Events
(function($) {

  //create some custom events to fire in each section 
  $.Events = {

     SECTION_ENTER: 'sectionEnter',
     
     SCROLL_TO: 'scrollTo',
     
     SCROLL: 'windowScroll',
     SCROLL_ENTER: 'windowScrollEnter',
     SCROLL_LEAVE: 'windwScrollLeave'
  }
  
})(jQuery);




//Init each section
(function($) {

	//extend the $ object with an instatiation
  	$.fn.Instantiate = function(settings) {
     
	    var config = {};
 
	    if (settings) $.extend(config, settings);
  			
		//for each element in the document check whether it has a data-controller and call it
	    this.each(function() { 

	        var $self = $(this);
	        var $controller = $self.attr('data-controller');
              
  			//call the handler function for the controller
	        if ($self[$controller]){
				$self[$controller]();
			}
            
	    });
      
  	}
    
})(jQuery);


(function($){
	
	$.fn.SiteScroll = function() {

	     this.each(function() { 

	        var $self = $(this);

	        $('body')
	          .bind($.Events.SCROLL_TO,
	            function(e,id){

	              var $element = $('#'+id),
	                  $header = $element.find('h1'),
	                  _align = $element.attr('data-align'),
	                  _offset = $element.attr('data-scrolloffset') ? parseInt($element.attr('data-scrolloffset')) : 50,
	                  _top = $element.offset().top;

				/*
				Removed by Pablo - Not sure what this does but seems to break things.
	              if (_align=="center" && $element.height()>$(window).height()) {

	                _top = $element.offset().top; + ($element.height()-$(window).height())/2

	              }
				*/

	              $.Scroll
	                .stop()
	                .animate(
	                  { 'scrollTop': _top },
	                  800,
	                  'easeInOutQuart'
	                )

	            })
	     });

	    return this;

	}
	
	//standard method to scroll the background at a constant rate
	$.fn.Scrollable = function(settings) {
		
		 //threashold ?the amount to push ast the section without scrolling?
		 //offset-scroll ?
		 //inertia ?
	     var config = { threshold: -100, offset_scroll: 6, offset_intertia: .25 };

	     if (settings){
			$.extend(config, settings);
		 }

	     this.each(function(){ 
		
        	var $self = $(this),
	            $id = $self.attr('id');
	        
			config.threshold = 0;
			if ($.Mobile || $.Unsupported) {
				$self.css({backgroundAttachment:'scroll'})
			}else{
				//when we scroll the window check the pane is in view (scrolled pixels + height of element) and scroll at the rate below
		        $(window).bind('scroll', function(e){
		              if ($.inview($self,{threshold:config.threshold}) ) {
						//scroll the background
		                _scroll_background();
						//trigger the event to scroll inner elements
						$self.triggerHandler($.Events.SCROLL,$.distancefromfold($self,{threshold:config.threshold}) - config.threshold);
		              }
		        });
	
		        function _scroll_background(){
		          var _x = '50%';
		          var bpos = _x + (-($.distancefromfold($self,{threshold:config.threshold}) - config.threshold) * config.offset_intertia) + 'px';
		          $self.css({'backgroundPosition':bpos})
		        }
			}
		});
		
		return this;
	}

	$.fn.Home = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
	            _threshold = -200;

	        $self.Scrollable({threshold: _threshold})
	
	     });
	    
		return this;
  	}

	$.fn.Create = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
	            _threshold = -200;

	        $self.Scrollable({threshold: _threshold})
	
	     });
	    
		return this;
  	}

	$.fn.Work = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
				$fg = $self.find('.fg'),
	            _threshold = -200;
	            _threshold = 0; // Override

	        $self.Scrollable({threshold: _threshold})	.bind($.Events.SCROLL,on_scroll)

			//scroll the found items within the scrolling window
			function on_scroll(e,distance) {

	          var bpos = '50% ' + ($(window).height()/2.5-distance/3) + 'px';
	          $fg.css({'backgroundPosition':bpos})

	        }
	     });  
	
	  	return this;
	}
	
	$.fn.News = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
	            _threshold = -200;

	        $self.Scrollable({threshold: _threshold})
	     });  
	
	  	return this;
	}
	
	$.fn.Contact = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
	            _threshold = -200;

	        $self.Scrollable({threshold: _threshold})
	     });  
	
	  	return this;
	}
	
	$.fn.Are = function(){
		
	     this.each(function() { 

	        var $self = $(this),
	            $id = $self.attr('id'),
	            _threshold = -200;

	        $self.Scrollable({threshold: _threshold})
	     });  
	
	  	return this;
	}
	
})(jQuery);

(function($){

    $.distancefromfold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return (fold + settings.threshold) - $element.offset().top ;
    };
    
    $.belowthefold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $element.offset().top - settings.threshold;
    };

        
    $.abovethetop = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $element.offset().top + settings.threshold  + $element.height();
    };
    
    $.inview = function($element, settings) {
        return ($.abovethetop($element,settings)!=true && $.belowthefold($element,settings)!=true)
    };


    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold"  : "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold"   : "!$.rightoffold(a, {threshold : 0, container: window})"
    });
    
})(jQuery);
