/* Author: 

*/

// function documentCoordinateToViewportCoordinate(x,y) {
  // var coord = new Object();
  // coord.x = x - window.pageXOffset;
  // coord.y = y - window.pageYOffset;
  // return coord;
// }
// 
// function viewportCoordinateToDocumentCoordinate(x,y) {
  // var coord = new Object();
  // coord.x = x + window.pageXOffset;
  // coord.y = y + window.pageYOffset;
  // return coord;
// }
// 
// function elementFromPointIsUsingViewPortCoordinates() {
  // if (window.pageYOffset > 0) {     // page scrolled down
    // return (window.document.elementFromPoint(0, window.pageYOffset + window.innerHeight -1) == null);
  // } else if (window.pageXOffset > 0) {   // page scrolled to the right
    // return (window.document.elementFromPoint(window.pageXOffset + window.innerWidth -1, 0) == null);
  // }
  // return false; // no scrolling, don't care
// }
// 
// function elementFromDocumentPoint(x,y) {
  // if (elementFromPointIsUsingViewPortCoordinates()) {
    // var coord = documentCoordinateToViewportCoordinate(x,y);
    // return window.document.elementFromPoint(coord.x,coord.y);
  // } else {
    // return window.document.elementFromPoint(x,y);
  // }
// }
// 
// function elementFromViewportPoint(x,y) {
  // if (elementFromPointIsUsingViewPortCoordinates()) {
    // return window.document.elementFromPoint(x,y);
  // } else {
    // var coord = viewportCoordinateToDocumentCoordinate(x,y);
    // return window.document.elementFromPoint(coord.x,coord.y);
  // }
// }

$(window).load(function() {
	
	function sectionFromPoint(offsetY){
		log('sec at: ' + offsetY);
		var secHeight = 0;
		var section = null;
	
		$('.section').each(function(){
			if($(this).height() + secHeight >= offsetY){
				section = $(this);
				return false;
			}
			
			secHeight += $(this).height();
		});
		
		
		if(section == null && (offsetY >= secHeight)){
			// log(section);
			section = $('.section').last();
		}	
		// if(offsetY >= secHeight)
// 			
		return section;
	}
	
	Scroller = function(element) {
  		this.element = element;
	  	this.startTouchY = 0;
  		this.animateTo(0);

  		element.addEventListener('touchstart', this, false);
		element.addEventListener('touchmove', this, false);
	    element.addEventListener('touchend', this, false);
	    element.addEventListener('webkitTransitionEnd', this.transitionEnd, false);
	    window.addEventListener('orientationchange',this.orientationChange, false);
	}

	Scroller.prototype.handleEvent = function(e) {
  		switch (e.type) {
    		case 'touchstart':
      			this.onTouchStart(e);
      			break;
    		case 'touchmove':
		        this.onTouchMove(e);
      			break;
    		case 'touchend':
      			this.onTouchEnd(e);
      			break;
  		}
	}

	Scroller.prototype.onTouchStart = function(e) {
	  // This will be shown in part 4.
	  // alert('bahahah');
	  
	  this.stopMomentum();
	
	  this.startTouchY = e.touches[0].clientY;
	  this.startTouchTime = Date.now();
	  this.contentStartOffsetY = this.contentOffsetY;
	}

	Scroller.prototype.onTouchMove = function(e) {
	  if (this.isDragging()) {
	    var currentY = e.touches[0].clientY;
	    var deltaY = currentY - this.startTouchY;
	    var newY = deltaY + this.contentStartOffsetY;
	    this.animateTo(newY);
	  }
	}

	Scroller.prototype.onTouchEnd = function(e) {
		this.endTouchY = e.changedTouches[0].clientY; 
		this.endTouchTime = Date.now();
		if (this.isDragging()) {
			if (this.shouldStartMomentum()) {
		  		// This will be shown in part 3.
		      	this.doMomentum();
		    } else {
		      	this.element.style.webkitTransition = '';
		      	this.snapToBounds();
		    }
	    }
	}
	
	Scroller.prototype.transitionEnd = function(e) {
		x.inTransition = false;
		
		x.snapToSection();
		//check and make not of the section currently in the viewport
		log('ending');
		var el = window.document.elementFromPoint(600,160);
	    x.currentSection = $(el).parents('.section');
	    // log(x.currentSection);
	}

	Scroller.prototype.orientationChange = function(e){
		log('orienting');
		log(x.currentSection.position().top);
		x.animateTo(-x.currentSection.position().top);
		x.snapToBounds();	
	}

	Scroller.prototype.animateTo = function(offsetY) {
  		this.contentOffsetY = offsetY;
	  	// We use webkit-transforms with translate3d because these animations
	  	// will be hardware accelerated, and therefore significantly faster
	  	// than changing the top value.
  		this.element.style.webkitTransform = 'translate3d(0, ' + offsetY + 'px, 0)';
		// log(document.window.elementFromPoint(300, Math.abs(this.contentOffsetY)));
	}

	// Implementation of this method is left as an exercise for the reader.
	// You need to measure the current position of the scrollable content
	// relative to the frame. If the content is outside of the boundaries
	// then simply reposition it to be just within the appropriate boundary.
	Scroller.prototype.snapToBounds = function() {
		log('bounds');
	 	if(this.contentOffsetY > 0){
	 		this.animateTo(0);
	 		return;
	 	}
	
	 	var btmCoord = parseInt(this.contentOffsetY * (-1), 10) + parseInt(window.innerHeight,10) - 146;
	 	var ch = 0;
	 	
	 	if(window.location.href.indexOf('news') != -1){
	 		ch = $('#content').height();	
	 	}else{
		 	$('#content .section').each(function(){
		 		ch += $(this).height();
		 	});
		}
		
	 	if(btmCoord > ch){
	 		this.animateTo((ch + 146 - window.innerHeight) * (-1));
	 	}  
	}
	
	// This method will snap to different sections of the website content
	// after the transition has finished
	Scroller.prototype.snapToSection = function() {
		// log('snappingSection: ' + this.contentOffsetY);
		// var el = document.elementFromPoint(600, Math.abs(this.contentOffsetY));
		// var el2 = elementFromDocumentPoint(600, Math.abs(this.contentOffsetY));
		// log(el2);
		// log( $(document.window.elementFromPoint(300, x.contentOffsetY *(-1))).parentUntil('.section') );
	}
	
	// Implementation of this method is left as an exercise for the reader.
	// You need to consider whether their touch has moved past a certain
	// threshold that should be considered ‘dragging’.
	Scroller.prototype.isDragging = function() {
	 	return true; 
	}
	
	// Implementation of this method is left as an exercise for the reader.
	// You need to consider if the end velocity of the drag was past the
	// threshold required to initiate momentum.
	Scroller.prototype.shouldStartMomentum = function() {
	  	if(Math.abs(this.getEndVelocity()) >= 0.12)
	  		return true;
	}
	
	Scroller.prototype.getEndVelocity = function(endPos) {
	  	var deltaY = this.startTouchY - this.endTouchY;
	  	var deltaTime = this.endTouchTime - this.startTouchTime;
	  	// var velocity = deltaY/(deltaTime*1000);
	  	var velocity = - deltaY/(deltaTime);
	  	// log('deltay: ' + deltaY);
	  	// log('deltaTime:' + deltaTime);
	  	// log('velocity:' + velocity); 
	  	return velocity;
	}
	
	Scroller.prototype.isDecelerating = function(){
		return this.inTransition;
	}
	
	Scroller.prototype.doMomentum = function() {
		this.inTransition = true;
		// Calculate the movement properties. Implement getEndVelocity using the
	  	// start and end position / time.
	  	var velocity = this.getEndVelocity();
		var acceleration = velocity < 0 ? 0.0007 : -0.0007;
	  	var displacement = - (velocity * velocity) / (2 * acceleration);
	  	var time = - velocity / acceleration;
		
		var newY;
		if(this.contentOffsetY + displacement > 0 || (window.location.href.indexOf('news') != -1)){
			//if trying to go above the top bounds of the content
			//continue with standard behavious and snapToBounds() will fix it 
			newY = this.contentOffsetY + displacement;
		}else{
			var el = sectionFromPoint(Math.abs(this.contentOffsetY + displacement));
			// log(el);
			sectionBottom = el.position().top + el.height();
			pointOffset = sectionBottom - Math.abs(this.contentOffsetY + displacement);
			if((el.height()/2) <= pointOffset){
				//snap to top of the section
				newY = -el.position().top;
			} else{
				//snap to next section but only if thers is a sibling
				if(el.next().length != 0)
					newY = -el.next().position().top;
				else
					newY = this.contentOffsetY + displacement;
			}
		}
		
	  	// Set up the transition and execute the transform. Once you implement this
	  	// you will need to figure out an appropriate time to clear the transition
	  	// so that it doesn’t apply to subsequent scrolling.
	  	this.element.style.webkitTransition = '-webkit-transform ' + time + 'ms cubic-bezier(0.33, 0.66, 0.66, 1)';
	  	log(this.element.style.webkitTransition);
	  	// var newY = this.contentOffsetY + displacement;
	  	this.contentOffsetY = newY;
	  	this.element.style.webkitTransform = 'translate3d(0, ' + newY + 'px, 0)';
	  	this.snapToBounds();
	}
	
	Scroller.prototype.stopMomentum = function() {
  		if (this.isDecelerating()) {
    		// Get the computed style object.
    		var style = document.defaultView.getComputedStyle(this.element, null);
    		// Computed the transform in a matrix object given the style.
    		var transform = new WebKitCSSMatrix(style.webkitTransform);
    		// Clear the active transition so it doesn’t apply to our next transform.
    		this.element.style.webkitTransition = '';
    		// Set the element transform to where it is right now.
    		this.animateTo(transform.m42);
  		}
	}
	
	function secondaryNav(e, scroller){
		var offsetTop = 113;
		var targetID = cutID(e.currentTarget.href);
		//the value needs to be negative cos we are pushing conent up
		scroller.animateTo(-$(targetID).position().top);
		// alert($(targetID).position().top);
	};
	
	function secondaryNavDOM(){
		if(window.location.href.indexOf('companies') != -1)
			return true;
		//rearrange the DOM so secondary navigation stays fixed
		// log(settings); 			
		var promo = $('body').find("#promos").detach();
		promo.insertBefore('#main').css('top','113px');
	}
	
	x = null;
	if(navigator.userAgent.match(/iPad/i)){
		// log(window.location.href);
		secondaryNavDOM();
		document.body.addEventListener('touchmove', function(e) {
			// This prevents native scrolling from happening.
			e.preventDefault();
		}, false);
		// log('bless');
		x = new Scroller(document.getElementById('ajaxContent'));
		
		$('body').ajaxStart(function(e, xhr, settings) {
			$(this).find("#promos").remove();
		});
	
		$('body').ajaxComplete(function(e, xhr, settings) {
			$('#promos a').unbind('click');
			$('#promos a').click(function(e){
				secondaryNav(e, x);
			});
			//make sure the content goes back to top when new page is loaded
			x.animateTo(0);
				
			secondaryNavDOM();
			if(window.location.href.indexOf('news') != -1){
				var content = $('#content');
				
				if(content.css('background-image') == 'none')
					return true;
				var img = $('<div/>').addClass('news-bg')
							.css({
								'position' : 'absolute',
								'top' : '113px',
								'overflow': 'hidden',
								'width': '100%'
							}) 
							.append($('<img/>').attr('src', content.css('background-image').slice(4,-1))
									.attr('height', $(window).height() - 142)
	      					);
				img.insertBefore('#main');
				content.css('background-image','none');
			} else{
				//$('#up, #down').find('a').attr('style', '');	
				$('.news-bg').remove();
			}
		});
		
		$(window).unbind('scrollstop');
	}
	
	if(window.location.href.indexOf('news') != -1){
		log('its the news');
		$('#content').find('a').click(function(evt){
			evt.preventDefault();
		});
		$('#videoContainer').css('visibility', 'visible');
		$('#up, #down').find('a').css('display', 'none');
	}
	
	$('body').ajaxComplete(function(e, xhr, settings){
		if(window.location.href.indexOf('news') != -1){
			$('#content').find('a').click(function(evt){
				if($(this).hasClass('article-ext'))
					return true;
				log(this);	
				evt.preventDefault();
				
				loadURL = $(this).attr('href');
				if($(this).hasClass('news-list-link')){
					loadText = 'news';
				}
				else{
					var start = $(this).attr('href').lastIndexOf('news/');
					loadText = $(this).attr('href').substr(start);
				}
				navLinks(loadURL, loadText, '')
			});
			$('#up, #down').find('a').css('display', 'none');
			$('#videoContainer').css('visibility', 'hidden');
			
			// var content = $('#content');
			// //if conent doesn't have a backgorund image (which will occur if someone 
			// //refreshes on the news page) then skip the background image hack 
			// if(content.css('background-image') == 'none')
				// return true;
// 			
			// var img = $('<div/>').addClass('news-bg')
						// .css({
							// 'position' : 'absolute',
							// 'top' : '113px',
							// 'overflow': 'hidden',
							// 'width': '100%',
							// 'z-index': '-10'
						// }) 
						// .append($('<img/>').attr('src', content.css('background-image').slice(4,-1).replace(/"/g, ''))
								// .attr('height', $(window).height() - 142)
      					// );
			// img.insertBefore('#main');
			// content.css('background-image','none');
		} else{
			$('#videoContainer').css('visibility', 'visible');
			//$('#up, #down').find('a').attr('style', '');	
			// $('.news-bg').remove();
		}
	})	
	
});






















