$(function(){

	// IMAGES LOADED

	$('#Main').not('.sn_contact').imagesLoaded( function( $images ) {
	  $images.animate({opacity:1});
	});
		
});

$(window).load(function(){

	// HOMEPAGE: FADE IN SLIDESHOW CAPTION
	$('#SlideCaptionContainer').fadeIn('slow');

	
	// PORTFOLIO CAT: CALCULATE PORTFOLIO GRID HEIGHT
	var portfolioHeight = $('.sn_pcat #Grid').height();
	$('.sn_pcat #Grid').css('height', portfolioHeight);
	$('.sn_pcat #Grid').css('display','none');	
	
	$('a#GridExpand').animate({opacity:1});

});

$(document).ready(function() {

	// ABOUT: TRIPTYCH
	if($('.sn_text').length > 0) {
		$('#Triptych.animate').triptych();
	}

	// CONTACT: FORM VALIDATION
	$("#freeform").validate();


	// PROFILE: MORPHEUS
	if($('.sn_profile').length > 0) {
		$('#BodyTextImage aside ul li.playful').morpheus({speed:1000, delay:3000});
	}
	
	
	// PORTFOLIO: TRIPTYCH MIDDLE CELL
	if($('.sn_portfolio').length > 0) {
		$(this).find('.tych:nth-child(2n)').addClass('middle');
	}
	if($('.sn_pcat').length > 0) {
		$(this).find('.tych:nth-child(2n)').addClass('middle');
	}
	
	// GLOBAL: REMOVE BOTTOM MARGIN FOR LAST PARAGRAPH
	$('article p:last').css('margin-bottom','0px');
	
	
	// NEWS: REMOVE BOTTOM BORDER FOR LAST NEWS ITEM
	$('#BodyTextSidebar article table tr:last td').css('border-bottom','none');


	// TEAM/PORTFOLIO: SELECT BOX BEHAVIOR
	$('ul.select li').not(':first').hide();
		
	$('ul.select').mouseenter(function(){
		$(this).children('li.arrow').removeClass('arrow');
		$(this).children('li').show();
	}).mouseleave(function(){		
		if($(this).children('li').hasClass('active')) {
			$(this).children('li.active').addClass('arrow');
			$(this).children('li').not('.active').hide();
		} else {
			$(this).children('li').not(':first').hide();
		}	
	});
	
	
	// PORTFOLIO: MODAL SCROLL
/*
	$('.modal-trigger').click(function(){
		var modalPos = $(window).scrollTop() + 170;
		$('.jqmWindow').css('top', modalPos + 'px');
	});
*/
	
	
	// PORTFOLIO CAT: GRID EXPAND ANIMATION
	$('a#GridExpand').click(function(e){
		e.preventDefault();
		if($(this).hasClass('open')) {
			$(this).css('width','auto').css('background-position','top right').removeClass('open');
			$(this).removeClass('open');
			$.scrollTo({top:'0px', left:'0px'}, 500 );
			$('.sn_pcat #Grid > .grid_item').fadeOut('fast');
		}
		else {
			$(this).css('background-position','925px 0px').css('width','920px').addClass('open');
			$('.sn_pcat #Grid').show();
			$(this).addClass('open');
			var portfolioTop = $('a#GridExpand').offset().top - 110;
			$.scrollTo({top:portfolioTop+'px', left:'0px'}, 500, function(){
				var d= 0;
				$('.sn_pcat #Grid > .grid_item').each(function() {
					$(this).delay(d).css('visibility','visible').hide().fadeIn(800);
					d += 200;
				});
			});
		}
	});
		

	// GRID OVERLAY ANIMATIONS
	
	//////// TEAM: OVERLAY ANIMATION
	$('.sn_tcat #Grid .grid_item').mouseenter(function(){
		$('.sn_tcat #Grid .grid_item').not($(this)).children('.inactive-overlay').stop().fadeTo('fast',0.5);
	}).mouseleave(function(){
		$('.sn_tcat #Grid .grid_item').children('.inactive-overlay').stop().fadeOut();
	});
	
	//////// PORTFOLIO: SECTOR OVERLAY ANIMATION
	$('.grid_section').mouseenter(function(){
		$('.grid_section').not($(this)).children('.inactive-overlay').stop().fadeTo('fast',0.5);
	}).mouseleave(function(){
		$('.grid_section').children('.inactive-overlay').stop().fadeOut();
	});


	// PORTFOLIO/PORTFOLIO CAT: QTIPS
	
	//////// ADD A UNIQUE CLASS TO EACH GRID ITEM
	var itemNo = 0;
	$('.cooltip #Grid .grid_item').children('.logo-overlay').each(function(itemNo) {
		$(this).addClass('item'+(itemNo));
		itemNo++;
    });
	
	//////// QTIP SETUP
	$('.cooltip #Grid .grid_item').qtip({
		prerender: true,
		content: {
		  text: function(api) {
		     return $(this).children('.grid_qtip_container').html();
			}
		},
		hide: {
			fixed:true,
			delay:200
		},
		position: {
			my: 'bottom center',
			at: 'top center',
			viewport: $(window),
			adjust: {
				y: -10,
				method: 'none shift'
			}
		},
		events: {
			'show': function(event, api) {
				var dat = $(this);
            	viewportAdjust(api, dat);
			},
			'hide': function(event, api) {
				var dat = $(this);
				hideLogo(api, dat);
			}
        },
		style: {
            tip: false
        }
	});
	
	//////// QTIP SHOW FUNCTION: ADJUST TO VIEWPORT
	function viewportAdjust(api, dat) {
		
		var datID = dat.attr('id');
		var datNo = datID.match(/\d+$/);
		
		// fade in logo
		var activeItem = $('.item' + datNo);
		var activeItemParent = activeItem.closest('.grid_item');
		activeItem.stop().fadeTo('fast',0.9);
		//$('.cooltip #Grid .grid_item').not(activeItemParent).children('.inactive-overlay').stop().fadeTo('fast',0.5);
		
		// using modulus to adjust for the first/last items in each row
		if(datNo % 4 == 0 || datNo == 0) {
			$('.tip').css('left','100px');
			api.set('position.adjust.x', 105);
		}  else if (datNo % 4 == 3) {
			$('.tip').css('left','300px');
			api.set('position.adjust.x', -105);
		} else {
			$('.tip').css('left','200px');
			api.set('position.adjust.x', 0);
		}
		
	}
	
	//////// QTIP HIDE FUNCTION: FADE OUT LOGO 
	//////// (use this function so logo doesn't fade out while hovering over QTIP)
	function hideLogo(api, dat) {
		var datID = dat.attr('id');
		var datNo = datID.match(/\d+$/);
		$('.item' + datNo).fadeOut();
	}
	
	//////// FADE OUT INACTIVE-OVERLAY 
	//////// (inactive overlay still fades out while hovering over QTIP... c'est la vie)
	//$('.cooltip #Grid .grid_item').mouseleave(function(){	
	//	$('.cooltip #Grid .grid_item').children('.inactive-overlay').stop().fadeOut();
	//});
	

	
	// TEAM: MASONRY
	
	var
		speed = 600,
		$wall = $('.sn_tcat #Grid');
	;

	$wall.masonry({
		singleMode: true, 
		itemSelector: '.grid_item:not(.invis)',
		animate: true,
			animationOptions: {
				duration: speed,
				queue: false
			}
		}
	);
	
		
	$('ul#filter-menu.masonry li a').click(function(e){
	
		e.preventDefault();
		
		$('.grid_item').children('.inactive_overlay').hide(); // rollover overlay sticks sometimes just hide it.
				
	  	var topicClass = '.' + $(this).attr('class');
		
		if(topicClass=='.all') {
						
		// show all hidden boxes
			$('ul#filter-menu.masonry li a').parent().removeClass('active');
			$wall.children('.invis').toggleClass('invis').stop().fadeIn(speed);
			$(this).parent().addClass('active');

		
		} else {  
			
			// hide visible boxes 
			$('ul#filter-menu.masonry li a').parent().removeClass('active');
			$wall.children().not(topicClass).not('.invis').toggleClass('invis').stop().fadeOut();
			
			// show hidden boxes
			$wall.children(topicClass+'.invis').toggleClass('invis').stop().fadeIn(speed);
			$(this).parent().addClass('active');

		}
		
		$wall.masonry();
		return false;
	
	});



	// PORTFOLIO CAT/PORTFOLIO: LOGO VERTICAL CENTERING 	
	//	$('.cooltip #Grid .grid_item .logo-overlay img').each(function(){
	//		
	//		var logoHeight = $(this).height();
	//		var logoHeightHalf = logoHeight/2;
	//		var logoMargin = 75 - logoHeightHalf;
	//		
	//		$(this).css('margin-top',logoMargin);
	//	
	//	});
	
});



// PLUGIN: MORPHEUS

(function($) {
	$.fn.morpheus = function (options) {
		var settings = {
			speed: 700,
			delay: 300
		};
		var options = $.extend(settings,options);
		
		$(this).delay(options.delay).fadeIn(options.speed, function() {
			$(this).delay(options.delay).fadeOut(options.speed, function(){
				$(this).morpheus({speed:options.speed, delay:options.delay})
			});
			return $(this);
		});		
		
	};
})(jQuery);



// PLUGIN: TRIPTYCH
(function($) {
	$.fn.triptych = function (options) {
		
		var fnThis = $(this);
		
		var settings = {
			groups: 1, // number of sets
			cells:3, // number of images per set
			speed: 800, // speed of cell fade
			celldelay: 800, // time between cell fades
			groupdelay: 2000, // time between start of new group 
			ran: false
		};
		var options = $.extend(settings,options);

		var tychslice = fnThis.children('.tych');
		for(var i = 0; i < tychslice.length; i+=options.cells) {
			tychslice.slice(i, i+options.cells).wrapAll('<div class="tych_group"></div>');
		}
		
		options.groups = fnThis.children('.tych_group').length;

		fnThis.children('.tych_group').each(function(no){
			var zIndexxx = 1000-(no*100);
			$(this).css('z-index', zIndexxx).
			no++;
		});
		
		fnThis.children('.tych_group:last').children('.tych').addClass('last');
		fnThis.find('.tych:nth-child(2n)').addClass('middle');
		
		var tychgroups = fnThis.children('.tych_group');
		
		var cycleTime = ((options.celldelay*options.cells) + options.groupdelay);
		var totalTime = (cycleTime*options.groups);

		ranOnce = options.ran;
		
		var timer;
		
		function runGroups(){
			
			if(ranOnce == true) {
				
				var tychgroups = fnThis.children('.tych_group');
				var delay = options.celldelay;
				var cellCounter = options.cells;
				
				tychgroups.children('.tych').removeClass('loaded');
				
				tychgroups.first().children('.tych').each(function() {
					$(this).delay(delay).animate({opacity:1}, options.speed, function(){
						cellCounter--
						if(cellCounter == 0) {
							tychgroups.not('.tych_group:first').children('.tych').css('opacity','1');
							tych();																	
						}
					});
					delay+=options.celldelay;
				});
				
				timer = setTimeout(function(){
					fnThis.triptych({ran:true});
				}, (totalTime));
				
			} else {

			
				$('.tych').css('opacity','1');
				tych();
				timer = setTimeout(function(){
					fnThis.triptych({ran:true});
				}, (cycleTime*options.groups));
				
			}
			
			function tych(){

				n = cycleTime;
				
				var tychgroups = fnThis.children('.tych_group');
				
				tychgroups.each(function(n){
					
					var xiaohaize = $(this).children('.tych').not('.last');
					
					setTimeout(function(){
							
			            rando = setInterval(function(){
			                 $notLoaded = xiaohaize.not(".loaded");
			                 $notLoaded.eq(Math.floor(Math.random()*$notLoaded.length)).animate({opacity:0}, options.speed).addClass("loaded");
			                 if ($notLoaded.length == 0) {
			                      clearInterval(rando);
			                 }
			           	}, options.celldelay);
		
					}, ((n*cycleTime)+options.groupdelay));
					
				});
			
			}
		
		}
		
		runGroups();
							
		return $(this);
		
	};

})(jQuery);
