jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};

var GS = GS || {};

GS.Transition = (function ($){
	var animationDuration = 600,
		boxAnimationDelayIncrement = 50,
		secondGridAnimationDelay = animationDuration/100*90,
		transitionIndex = -1;

	function setTransitionIndex( newVal ) {
        transitionIndex = newVal;
		$('body').data('transitionIndex',newVal);
	}

	function getTransitionIndex() {
		transitionIndex = $('body').data('transitionIndex');
		return transitionIndex;
	}

	function calculateTransitionIndex() {
		var transitionIndexValue = null;

		if($('body').hasClass('transition-in-progress')) {
			return transitionIndexValue;
		}
		
		var pathname = window.location.pathname.substring(window.location.pathname.indexOf('/')+1);

		var t;
		var timer_is_on=0;

		function timedCheck()
		{
			if( $('#main-nav > ul > li > strong').length < 1 ) {
				t=setTimeout(timedCheck,100);
			} else {
				stopCheck();
				var currentNav = $('#main-nav > ul > li a.toplevel[href$="'+pathname+'"], #sub-nav > ul > li a.toplevel[href$="'+pathname+'"]');
				transitionIndex = $('#main-nav > ul > li').index(currentNav.closest('li'));
				setTransitionIndex(transitionIndex);
				return transitionIndex;
			}
		}

		function doTimer()
		{
			if (!timer_is_on) {
				timer_is_on = 1;
				timedCheck();
			}
		}

		function stopCheck()
		{
			clearTimeout(t);
			timer_is_on = 0;
		}
		if($('body#homepage').size() > 0) {
			transitionIndex = -1;
			setTransitionIndex(transitionIndex);
			return transitionIndex;
		} else {
			doTimer();
		}
	}

	function swipeTransitions(){
		if (Modernizr.touch){
			var swipeOptions = {
				swipeLeft: function(){
					doTransition(1);
				},
				swipeRight: function(){
					doTransition(-1);
				},
				threshold: 50
			}
			$('body.top-level').swipe(swipeOptions);
		}
	}
		
	function transitionGrid( newPageUrl, transitionDirection ) {

		if($('body').hasClass('transition-in-progress'))
			return false;
		// Hide the navigation overlay?
		$('#main-nav li').removeClass('active');

		$('body').addClass('transition-in-progress');
		var divWrapper = $('<div></div>');
		divWrapper.attr('id','grid-animation-wrapper');
		$('#content > article').wrapAll(divWrapper);

		var gridOffset = $('#grid-animation-wrapper').offset();
		var gridWidth = $('#grid-animation-wrapper').width();
		var newGrid = $('<div></div>');
		newGrid.attr('id','new-animation-grid');
		var containerWidth = $('section#content').width();

		newGrid.css({'top': gridOffset.top});

		if($.browser.msie){
			newGrid.loadShiv( newPageUrl + ' #content', function (){ 
				var fixhtml5 = $(innerShiv(newGrid.html(),false));
				fixhtml5.find('article').css('left', (containerWidth*transitionDirection) +'px');
				$('#content').append( newGrid.html( innerShiv( fixhtml5.html() ) ) );
				transitionToNewPageContent(newGrid, transitionDirection);
			});
		}
		else {
			newGrid.load( newPageUrl + ' #content', function (){ 
				newGrid.html(newGrid.find('#content').html());
				newGrid.children().css('left', (containerWidth*transitionDirection) +'px');
				$('#content').append(newGrid);
				transitionToNewPageContent(newGrid, transitionDirection);
			});
		}
	}
	
	function transitionToNewPageContent(newGrid, transitionDirection){
		var containerWidth = $('section#content').width();

		$('#grid-animation-wrapper > article').css('position', 'relative');
		var blockDelay = 0;
		var collectionOut = (transitionDirection == 1) ? $('#grid-animation-wrapper > article') : $('#grid-animation-wrapper > article').reverse();
		collectionOut.each(function (index, item){
			setTimeout(function (){
				$(item).animate({
					left: (-1 * (containerWidth) * transitionDirection)+"px"
				}, {
					duration: animationDuration, 
					easing: 'easeInExpo'
				});
			}, (blockDelay += boxAnimationDelayIncrement));
		});
		setTimeout(function (){
			var newGridBlockDelay = 0;
			var collectionIn = (transitionDirection == 1) ? $('#new-animation-grid > article') : $('#new-animation-grid > article').reverse();
			collectionIn.each(function (index, item){
				setTimeout(function (){
					$(item).animate({
						left: 0
					}, {
						duration: animationDuration, 
						easing: 'easeOutExpo'
					});
				}, (newGridBlockDelay += boxAnimationDelayIncrement));
			});
			setTimeout(function (){
				$('#grid-animation-wrapper').remove();
				$('#content').html($('#new-animation-grid').html());
				$('body').removeClass('transition-in-progress');
				updateOverlayLinks();
			}, newGridBlockDelay+1000);
		}, secondGridAnimationDelay);

		$('#main-nav > ul > li > strong > a').unwrap();
		if(transitionIndex > -1) {
			$('#main-nav > ul > li').eq(transitionIndex).find('a').eq(0).wrap('<strong></strong>');
		}
	}
	
	function prepOverlayLinks() {
		if(getTransitionIndex === 'undefined') {
			setTransitionIndex(-1);
		}
		calculateTransitionIndex();

		// $('.top-level #content').bind({
		// 	'mousemove': function(e){
		// 		var containerOffset = $(this).offset();
		// 		var containerWidth = $(this).width();
		// 		var targetWidth = (containerWidth >= 1200) ? 200 : 160;
		// 		var limits = {
		// 			'leftMin': 0,
		// 			'leftMax': targetWidth,
		// 			'rightMin': (containerWidth - targetWidth),
		// 			'rightMax': containerWidth
		// 		}
		// 		var coords = {
		// 			'left': e.pageX - containerOffset.left, 
		// 			'top': e.pageY - containerOffset.top
		// 		}
		// 		if(coords.left > limits.leftMin && coords.left < limits.leftMax) {
		// 			updateOverlayLinks();
		// 			manageOverlayLinks('#transitionPrevHolder','show');
		// 		} else {
		// 			manageOverlayLinks('#transitionPrevHolder','hide');
		// 		}
		// 		if(coords.left > limits.rightMin && coords.left < limits.rightMax) {
		// 			updateOverlayLinks();
		// 			manageOverlayLinks('#transitionNextHolder','show');
		// 		} else {
		// 			manageOverlayLinks('#transitionNextHolder','hide');
		// 		}
		// 	},
		// 	'mouseleave': function() {
		// 		manageOverlayLinks('#transitionPrevHolder','hide');
		// 		manageOverlayLinks('#transitionNextHolder','hide');
		// 	}
		// });
		
		var nextButton = $('<a>Next</a>');
		nextButton.attr({'id':'transitionNextButton', 'class': 'transitionButton'});
		nextButton.bind('click', function(){
			$(this).blur();
			doTransition(1);
		});
		nextButton.bind('mouseenter', updateOverlayLinks);
		var nextContainer = $('<span></span>');
		nextContainer.attr('id','transitionNextHolder');
		nextContainer.bind({
			'mouseenter': function(el){
				$(this).addClass('hover');
			},
			'mouseleave': function(el){
				$(this).removeClass('hover');
			}
		})
		nextContainer.append(nextButton);
		
		var prevButton = $('<a>Previous</a>');
		prevButton.attr({'id':'transitionPrevButton', 'class': 'transitionButton'});
		prevButton.bind('click', function(){
			$(this).blur();
			doTransition(-1);
		});
		prevButton.bind('mouseenter', updateOverlayLinks);
		var prevContainer = $('<span></span>');
		prevContainer.attr('id','transitionPrevHolder');
		prevContainer.bind({
			'mouseenter': function(el){
				$(this).addClass('hover');
			},
			'mouseleave': function(el){
				$(this).removeClass('hover');
			}
		})
		prevContainer.append(prevButton);

		$('body #wrapper').append(prevContainer, nextContainer);

		// manageOverlayLinkVisibility();

		// previewTransitionEffects(prevButton);
		// previewTransitionEffects(nextButton);
	}

	function previewTransitionEffects(el){
		if(el){
            el = el instanceof jQuery ? el : $(el);
			el.css({
				'opacity': 0,
				'display': 'block'
			})
			.show()
			.delay(3000)
			.animate(
				{opacity: 1},
				1000,
				function (){
					$(this).delay(5000).fadeOut(1000,function(){
						$(this).attr('style','position: relative;'); //Reset styles to stop IE messing up
					});
				}
			);
		}
	}

	function manageOverlayLinks(el,action){
		if(el){
			if(action == 'show') {
				$(el).removeClass('forceHide').addClass('active');
			} else if(action == 'hide'){
				$(el).removeClass('forceHide').removeClass('active');
			} else if(action == 'disable'){
				$(el).addClass('forceHide')
			}
		}
	}

	function manageOverlayLinkVisibility(){
		if(transitionIndex <= -1){
			$('#transitionPrevHolder, #transitionPrevButton').addClass( 'forceHide' );
		} else {
			$('#transitionPrevHolder, #transitionPrevButton').removeClass( 'forceHide' );
		}
	}


	function updateOverlayLinks() {
		var tIndex = parseInt(transitionIndex);
		var nextText = ( (tIndex + 1) == $('#main-nav > ul > li').size() ) ? 'HOMEPAGE' : $('#main-nav > ul > li').eq(tIndex + 1).find('a').eq(0).text();
		var prevText = (tIndex == 0 ) ? 'HOMEPAGE' : ( tIndex == -1 ? $('#main-nav > ul > li').last().find('a').eq(0).text() : $('#main-nav > ul > li').eq(tIndex - 1).find('a').eq(0).text() );
		
		$('#transitionNextButton').text( nextText );
		$('#transitionPrevButton').text( prevText );
	}

	function doTransition(moveDirection, updateIncrement){
		moveDirection = moveDirection ? moveDirection : 1;
		updateIncrement = updateIncrement ? ((updateIncrement === 'no') ? false : true ) : true;
		
		$('.transitionButton').blur();
		$('#transitionPrevHolder, #transitionNextHolder').removeClass('active').blur();
		
		if(transitionIndex <= -1 && moveDirection == -1){
			// alert('No left turn!');
			// $('#transitionNextHolder, #transitionNextButton').removeClass( 'forceHide' );
			// $('#transitionPrevHolder, #transitionPrevButton').addClass( 'forceHide' );
			// return false;
		// } else if(transitionIndex >= ($('#main-nav > ul > li').size() -1) && moveDirection == 1){
		// 	alert('No right turn!');
		// 	$('#transitionNextHolder, #transitionNextButton').addClass( 'forceHide' );
		// 	$('#transitionPrevHolder, #transitionPrevButton').removeClass( 'forceHide' );
		// 	return false;
		} else {
			$('#transitionNextHolder, #transitionNextButton').removeClass( 'forceHide' );
			$('#transitionPrevHolder, #transitionPrevButton').removeClass( 'forceHide' );
		}

		if(updateIncrement === true) {
			setTransitionIndex( transitionIndex + moveDirection );
		}
		if (transitionIndex <= -2) {
			setTransitionIndex( $('#main-nav > ul > li').size() - 1 );
			// setTransitionIndex( -1 );
		} else if (transitionIndex >= $('#main-nav > ul > li').size()) {
			setTransitionIndex( -1 );
			// setTransitionIndex( $('#main-nav > ul > li').size() - 1 );
		}

		var targetURL = (transitionIndex == -1) ? $("#homelink a")[0].href : $('#main-nav > ul > li').eq(transitionIndex).find('a')[0].href;

		// $('#main-nav > ul > li > strong > a').unwrap();
		// if(transitionIndex > -1) {
		// 	$('#main-nav > ul > li').eq(transitionIndex).find('a').eq(0).wrap('<strong></strong>');
		// }
		History.pushState(null, null, targetURL);
		// $(this).blur();
		transitionGrid(targetURL, moveDirection);
	};

	function prepTouchOverlay() {
		var touchOverlay = $('<span>Swipe enabled</span>');
		touchOverlay.attr('id','touchOverlay');

		$('body #wrapper').append(touchOverlay);
		previewTransitionEffects(touchOverlay);
		// $('ul#marketing-nav li a.toplevel').bind({
		// 	'click': function (event){
		// 		event.preventDefault();
		// 		event.stopPropagation();
		// 		return false;
		// 	}
		// });
		
	}

	$(function (){
		if (Modernizr.touch){
			prepTouchOverlay();
		} else {
			prepOverlayLinks();
		}

		(function(window,undefined){

			var History = window.History; // Note: We are using a capital H instead of a lower h

			History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
				var State = History.getState(); // Note: We are using History.getState() instead of event.state
				//History.log(State.data, State.title, State.url);
				var oldIndex = transitionIndex;
				var targetLink = $('#main-nav').find('a[href$="'+State.url.substring(State.url.replace('http://','').indexOf('/')+1)+'"]');
				var newIndex = $('#main-nav > ul > li').index(targetLink.closest('li'));
				if(newIndex !== oldIndex && newIndex != -1) {
					setTransitionIndex( newIndex );
				}

				// Only fire the transition if we have something to transition from & to
				if( (History.getHash() != '' && window.location.pathname !== History.getHash()) || (oldIndex && oldIndex != transitionIndex) ){

					$('#main-nav > ul > li > strong > a').unwrap();
					$(targetLink).wrap('<strong></strong>');

					var transitionDirection = (oldIndex < transitionIndex) ? 1 : -1;

					if( targetLink.attr('href') != '#' ){
						transitionGrid(State.url, transitionDirection);
					}
				}
				
			});

		})(window);
        
/*
        if(!!history && !!history.pushState){
            $(window).bind("popstate", function(e) {
    			var oldIndex = transitionIndex;
    			var targetLink = $('#main-nav').find('a[href$="'+location.pathname.substring(location.pathname.indexOf('/')+1)+'"]');
    			transitionIndex = $('#main-nav > ul > li').index(targetLink.parent());

    			if(oldIndex != transitionIndex){
    				$('#main-nav > ul > li > strong > a').unwrap();
    				$(targetLink).wrap('<strong></strong>');

					var transitionDirection = (oldIndex < transitionIndex) ? 1 : -1;

					if( targetLink.attr('href') != '#' ){
						transitionGrid(location.pathname, transitionDirection);
					}
				}
			});
		}
*/
	});
    
    
    GS.Page.register({className: 'top-level'}, function (){
		// $("#main-nav ul li.active a.toplevel").die('touchstart');
    	$("#main-nav>ul>li>a, #main-nav ul li.active a.toplevel").live({
    		'click': function (event){
    			event.preventDefault();
    			event.stopPropagation();
    			$('.activeState').removeClass('activeState');
    			var target = event.target;

    			target = target.tagName.toLowerCase() != 'a' ? $(target).closest('a') : $(target);

    			var oldIndex = transitionIndex;
    			setTransitionIndex( $(target).parents('ul').find('>li').index($(target).parent()));
    			if(oldIndex != transitionIndex){
     				var transitionDirection = (oldIndex < transitionIndex) ? 1 : -1;
					doTransition(transitionDirection,'no');
    			}
    		}
    	});

    	$("#homelink a").live({
    		click: function (event){
    			event.preventDefault();
    			event.stopPropagation();
    			var oldIndex = transitionIndex;
    			setTransitionIndex( -1 );

				var transitionDirection = ( oldIndex == $('#main-nav > ul > li').size() ) ? 1 : -1;

    			$('#main-nav > ul > li > strong > a').unwrap();

				var transitionDirection = ( oldIndex == $('#main-nav > ul > li').size() ) ? 1 : -1;
				doTransition(transitionDirection,'no');
    		}
    	});

		swipeTransitions();
    });
})(jQuery);


