//Main nav hover effect
function mainNavHover() {
	//find each link in the main nav bar and attach hover event
	$('#pageHeader a').hover(function(){
		//on mouse hover animates background in
		$(this).stop().animate({backgroundPosition: '0 -70'}, 300);
	}, function(){
		//on mouse leave animates background out if the active class hasnt been set by mainNavScroll()
		if ( $(this).attr('class') != 'active'){
			$(this).stop().animate({backgroundPosition: '0 0'}, 300);
		};
	});
}
//Main nav scroll effect
function mainNavScroll() {
	$window = $(window);
	
	// Cache the Y offset and the speed of each sprite
	$('[data-type]').each(function() {
	  $(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
	  $(this).data('speed', $(this).attr('data-speed'));
	});
	
	// on window scroll
	$window.scroll(function(){
		$('section').each(function(){
			// Store some variables based on where we are
			var $self = $(this),
			offsetCoords = $self.offset(),
			topOffset = offsetCoords.top;
			
			// If this section is in view
			if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
			( (topOffset + $self.height()) > $window.scrollTop() ) ) {
			
				  // Check for other sprites in this section
				$('[data-type="sprite"]', $self).each(function() {
				
				  // Cache the sprite
				  $sprite = $(this);
				
				  // Use the same calculation to work out how far to scroll the sprite
				  var yPos = -($window.scrollTop() / $sprite.data('speed'));
				  var coords = (yPos + $sprite.data('offsetY')) + 'px';
	
				  $sprite.css({ top: coords });
				}); // sprites
			
			  }; // in view						   
		});
							
							
							
		//initialize array for later use
		var pageArray = new Array();
		$('[data-content]').each(function(){
		 
		// Store some variables based on where we are
			var $self = $(this),
			offsetCoords = $self.offset(),
			topOffset = offsetCoords.top;
		
			// If this section is in view or been "scrolled past"
			if ( $window.scrollTop() > topOffset -150 ) {
			  var page = $self.attr('data-content');
			  pageArray.push(page);
			}; // in view		
			
			
		 
		}); // each data-type
		
		// gets last page in array and sets as current page
		var currentPage = pageArray[pageArray.length-1];
		
		//as you scroll page animates top navbar to show current page and adds class to prevent hover from removing active state
		$('[data-nav]').each(function(){
			if( $(this).attr('data-nav') == currentPage ){
				$('[data-nav]').stop().animate({backgroundPosition: '0 0'}, 300).removeClass('active');
				$(this).stop().animate({backgroundPosition: '0 -70'}, 300).addClass('active');
			};
		});
		
	}); // window scroll
};

//creates panning animation/transition for main pages
function mainNavigation() {
	var contact = $('#section5');
	var contactHeight = contact.height() +100;
	contact.css({'position':'fixed', 'top': -contactHeight});
	var contactLink = $('#pageHeader a[data-contact]');
	contactLink.addClass('closed');
	
	contactLink.click(function(event){
		event.preventDefault();
		var currentState = $(this).attr('class');
		if ( currentState == "closed"){
			contact.animate({'top': 0});
			$(this).removeClass('closed').addClass('active');
		} else {
			contact.animate({'top': -contactHeight});
			$(this).addClass('closed').removeClass('active');
		}
		
	});
	
	$('#pageHeader a[data-section]').click(function(event){
		event.preventDefault();
		
		var section = $(this).attr('data-section');
		var adjustedPosition = $(section).offset().top - 68;
		
		if(contactLink.attr('class') == "active"){
			contact.animate({'top': -contactHeight});
			contactLink.addClass('closed').removeClass('active');
		};
		
		$('html, body').stop().animate({
		   scrollTop: adjustedPosition
		}, 1500);
	});
	
	$('#contactClose').click(function(event){
		event.preventDefault();
		contact.animate({'top': -contactHeight});
		$('#pageHeader a[data-contact]').addClass('closed').animate({backgroundPosition: '0 0'}, 300).removeClass('active');
	});
	
};

function mousewheelAnimate() {
	$(window).bind('mousewheel', function(event, delta) {
		event.preventDefault();
		$viewport = $('html, body');
		
		
		if( $viewport.is(':animated') ){
			
		} else {
			$viewport.animate({
			   scrollTop: $(window).scrollTop() - (delta * 80)
			}, 100);
		};
	});
};
function sideSwitcher(){
	var tabs = $('[data-partnertab]');
	var totalTabs = tabs.length -1;
	var currentTab = 0;
	
	var viewportWidth = $('[data-content="about"]').width();
	var viewportPadding = $('.section2Content').css('padding-left');

	tabs.css('position', 'absolute');
	tabs.each(function(index){
		if (index > 0){
			$(this).css('left', viewportWidth +10);
		}
	});
	//bind to click event to next arrow
	$('#section2 a[data-productlink="next"]').click(function(event){
		event.preventDefault();
		//if there are more articles in the cueue go to next
		if(currentTab < totalTabs){
			currentTab++;
			var prevTab = currentTab -1;
			nextTab();
		//if no articles left in cue go back to beginning
		} else{
			currentTab = 0;
			var prevTab = totalTabs;
			nextTab();
		}
		
		function nextTab() {
			//animates next article up into view and previous article up out of view
			$(tabs[currentTab]).css({"left":viewportWidth}).stop().animate({left : viewportPadding});
			$(tabs[prevTab]).stop().animate({left : -viewportWidth});
		};
	});
	
	//bind to click event to prev arrow
	$('#section2 a[data-productlink="prev"]').click(function(event){
		event.preventDefault();
		//if there are more articles in the cueue go to next
		if(currentTab > 0){
			currentTab--;
			var prevTab = currentTab +1;
			backTab();
		//if no articles left in cue go back to beginning
		} else{
			currentTab = totalTabs;
			var prevTab = 0;
			backTab();
		}
		
		function backTab() {
			//animates next article up into view and previous article up out of view
			$(tabs[currentTab]).css({"left": -viewportWidth}).stop().animate({left : '0px'});
			$(tabs[prevTab]).stop().animate({left : viewportWidth});
		};
	});
	
};

//Home page switcher
function imageSwitcher(){
	//find how many article sections there are and set current article to 0 base
	var articles = $('#section1 article');
	var totalArticles = articles.length -1;
	var currentArticle = 0;
	//sets up prev article for use in later functions
	var prevArticle = totalArticles;
	//find background area and figure out its height to slide backround image in and out of view
	var background = $('#section1');
	var backgroundHeight = parseInt(background.height()) + parseInt(background.css('padding-top'));
	//figure out content viewport height for sliding content out of view
	var viewportHeight = $('#section1 .content').height() +50;
	//set auto time interval
	var timeInterval = 6000;
	
	//hide spare articles at beginning
	articles.each(function(index){
		if(index > 0){
			$(this).css('display', 'none');	
		}
	});
	
	//auto animate when in view
	//REMOVE THE HOVER
	//REMOVE THE HOVER
	//REMOVE THE HOVER
	var autoRun = setInterval( calcNext, timeInterval );
//	$('#section1 .content').hover(function() {
//		autoRun = clearInterval(autoRun);
//	}, function() {
//		autoRun = setInterval(calcNext, timeInterval);
//	});
	
	$(window).scroll(function(){	 
		// Store some variables based on where we are
		var $section = $('[data-content="home"]'),
		offsetCoords = $section.offset(),
		topOffset = offsetCoords.top;
	
		// If this section is in view or been "scrolled past"
		if ( ($window.scrollTop() + $window.height()) > (topOffset) && ((topOffset + $section.height()) > $window.scrollTop()) ) {
			if ($section.attr('data-active') == 'false'){
				autoRun = setInterval(calcNext, timeInterval);
				$section.attr('data-active', 'true');
			} else {
				return false;
			};
			
		} else {
			autoRun = clearInterval(autoRun);
			$section.attr('data-active', 'false');
		}; // in view					
	}); // window scroll
	

	
	//bind to click event to next arrow
	$('#section1 a[data-link="next"]').click(function(event){
		event.preventDefault();											  
		calcNext();
	});
	
	//binds click event to previous button 
	$('#section1 a[data-link="prev"]').click(function(event){
		event.preventDefault();
		calcPrev();
	});
	
	//calculate next article and trigger animation
	function calcNext() {
		//if there are more articles in the cueue go to next
		if(currentArticle < totalArticles){
			currentArticle++;
			prevArticle = currentArticle -1;
			swapArticle();
		//if no articles left in cue go back to beginning
		} else{
			currentArticle = 0;
			prevArticle = totalArticles;
			swapArticle();
		};
	};
	//calculate prev article and trigger animation
	function calcPrev(){
		if(currentArticle > 0){
			currentArticle--;
			prevArticle = currentArticle +1;
			swapArticle();
		} else{
			currentArticle = totalArticles;
			prevArticle = 0;
			swapArticle();
		};
	};
	
	//sets animation of articles and background for next
	function swapArticle() {
		//animates next article up into view and previous article up out of view
		$(articles[prevArticle]).fadeOut(2000);
		$(articles[currentArticle]).fadeIn(2000);
		
	};
};
//setup ajax fade in of content
function fadeInTransition(){
	
	//hides all sections besides first in the about section
	$('#about [data-tab]').each(function(index){
		if(index > 0){
			$(this).css('display','none');
		};							  
	});
	//hides all sections besides first in the products section
	$('#products [data-tab]').each(function(index){
		if(index > 0){
			$(this).css('display','none');
		};
	});
	//hides all sections besides first in the products section
	$('#serve [data-tab]').each(function(index){
		if(index > 0){
			$(this).css('display','none');
		};
	});
	
	$('[data-fade]').click(function(event){
		event.preventDefault();
		var currentSection = $(this).parents('[data-content]').attr('data-content');
		var clickedArticle = $(this).attr('data-fade');
		
		
		$('#'+ currentSection +' article').each(function(){
			var display = $(this).css('display');
			if (display != 'none'){
				$(this).fadeOut(function(){
					$('#'+ clickedArticle).fadeIn();	   
				});
			}
		});
		
	});
	
	//ICONN images transition in section 3
	$('#serve [data-iconn]').click(function(index){
		var newImage = $(this).attr('data-iconn');
		var imageSection = $('#ICONNimg');
		var newImagePosition = newImage + ' 0'
		imageSection.fadeOut(function(){
			imageSection.css('background-position', newImagePosition).fadeIn();
		});
	});
	
}

function arrowSlider(){
	$("[data-slider]").each(function(){
		var navbar = $(this); //finds navbar element
		var arrow = $('.arrow', this); //finds arrow element
		var arrowWidth = arrow.width(); //sets arrow width
		var navBarWidth = 0; //readies navbar width variable for use
		var activeLink = $('.active', this).parent(); //finds current page link(active link)
		var activeLinkPosition = activeLink.position(); //calculates active links position inside navbar
		var arrowHomePosition = Math.round(((activeLink.width() - arrowWidth) / 2) + activeLinkPosition.left); //calculates home(default) position of arrow underneath active link
		
		//finds width of all links combined
		$('li', this).each(function(){
			navBarWidth = navBarWidth + $(this).width() + parseInt($(this).css('padding-left'), 10);							  
		});
		//sets arrow to default underneath active link
		arrow.css('left', arrowHomePosition);
		
		//creates animation for arrow to follow mouse and return to home
		function arrowFollow(){	
			//calculate max left and right so arrow wont go beyond bounds of links
			var maxPosition = navbar.children('ul').position();
			var maxLeftPosition = maxPosition.left;
			var maxRightPosition = maxLeftPosition + navBarWidth - arrowWidth;
			
			//sets up arrow animation inside of navbar area
			navbar.mousemove(function(e){
				var mousePosition = e.pageX; //finds mouse position on page
				var navbarPosition = navbar.offset(); //finds navbar position on page
				var zeroedMousePosition = mousePosition - navbarPosition.left; //calculates cursor position inside navbar
				var arrowFollowPosition = Math.round(zeroedMousePosition - (arrowWidth / 2)); //calculates arrow position to be centered on cursor
				
				//animates arrow to follow mouse inside the bounds of the link area
				if (zeroedMousePosition < maxLeftPosition){
					arrow.stop().animate({left : maxLeftPosition},300);
				} else if(zeroedMousePosition > maxRightPosition){
					arrow.stop().animate({left : maxRightPosition},300);
				} else{
					arrow.stop().animate({left : arrowFollowPosition},300);
				};
			});
			
			//animates arrow back to home position when cursor leaves navbar area
			navbar.mouseleave(function(){
				arrow.stop().animate({left : arrowHomePosition},300);
			});
		};
		
		//cache all links in current nav bar
		var currentLinks = $('a', this);
		//remove active class from all links and apply to clicked link then reset home position
		$('a', this).click(function(){
			activeLink = $(this).parent();
			currentLinks.removeClass('active');
			$(this).addClass('active');
			setArrowHome();
		});
		function setArrowHome(){
			activeLinkPosition = activeLink.position(); //calculates active links position inside navbar
			arrowHomePosition = Math.round(((activeLink.width() - arrowWidth) / 2) + activeLinkPosition.left); //calculates home(default) position of arrow underneath active link
		};
		
		//initializes arrow follow functionality
		arrowFollow();
		   
	});
};

function rainbowRoad(){
	//finds image to scroll
	var rainbow = $('#rainbowPillar img');
	//sets height so image wont disappear from background as scrolls
	var rainbowHeight = rainbow.height() - $('[data-content="serve"]').height();
	$('[data-color]').click(function(){
		//finds current color position on image
		var currentColor = rainbow.css('top');
		//finds color and point to scroll to
		var newColor = $(this).attr('data-color');
		//determines if new color is above old color in image
		var comparison = parseInt(newColor) - parseInt(currentColor);
		//set transition time
		var transitionTime = 1000;
		//if new color is above old color scrolls to bottom of image then jumps to top and continues scroll
		if(comparison > 0){
			//equalize speed for continous animation
			//find distance to bottom of image from current position
			var bottomDistance = rainbowHeight + parseInt(currentColor);
			//figure out what each pixel is in percentage of distance to travel
			var speedVar = 100/(-newColor + bottomDistance);
			//find speed pre-jump to 0 and post jump to 0
			var postjumpSpeed = Math.round((-newColor * speedVar) / 100 * transitionTime);
			var prejumpSpeed = Math.round((bottomDistance * speedVar) / 100 * transitionTime);
			rainbow.animate({'top' : -rainbowHeight}, prejumpSpeed, function(){
				rainbow.css('top', '0px')
			}).animate({'top' : newColor}, postjumpSpeed);
		//in new color is below old color scrolls to color
		} else {
			rainbow.animate({'top' : newColor}, transitionTime);
		}
	});
}

function enableTwitter(){
	// set your twitter id
    var user = 'tascet';
      
    // using jquery built in get json method with twitter api, return only one result
    $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&count=1&callback=?', function(data)      {
          
        // result returned
        var tweet = data[0].text;
		var tweetID = data[0].id_str;
        // process links(www), mentions(@), and trends(#)
        tweet = tweet.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$1">$1</a>').replace(/(^|\s)@(\w+)/ig, '$1<a href="http:\/\/www.twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/ig, '$1<a href="http:\/\/search.twitter.com/search?q=%23$2">#$2</a>');
     
        // output the result and add reply, retweet and favorite buttons
        $('[data-twitter="tweet"]').prepend(tweet);
		$('[data-twitter="buttons"]').append('<a href="https://twitter.com/intent/tweet?in_reply_to='+tweetID+'" id="replyIcon"><div></div>Reply</a> <a href="https://twitter.com/intent/retweet?tweet_id='+tweetID+'" id="retweetIcon"><div></div>Retweet</a> <a href="https://twitter.com/intent/favorite?tweet_id='+tweetID+'" id="favoriteIcon"><div></div>Favorite</a>');
    });
};

function contactValidation() {
	$("#contactForm").validate({
	   rules: {
		 name: "required",
		 phone: {
		   required: true,
		   phone: true
		 },
		 email: {
		   required: true,
		   email: true
		 },
	   },
	   messages: {
		 name: "We'd like to know who's contacting us",
		 phone: {
		   required: "We need your phone number for future contact",
		   phone: "Please enter a valid phone number in the form 555-555-5555"
		 },
		 email: {
		   required: "We need your email address for future contact",
		   email: "Your email address must be in the format of name@domain.com"
		 },
		 message: "Let us know why you are contacting us"
	   },
	   submitHandler: function(form) {
		   	$('#spinner').show();
		   
		 	var name = $("input#name").val();  
			var email = $("input#email").val();  
			var phone = $("input#phone").val(); 
			var message = $("textarea#message").val(); 
			var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message; 
			
			$.ajax({  
			  type: "POST",  
			  url: "/email.php",  
			  data: dataString,  
			  success: function() {  
				$('#spinner').html("<h3>Contact Form Submitted!</h3>").append("<p>We will be in touch soon.</p>").delay(3000).fadeOut(1500);  		
			  }, 
			  error: function() {  
				$('#spinner').html("<h3>We're Sorry!</h3>").append("<p>There appears to have been an error.<br>Please contact us via our other contact info.</p>");  		
			  } 
			});  
			return false;  
	   }
	})
};
	//Jump to section if hashtag exists
function jumptohash() {
	var hash = window.location.hash;
	if(hash) {
		var linkArray = new Array();
		$('[data-fade]').each(function(){
			linkArray.push($(this).attr('href'));
		});
		linkArray.push('#section5');
		
		if($.inArray(hash, linkArray) > -1){
			$('a[href*="'+ hash +'"]').click();
			
			if(hash != '#section5'){
				var jumppoint = $('a[href*="'+ hash +'"]').data('jump');
				window.location = jumppoint;
			};
		};
	};
};

//on document ready activate functions
$(function(){ 
	fadeInTransition();
	mainNavHover();	
	mainNavigation();
	imageSwitcher();
	sideSwitcher();
	arrowSlider();
	rainbowRoad();
	mainNavScroll();
	mousewheelAnimate();
	jumptohash();
	contactValidation();
	enableTwitter();
});

//fix for animated background scroll in IE
(function($) {
  jQuery.fn.backgroundPosition = function() {
    var p = $(this).css('background-position');
    if(typeof(p) === 'undefined') return $(this).css('background-position-x') + ' ' + $(this).css('background-position-y');
    else return p;
  };
})(jQuery);
