$(function() {
	// Fancybox
	$('.fancybox').fancybox({
		padding : 0,
		width: 713,
		height: 400,
		helpers : {
			overlay : {
				opacity : 0.7
			}
		},
		afterShow : homeOnly
	});
	
	function homeOnly() {
		if ($('body').hasClass('home')) {
			$('.fancybox-close').after('<ul class="fancybox_nav"><li><a href="#">Juxt Reel</a></li><li><a href="#">Video Reel</a></li></ul>');
			$('.fancybox_nav a').each(function(i, elem){
				$(elem).attr('href',$('.item.reel a').get(i));
			})
		}
		
		$('ul.fancybox_nav a').each(function(){
			if ($(this).attr('href') == $('.fancybox-iframe').attr('src')) {
				$(this).parent().addClass('current');
			}
		})
		
		$('ul.fancybox_nav a').bind('click',function(e){
			e.preventDefault();
			
			if ($('.fancybox-iframe').attr('src') != $(this).attr('href')) {
				$('.fancybox-iframe').attr('src', $(this).attr('href'));
				$(this).parent().siblings().removeClass('current');
				$(this).parent().addClass('current');
			}
		})
	}
	
	if (supportsTouch) {
		$('body.home').addClass('touch');
	}
	else {
		$('.item').jknav();
		$.jknav.init();
		
		// Home navigation
		$('#home_navigation a').bind('click', function(e){
			e.preventDefault();
		})
		
		$('#home_navigation a').each(function(index) {
			$(this).bind('mouseover', function(e){
				e.preventDefault();
				$.scrollTo.window().stop();
				$.scrollTo('.item_'+parseInt(index+1), 500);
			})
		});
		
		// Fade in/out sections
		$(window).bind('scroll',function(e){
			$('.item').each(function(index, domEle){
				var windowY = $(window).scrollTop();
				var eleY = $(domEle).position().top;
				var giveTop = 100;
				var giveBottom = 100;
				if ( eleY+giveBottom >= windowY && windowY >= eleY-giveTop ) {
					$(domEle).find('*').fadeTo(0, 1);
				}
				else {
					var distance;
					if (windowY < eleY) {
						distance = Math.abs(windowY - (eleY - giveTop));
					}
					else {
						distance = Math.abs(windowY - (eleY + giveBottom));
					}
					$(domEle).find('*').fadeTo(0, 100/distance);
				}
			})
			if ($('footer').hasClass('short')){
				var joinPos = $('#content .join').position().top - $(window).scrollTop();
				var footerPos = $('footer').position().top - $(window).scrollTop();
				
				if (footerPos < joinPos+470) {
					
					$('#home_navigation').addClass('attach').removeClass('short');
				}
				else {
					$('#home_navigation').addClass('short').removeClass('attach');
				}
			}
		})
		
		// Footer
		var windowHeight = $(window).height();
		if (windowHeight < 910) {
			$('body.home footer').addClass('short');
			$('body.home #home_navigation').addClass('short');
		}

		$(window).resize(function(){
			windowHeight = $(window).height();
			if (windowHeight < 950) {
				$('body.home footer').addClass('short');
				$('body.home #home_navigation').addClass('short');
			}
			else {
				$('body.home footer').removeClass('short');
				$('body.home #home_navigation').removeClass('short');
			}
		})
	}
});
