(function( $ ){	

	//global vars go here.
	var firstRun = true;
	var updateLocationSwitch = false;
	var scrollOffset = 67;
	
	// Global activation
	$(document).ready(function() {

		// Mark browser
		browserName = BrowserDetect.browser;		
		$('body').addClass(browserName.toLowerCase()).addClass('ver' + BrowserDetect.version);
		
		// Adjust footer if it's a short page
		if ($(window).height() > 650 && $('body').height() < $(window).height()) {
			$('footer').addClass('fixed-footer');
		}
			
		//Safe Mailto 
		if( $('a.email').length > 0 ) {
			$('a.email').mailto();
		}	
		
		// Only activate the one page features for the homepage 
		if ($('body').hasClass('homepage')) {
		
			// Set up scrolling
			$("html, body").bookmarkScroll();
			$('header a').scrollify().each(function() {
				navAnchors.push('#' + $(this).attr('rel') + '-anchor');
			});
			$(window).scroll(function(){
				clearTimeout(scrollFinish);
			    scrollFinish = setTimeout(updateLocation, 400);
			});	
			
			//Scroll back down to the contact section to see the validation/success message
			if( $('#contact_thanks').length > 0 || $('div.validation_message').length > 0 ) {			
				$('#contact-nav-link').trigger('click');
			}				
		
			// Set up interactivity
			$('.hero', '#welcome').welcomeClick();	
			$('.thumbs a', '#welcome').showTitle();	
			$('ul.timeline li', '#process').setupProcessNav();
			$('.learn-more a', '#process').processLearnMore();
			$('#projects').setupPortfolioNav();
			$('nav', '#team').expandTeam();
			$('a.learn-more', '#team').teamLearnMore();
			
			// Resize Team members and set up window resize listener
			$('#team nav').addClass('jquery');
			$.fn.resizeTeam();
			$(window).resize(function() {
				$.fn.resizeTeam();
			});
			
			// Portfolio Gateway 
			$('#projects .more-portfolios').click(function() {
				$('#portfolio-gateway').fadeIn();	
				if( typeof(_gaq) !== undefined ) {
					_gaq.push(['_trackPageview','/portfoliosignupform']);
				}				
				return false;			
			})
			$('#portfolio-gateway .cancel').click(function() {
				$('#portfolio-gateway').fadeOut();
				return false;				
			});			
			
			$('#portfolio-signup-form').live('submit', function(){		
			     $('#portfolio-error').html('');			
			     $.ajax({
                    type: 'POST',
                    url: 'portfolio-ajax.php',
                    data: $(this).serialize(),	
                    dataType: 'json',					
                    success: function (data){                    
                        if( data.result == "Success" ) {
            				if( typeof(_gaq) !== undefined ) {
            					_gaq.push(['_trackPageview','/portfoliosignupcomplete']);
            				}                                                    
                            setTimeout('document.location = "' + data.body + '"', 100);
                        }
                        else
                        if( data.result == "Error" ) {
                            $('#portfolio-error').html(data.body);
                        }                        
                    }
			     });
			     return false;
			});
			
			//initialize history functions
			$.history.init(function(hash){
				if(hash == "") {
					// initialized.
				} else if(hash[0] == '!') {
					//callback
					if(updateLocationSwitch) { // dont update the page if updateLocation caused this
						updateLocationSwitch = false;
						return;
					}
					hashSwitch = hash.substr(1);
					
					// Check for a second parameter.
					splitHashSwitch = hashSwitch.split('/', 2);
					if(splitHashSwitch.length == 2) {
						hashSwitch = splitHashSwitch[0];
						if(hashSwitch == 'portfolio' && firstRun) {
							firstRun = false;
							$('nav a[rel=' + splitHashSwitch[1] + ']', '#portfolio').trigger('click');
						}
						if(hashSwitch == 'team' && firstRun) {
							firstRun = false;
							$('nav a[rel=' + splitHashSwitch[1] + ']', '#team').trigger('click');
						}
						if(hashSwitch == 'welcome' && firstRun) {
							firstRun = false;
							$('nav a[rel=' + splitHashSwitch[1] + ']', '#welcome').trigger('click');
						}
						return false;
					} else {
					
						switch (hashSwitch) {
							case 'portfolio' : // means "back" pushed from a portfolio item
								$('a.back-button', '#portfolio').trigger('click');
								break;
							case 'welcome' : // means "back" pushed from a video
								$('a.back-button', '#welcome').trigger('click');
								break;
							case 'team' : // means "back" pushed from a team profile
								$('a.back-button', '#team').trigger('click');
								break;
						}
					}
					$("html, body").bookmarkScroll();
				}
			},
			{ unescape: ",/" });
			firstRun = false;
		}
		else if ($('body').hasClass('blog')) {
			// Activate global nav link
			$('#blog-nav-link').addClass('active').click(function() {
				return false;
			});
			
			// Make the whole post clickable
			$('.post', '.content').each(function() {
				$(this).click(function() {
					window.location = $('h2 a', $(this)).attr('href');
				});
			});
		}
	});
	

	// Welcome
	Cufon.replace('#welcome .knockout-shadow', { 
		fontFamily: 'Knockout',
		fontSize: '220px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		textShadow: '2px 2px 0px #fff, 6px 6px 0px #e3e3e3',
		color: '-linear-gradient(#433b36, #665f5b)'
	});
	
	Cufon.replace('#welcome .cabernet', { 
		fontFamily: 'CabernetJF',
		fontSize: '40px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		color: '-linear-gradient(#86817d, #999490)'
	});
	
	// 404
	Cufon.replace('#error-404 .knockout-shadow', { 
		fontFamily: 'Knockout',
		fontSize: '180px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		textShadow: '2px 2px 0px #fff, 6px 6px 0px #e3e3e3',
		color: '-linear-gradient(#433b36, #665f5b)'
	});
	
	Cufon.replace('#error-404 .cabernet', { 
		fontFamily: 'CabernetJF',
		fontSize: '30px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		color: '-linear-gradient(#86817d, #999490)'
	});
	
	
	// Footer
	Cufon.replace('footer h2', { 
		fontFamily: 'Knockout',
		fontSize: '22px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		color: '-linear-gradient(#423a35, #594c44)'
	});
	
	// Blog
	Cufon.replace('h1.blog-title', { 
		fontFamily: 'CabernetJF',
		fontSize: '90px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		color: '-linear-gradient(#86817d, #999490)'
	});
	
	Cufon.replace('h2.post-title a', { 
		fontFamily: 'Knockout',
		fontSize: '40px',
		fontStyle: 'normal',
		lineHeight: '1.2em',
		color: '#433b36'
	});
	
	// General
	Cufon.replace('.knockout', { 
		fontFamily: 'Knockout',
		fontSize: '75px'
	});
		
///////////////////////////////////////
// Data / Templates
///////////////////////////////////////

videoDetailTemplate = '<div id="article-video"></div>';

videoTitleTemplate = '<span class="title"></span>';

tooltipTemplate = '<div class="tooltip"><div></div></div>';

processOverviewTemplate = '<div id="article-process">' +
	'<div class="overview"><div class="clear"></div></div>' +
	'</div>';

projectDetailTemplate = '<div id="article-portfolio">' +
	'<div class="details">' +
	'<h3>Project Overview</h3>' +
	'<div class="column double-wide description"></div>' +
	'<div class="column testimonial"><img /><blockquote></blockquote><small></small><a href="" class="url" title="" target="_blank">Visit the Live Site</a></div>' +
	'</div>' +
	'<div class="imagery"><ul></ul></div>' +
	'</div>';

projectListTemplate = '<div id="article-portfolio">' +
	'<div class="list"></div>' +
	'</div>';
	
teamDetailTemplate = '<div id="article-team">' +
	'<div class="details"></div>' +
	'</div>';
	
teamOverviewTemplate = '<div id="article-team">' +
	'<div class="overview"><div class="clear"></div></div>' +
	'</div>';

navAnchors = [];

videoData = {};

processData = {};

projectData = {};

teamData = {};


var initialTeamCaption;
var initialPortfolioCaption;
var autoSlide;
var scrollFinish;


///////////////////////////////////////
// Global Nav
///////////////////////////////////////

// Scrollify global nav
// ONLY WORKS ON <A> WRAPPED IN A <NAV>
$.fn.scrollify = function() {
	return this.click(function() {
		currentLink = $(this);
		anchor = '#' + currentLink.attr('rel') + '-anchor';
		if (!currentLink.hasClass('active')) {
			destination = ($(anchor).offset().top - scrollOffset);
			$("html, body").stop(true, true).animate({ scrollTop: destination }, 1000, 'easeInOutCubic', function() {
				$.history.load( '!' + currentLink.attr('rel') );
			});
			
			$('a', currentLink.parents('nav')).deactivate();
			currentLink.activate();
		}
		
		return false;
	});
};

$.fn.bookmarkScroll = function() {
	page = this;
	hash = window.location.hash;
	if (hash != '') {
		cleanedHash = '';
		switch (hash) {
			case '#welcome-anchor' :
				cleanHash();
				break;
			case '#process-anchor' :
				cleanHash();
				break;
			case '#portfolio-anchor' :
				cleanHash();
				break;
			case '#team-anchor' :
				cleanHash();
				break;
			case '#contact-anchor' :
				cleanHash();
				break;
			case '' :
				break;
			default : 
				cleanHash();
		}
		if($('#' + cleanedHash + '-anchor').length) {
			destination = $('#' + cleanedHash + '-anchor').offset().top - scrollOffset;
			page.stop(true,true).animate({ scrollTop: destination }, 1600, 'easeInOutCubic');
			$('a[rel=' + cleanedHash + ']', 'header').activate();
		}
	}
}

// The non-javascript anchor names need to be cleaned in the rare case they appear
function cleanHash() {
	sliceHash = hash.substr(1);
	if(sliceHash[0] == '!') {
		sliceHash = sliceHash.substr(1);
	}
	splitHash = sliceHash.split(/[\/-]+/); // split for slashes or dashes
	cleanedHash = splitHash[0];
	return cleanedHash;
}

function updateLocation() {
	// Get the Y values of the current view
	pageTop = $(window).scrollTop();
    pageBottom = pageTop + $(window).height();
	
	clearTimeout(scrollFinish);
	
	for (i = 0; i < navAnchors.length; i++) {
		if ($(navAnchors[i]).offset()) {
			if (navAnchors[i] == "#welcome-anchor") {
				sectionTop = ($(navAnchors[i]).offset().top + 400);			
			}
			else {
				sectionTop = ($(navAnchors[i]).offset().top + (200));
			}
			sectionBottom = sectionTop + $(navAnchors[i]).height();
			//alert(navAnchors[i] + '- page: ' + pageBottom + ' / ' + pageTop + ' section: ' +  sectionBottom + ' / ' + sectionTop);
			if (sectionBottom >= pageTop && sectionTop <= pageBottom) {
				$('a', 'header').deactivate();
				// Activate current section
				slicedAnchor = navAnchors[i].slice(1);	
				stripped = slicedAnchor.split('-');
				$('a[rel="' + stripped[0] + '"]', 'header').activate();
				
				//Get current URL and make sure that the redirect should happen.
				cleanHash();
				
				if(cleanedHash != stripped[0]) {
					updateLocationSwitch = true;
					$.history.load( '!' + stripped[0] );
				}
				break;
			}		
		}
	}
}

///////////////////////////////////////
// Welcome 
///////////////////////////////////////
$.fn.welcomeClick = function() {	
	videoOn = true;
	$('img', this).wrap('<a title="Watch Now" />');
	$('a', this).append('<span class="play-button">&nbsp;</span>').attr('title', '').attr('rel', $('ul.thumbs a:eq(0)', '#welcome').attr('rel'));
	
	$('nav a:not(".mitx-link")', '#welcome').click(function() {
		newVideo = $(this);
		videoSlug = newVideo.attr('rel');
		
		displayVideo(videoSlug);
		return false;
	});	
}

function displayVideo(videoSlugSet) {
	if (typeof videoSlugSet == "undefined") {
		return false;
	}
	$.history.load( '!welcome'); //make sure back works
	$.history.load( '!welcome/'+videoSlugSet);
		
	$('nav', '#welcome').fadeOut(300, function() {
		newArticle = $(videoDetailTemplate).clone();
		newArticle.addClass(videoSlugSet);
		$('#welcome').append(newArticle);
		currentVideo = $('#article-video', '#welcome');
		$.ajax({
	  		url: '/videos/' + videoSlugSet + '/',
	  		dataType: 'text',
	 		success: function(text) {	 			 			
	  			ajaxData = $(text);	  			
	  			
	  			videoData[videoSlugSet] = {
	  				'title' : ajaxData.find('#video-div h1').text(),
	  				'embed' : ajaxData.find('#video-div div.video').html()
	  			};
				// Put the data into the new detail
				currentVideo.html(videoData[videoSlugSet]['embed']);
				
				// We've got all the data, so let's use it
				$('.nav-panel h3', '#welcome').text('Now Playing').fadeIn(300);
				$('.nav-panel h4', '#welcome').text(videoData[videoSlugSet]['title']).fadeIn(300);
				$('.nav-panel a.back-button', '#welcome').fadeIn(300);
				
				currentVideo.fadeIn(300).backToWelcomeStart();	
	  		}
		});
	});
}

// Welcomne back button
$.fn.backToWelcomeStart = function() {
	backButton = $('a.back-button', '#welcome');
	goodbyeDetail = this;
	welcomeNav = $('nav', '#welcome');
	backButton.click(function() {
		goodbyeDetail
			.fadeOut(300, function() {
				goodbyeDetail.remove();
				welcomeNav.fadeIn(300);
				$('.nav-panel h3', '#welcome').text('').fadeOut(200);
				$('.nav-panel h4', '#welcome').text('').fadeOut(200);
				$('.nav-panel .back-button', '#welcome').fadeOut(200);
			});
		$.history.load( '!welcome');
			
		return false;
	});
}

// Thumbnail tooltips
$.fn.showTitle = function() {
	var backupTitle;
	
	$('img', this).attr('title', '');
	
	return this.hover(function() {
		currentThumb = $(this);
		backupTitle = currentThumb.attr('title');
		currentThumb.attr('title', '');
		titleTip = $(videoTitleTemplate).clone();
		currentThumb.append(titleTip);
		$('.title', currentThumb).text(backupTitle).fadeIn(200);
	},
	function() {
		currentThumb = $(this);
		$('.title', currentThumb).fadeOut().remove();
		currentThumb.attr('title', backupTitle)
	});
}

///////////////////////////////////////
// Process
///////////////////////////////////////

$.fn.setupProcessNav = function() {
	
	// First time
	newTooltip = $(tooltipTemplate).clone();
	$('div', newTooltip).append($('ul.timeline li.concept', '#process').html());
	$('ul.timeline li.concept', '#process').append(newTooltip).activate();
	$('.tooltip', $('ul.timeline li.concept', '#process')).fadeIn();

	// Setup clicks
	this.click(function() {
		if (!$(this).hasClass('active')) {
			if ($('ul.timeline li.active', '#process')) {
				$('ul.timeline li.active', '#process').each(function() {
					$('.tooltip', $(this)).remove();
					$(this).deactivate();
				});
			}
			
			phaseDetails = $(this).html();
			newTooltip = $(tooltipTemplate).clone();
			$('div', newTooltip).append(phaseDetails);
			
			$(this).append(newTooltip).activate();
			$('.tooltip', $(this)).fadeIn();
		}
	});
}

// Set up Process Learn More

$.fn.processLearnMore = function() {
	$(this).click(function() {
		$(this).setupProcessDetail();

		return false;
	});
}

// Animate the nav and setup the new process detail
$.fn.setupProcessDetail = function() {
	processNav = $('nav', '#process');
	newContent = $(this).attr('rel');
	
	if (!processNav.hasClass('hidden')) {
		processNav
		.css('position', 'absolute')
		.css('top', '20px')
		.css('right', '0')
		.animate({right : processNav.css('width')}, 300, function() {
			processNav.hideMe();		
		});
	}

	newArticle = $(processOverviewTemplate).clone();
	newArticle.addClass(newContent);
	$('#process').append(newArticle);
	$('#article-process', '#process').populateProcessOverview();	

}


// Add content to the new process overview via AJAX
$.fn.populateProcessOverview = function() {
	currentDetail = $(this);
	processSlug = currentDetail.attr('class');
	// Gather the data and push it to our global JSON object
	$.ajax({
  		url: processSlug + '/',
  		dataType: 'text',
 		success: function(text) {
  			ajaxData = $(text);  			  			
  			processData[processSlug] = {
  				'one' : ajaxData.find('.column-one').html(),
  				'two' : ajaxData.find('.column-two').html()
  			}

			// Put the data into the new detail
			currentDetail
				.css('height', '500px')
				.css('width', '100%')
				.fadeIn(300);  
			$('.overview', currentDetail)
				.prepend('<div class="column">' + processData[processSlug]['two'] + '</div>')
				.prepend('<div class="column">' + processData[processSlug]['one'] + '</div>')
				.delay(300)
				.fadeIn(200);

			$('.nav-panel', '#process').delay(200).fadeIn(200);
			$('.nav-panel h3', '#process').delay(200).text('Process Overview').fadeIn(200);
						
			currentDetail.backToProcessStart();
  		}
	});
}


// Process back button
$.fn.backToProcessStart = function() {
	backButton = $('a.back-button', '#process');
	goodbyeDetail = this;
	processNav = $('nav', '#process');

	backButton.click(function() {
		goodbyeDetail
			.css('width', goodbyeDetail.width())
			.css('position', 'absolute')
			.css('right', '0')
			.animate({right : '-' + goodbyeDetail.width()}, 300, 'swing', function() {
				goodbyeDetail.remove();
				processNav.showMe().delay(100).animate({right : 0}, 300, 'swing', function() {
					$(this).css('top', '0').css('position', 'relative');
				});
				$('.nav-panel', '#process').fadeOut(200);
			});
			
		return false;
	})
}



///////////////////////////////////////
// Portfolio 
///////////////////////////////////////

// Create portfolio nav
$.fn.setupPortfolioNav = function() {
	navContainer = $(this);
	var delay;
	
	$('li a[rel!="more-portfolios"]', navContainer).attr('title', '')
		.live('mouseenter', function() {
			$('img', $(this)).attr('title', '');
			if ($('a[rel="portfolio"]', 'header').hasClass('active')) {
				rollover = $('.info', $(this));
				delay = setTimeout(function() {
					clearTimeout(delay);
					rollover.animate({bottom : '0px'}, 200);
				}, 250);
			}
		})
		.live('mouseleave', function() {
			clearTimeout(delay);
			$('.info', $(this)).animate({bottom : '-34px'}, 200);
		})
		.live('click', function() {
			$(this).setupPortfolioDetail();
			return false;	
		});	

};

// Animate the nav and setup the new portfolio item
$.fn.setupPortfolioDetail = function() {
	newProject = $(this).attr('rel');
	portfolioNav = $('nav', '#portfolio');
	if (!portfolioNav.hasClass('hidden')) {
		portfolioNav
		.css('width', portfolioNav.width())
		.css('position', 'absolute')
		.css('top', '0')
		.css('right', '0')
		.animate({right : portfolioNav.css('width')}, 300, function() {
			portfolioNav.hideMe();		
		});
	}
	if (newProject != 'select-clients-list') {
		newArticle = $(projectDetailTemplate).clone();
		newArticle.addClass(newProject);
	}
	else {
		newArticle = $(projectListTemplate).clone();
		newArticle.addClass(newProject);
	}
	$('#portfolio').append(newArticle);
	//$('article.' + newProject, '#portfolio')
	$('#article-portfolio', '#portfolio')	
		.css('width', portfolioNav.width())
		.css('top', '10px')
		.populatePortfolioDetail();
}

// Add content to the new project detail via AJAX
$.fn.populatePortfolioDetail = function() {
	$.history.load( '!portfolio'); //make sure back works
	currentDetail = $(this);
	projectSlug = currentDetail.attr('class');
	$.history.load( '!portfolio' ); //make sure back works
	$.history.load( '!portfolio/' + projectSlug )
	// Gather the data and push it to our global JSON object
	if (projectSlug == 'select-clients-list') {
		dataLocation = projectSlug + '/';	
	}
	else {
		dataLocation = 'portfolio/' + projectSlug + '/';	
	}
	$.ajax({
  		url: dataLocation,
  		dataType: 'text',
 		success: function(text) {
  			ajaxData = $(text);
  			if (projectSlug == 'select-clients-list') {
	  			projectData[projectSlug] = {
	  				'title' : ajaxData.find('.select-clients-list h1').text(),
	  				'description' : ajaxData.find('.select-clients-list .description').html(),
	  			}
			}
			else {
				projectData[projectSlug] = {
	  				'title' : ajaxData.find('#portfolio-div h1').text(),
	  				'type' : ajaxData.find('#portfolio-div h2').text(),
	  				'description' : ajaxData.find('#portfolio-div .description').html(),
	  				'logo' : ajaxData.find('#portfolio-div .testimonial img').attr('src'),
	  				'quote' : ajaxData.find('#portfolio-div .testimonial blockquote').text(),
	  				'caption' : ajaxData.find('#portfolio-div .testimonial small').text(),
	  				'url' : ajaxData.find('#portfolio-div .testimonial a.url').attr('href')
	  			}
			}
  			
  			projectImages = ajaxData.find('.imagery img');
  			for (i = 1; i <= projectImages.length; i++) {
  				projectData[projectSlug]['image-' + i] = projectImages[i - 1];
  			}
	
			// Put the data into the new detail
			if (currentDetail.hasClass('select-clients-list')) {
				$('.list', currentDetail).html(projectData[projectSlug]['description']);
			}
			else {
				$('.description', currentDetail).html(projectData[projectSlug]['description']);
			}
			
			if (projectData[projectSlug]['logo']) {
				$('.testimonial img', currentDetail).attr('src', projectData[projectSlug]['logo']).attr('alt', projectData[projectSlug]['title'] + ' Logo');			
			}
			
			if (projectData[projectSlug]['url']) {
				$('.testimonial a.url', currentDetail).attr('href', projectData[projectSlug]['url']);
				$('.testimonial a.url', currentDetail).attr('title', projectData[projectSlug]['title']).show();
			}
			
			if (projectData[projectSlug]['quote'] != "") {
				$('.testimonial blockquote', currentDetail).html('<span class="open">&ldquo;</span>' + projectData[projectSlug]['quote'] + '<span class="close"> &rdquo;</span>');
				$('.testimonial small', currentDetail).html('&ndash; ' + projectData[projectSlug]['caption']);
			}
			$('.imagery', currentDetail).append('<div class="slide-nav" />');
			
			// Single detail image
			$('.imagery ul', currentDetail).append('<li rel="' + projectSlug + '-1"></li>');
			$('.imagery ul li', currentDetail).append(projectData[projectSlug]['image-1']);
		
			
			// We've got all the data, so let's use it
			initialPortfolioCaption = $('.nav-panel h4', '#portfolio').text();
			if (currentDetail.hasClass('select-clients-list')) {
				$('.nav-panel h3', '#portfolio').text(projectData[projectSlug]['title']).fadeIn(300);			
			}
			else {
				$('.nav-panel h3', '#portfolio').text(projectData[projectSlug]['title']).fadeIn(300);
				$('.nav-panel h4', '#portfolio').text(projectData[projectSlug]['type']).fadeIn(300);	
				$('.nav-panel .toggle', '#portfolio').activateToggleNav();
			}	
			$('.nav-panel a.back-button', '#portfolio').fadeIn(300);	
			currentDetail
				.css('width', '100%')
				.css('right', 0)
				.fadeIn(300)
				.backToPortfolioStart();	

  		}
	});
}


// Project back button
$.fn.backToPortfolioStart = function() {
	backButton = $('a.back-button', '#portfolio');
	goodbyeDetail = this;
	projectNav = $('nav', '#portfolio');
	backButton.click(function() {
		goodbyeDetail
			.css('width', goodbyeDetail.width())
			.animate({right : '-' + goodbyeDetail.width()}, 300, 'swing', function() {
				goodbyeDetail.remove();
				projectNav.showMe().delay(100).animate({right : '0'}, 300, 'swing', function() {
					$(this).css('position', 'static');
				});
				$('.nav-panel h3', '#portfolio').fadeOut(200);
				$('.nav-panel h4', '#portfolio').fadeOut(200).text(initialPortfolioCaption).fadeIn(200);
				$('.nav-panel .back-button', '#portfolio').fadeOut(200);
				$('.nav-panel .toggle', '#portfolio').fadeOut(300);
				$('.nav-panel .toggle a', '#portfolio').deactivate();
			});
			
		return false;
	})
}

// Project toggle between images/details
$.fn.activateToggleNav = function() {
	toggle = this;
	$('.images', toggle).activate().click(function() {
		if (!$(this).hasClass('active')) {
			$('#article-portfolio .details', '#portfolio').animate({top : $('#article-portfolio .details', '#portfolio').height()}, 400);
			$('#article-portfolio .imagery', '#portfolio').animate({top : '0px'}, 400);
			$('a', toggle).deactivate();
			$(this).activate();
		}
	});
	$('.casestudy', toggle).click(function() {
		if (!$(this).hasClass('active')) {
			$('#article-portfolio .imagery', '#portfolio').animate({top : '-' + $('#article-portfolio .imagery', '#portfolio').height()}, 400);
			$('#article-portfolio .details', '#portfolio').animate({top : '0px'}, 400);
			$('a', toggle).deactivate();
			$(this).activate();
			clearInterval(autoSlide);
		}
	});
	toggle.fadeIn(300);
}

// Project detail slideshow
$.fn.detailSlideNav = function() {
	container = this;
	slides = $('li', this);
	for (i=0; i < slides.length; i++) {
		// Show the first slide, hide the others
		if (slides.eq(i).hasClass('active')) {
			slides.eq(i).css('top', 0);
		}
		else {
			slides.eq(i).css('top', '-' + slides.eq(i).height() + 'px');
		}
		
		// Create the slide nav
		name = slides.eq(i).attr('rel');
		var active = '';
		$('.slide-nav', container).append('<a rel="' + name + '" title="' + (i + 1) + '">&nbsp;</a>');
		if (i == 0) {
			active = 'active';
		}
		$('.slide-nav', container).css('width', (slides.length * 27) + 'px');
		$('.slide-nav a:eq(' + i + ')', container)
			.addClass(active)
			.click(function() {
				if (!$(this).hasClass('active')) {
					$(this).transitionDetailSlide();
					clearInterval(autoSlide);
				}
			});		
	}
	
	// Set up the auto progression
	count = 1;
	autoSlide = setInterval(function() {
		if (count < slides.length) {
			$('.slide-nav a', '#portfolio').eq(count).transitionDetailSlide();
			count++;
		}
		else {
			count = 0;
			$('.slide-nav a', '#portfolio').eq(count).transitionDetailSlide();
			clearInterval(autoSlide);	
		}
	}, 6000);
}

// Slide transition
$.fn.transitionDetailSlide = function() {
	$('.imagery .slide-nav a', '#portfolio').deactivate();
	this.activate()
	currentSlide = $('.imagery li.active', '#portfolio');
	newSlide = $('.imagery li[rel="' + this.attr('rel') + '"]', '#portfolio');
	
	currentSlide.css('top', '0px').animate({top : currentSlide.height()}, 700).deactivate();
	newSlide.css('top', '-' + newSlide.height() + 'px').show().animate({top : '0px'}, 700).activate();
}



///////////////////////////////////////
// Team
///////////////////////////////////////

// Size profile pictures by percent
$.fn.resizeTeam = function() {
	var teamWidth = $('#team nav').innerWidth();
	var count = $('#team nav a').length;
	teamWidth = teamWidth / count;
	$('#team nav a').width(teamWidth);
};

// Add hover to team
$.fn.expandTeam = function() {
	container = this;
	executed = false;
	live = true;
	die = false;
	
	var originalWidth;
	var currentPerson;
	var measure;
	var currentIndex;
	var startHover;
	var totalTeam = $('a', container);
	
	totalTeam
		.attr('title', '')
		.live('mouseenter', expand)
		.live('mouseleave', contract)
		.live('click', function() {
			$(this).setupTeamDetail('member');
			contract();
			return false;	
		});

	function expand() {
		originalWidth = totalTeam.eq(0).width();
		
		//alert('container: ' + container.width() + ' / original: ' + originalWidth + ' / org*count' + (originalWidth * $('a', container).length));
		clearTimeout(startHover);
		if (live && $('a[rel="team"]', 'header').hasClass('active')) {			
			currentPerson = $(this);
			measure = (300 - currentPerson.width()) / 2;
			currentIndex = currentPerson.index();
			
			startHover = setTimeout(function() {
				clearTimeout(startHover);
				live = false;	
				
				//check for first and last conditions
				if( currentPerson.index() == 0 ) { // if its the first
					measure = 0;
				}
				if( currentPerson.index() == totalTeam.length-1 ) { // if its the last
					measure = measure*2;
				}
				$('.wrapper', container).stop(true,true).animate({'margin-left' : '-' + measure + 'px'}, 310); 
				currentPerson.stop(true,true).animate({ width : '300px' }, 310);
				$('.info', currentPerson).animate({bottom : '0px'}, 310);
				$('.info .name, .info .role', currentPerson).removeClass('hidden');
				$('.info .icon', currentPerson).fadeTo(200, .85);
				
				die = true;
				
			}, 125);
		}
	};
	
	function contract() {
		if (die) {	
			die = false;
						
			$('.wrapper', container).stop(true,true).animate({'margin-left' : '0'}, 310 ); 		
			$('.info', currentPerson).animate({bottom : '-65px'}, 310);
			$('.info .icon', currentPerson).fadeTo(200, .6);
			$('.info .name, .info .role', currentPerson).addClass('hidden');
			
			currentPerson.stop(true,true).animate({width : originalWidth}, 310, function() {
				live = true;
			});
		}
	};
};	

// Animate the nav and setup the new team detail
$.fn.setupTeamDetail = function(type) {
	teamNav = $('nav', '#team');
	newContent = $(this).attr('rel');
	
	if (!teamNav.hasClass('hidden')) {
		teamNav
		.css('width', teamNav.width())
		.css('position', 'absolute')
		.css('top', '9px')
		.css('right', '0')
		.animate({right : teamNav.css('width')}, 300, function() {
			teamNav.hideMe();		
		});
	}
		
	// Differentiate between the two types of team details
	if (type == 'member') {
		newArticle = $(teamDetailTemplate).clone();
		newArticle.addClass(newContent);
		$('.border-wrapper','#team').append(newArticle);
		$('#article-team', '#team').populateTeamDetail();	
	}	
	else if (type == 'more') {
		newArticle = $(teamOverviewTemplate).clone();
		newArticle.addClass(newContent);
		$('.border-wrapper','#team').append(newArticle);
		$('#article-team', '#team').populateTeamOverview();	
	}
}

// Add content to the new team detail via AJAX
$.fn.populateTeamDetail = function() {
	currentDetail = $(this);
	teamSlug = currentDetail.attr('class');
	// Gather the data and push it to our global JSON object
	$.ajax({
  		url: 'team-members/' + teamSlug + '/',
  		dataType: 'text',
 		success: function(text) {
  			ajaxData = $(text);  			  			
  			teamData[teamSlug] = {
  				'title' : ajaxData.find('#team-div h1').text(),
  				'role' : ajaxData.find('#team-div h2').text(),
  				'bg' : ajaxData.find('#team-div img.detail').attr('src'),
  				'placement' : ajaxData.find('#team-div .bio').attr('alt'),
  				'bio' : ajaxData.find('#team-div .bio').html(),
  				'email' : ajaxData.find('#team-div .email').html(),
  				'phone' : ajaxData.find('#team-div .phone').html(),
				'dribbble' : ajaxData.find('#team-div .dribbble').html()
  			}

			// Put the data into the new detail
			currentDetail
				.css('background', 'url(' + teamData[teamSlug]['bg'] + ') no-repeat top')
				.css('height', '500px')
				.css('width', '100%')
				.fadeIn(300);  
			$('.details', currentDetail)
				.css('float', teamData[teamSlug]['placement'])
				.append(teamData[teamSlug]['bio'])
				.append(teamData[teamSlug]['email'])
				.append(' &nbsp; <span style="color:#DE7028;">' + teamData[teamSlug]['phone'] + '</span>')
				.append(teamData[teamSlug]['dribbble'])
				.delay(300)
				.fadeIn(200);
			
			initialTeamCaption = $('.nav-panel h4', '#team').html();
			$('.nav-panel h3', '#team').delay(200).text(teamData[teamSlug]['title']).fadeIn(200);
			$('.nav-panel h4', '#team').fadeOut(200).text(teamData[teamSlug]['role']).fadeIn(200);
			$('.nav-panel .back-button', '#team').fadeIn(200);
			
			$.history.load('!team');
			$.history.load('!team/' + teamSlug);
			
			currentDetail.backToTeamStart();
  		}
	});
}

// Set up Team Learn More

$.fn.teamLearnMore = function() {
	$(this).click(function() {
		$(this).setupTeamDetail('more');

		return false;
	});
}


// Add content to the new team overview via AJAX
$.fn.populateTeamOverview = function() {
	currentDetail = $(this);
	teamSlug = currentDetail.attr('class');
	// Gather the data and push it to our global JSON object
	$.ajax({
  		url: teamSlug + '/',
  		dataType: 'text',
 		success: function(text) {
  			ajaxData = $(text);  			  			
  			teamData[teamSlug] = {
  				'one' : ajaxData.find('.column-one').html(),
  				'two' : ajaxData.find('.column-two').html()
  			}

			// Put the data into the new detail
			currentDetail
				.css('height', '500px')
				.css('width', '100%')
				.fadeIn(300);  
			$('.overview', currentDetail)
				.prepend('<div class="column">' + teamData[teamSlug]['two'] + '</div>')
				.prepend('<div class="column">' + teamData[teamSlug]['one'] + '</div>')
				.delay(300)
				.fadeIn(200);
			
			initialTeamCaption = $('.nav-panel h4', '#team').html();
			$('.nav-panel h3', '#team').delay(200).text('Team Overview').fadeIn(200);
			$('.nav-panel h4', '#team').fadeOut(200);
			$('.nav-panel .back-button', '#team').fadeIn(200);
			
			currentDetail.backToTeamStart();
  		}
	});
}


// Team back button
$.fn.backToTeamStart = function() {
	backButton = $('a.back-button', '#team');
	goodbyeDetail = this;
	teamNav = $('nav', '#team');

	backButton.click(function() {
		goodbyeDetail
			.css('width', goodbyeDetail.width())
			.css('position', 'absolute')
			.css('right', '0')
			.animate({right : '-' + goodbyeDetail.width()}, 300, 'swing', function() {
				goodbyeDetail.remove();
				teamNav.showMe().delay(100).animate({right : '0'}, 300, 'swing', function() {
					$(this).css('position', 'static');
				});
				$('.nav-panel h3', '#team').fadeOut(200);
				$('.nav-panel h4', '#team').fadeOut(200).html(initialTeamCaption).fadeIn(200);
				$('.nav-panel .back-button', '#team').fadeOut(200);
			});
			
		return false;
	})
}

///////////////////////////////////////
// Helper Functions
///////////////////////////////////////

	// Add an active class
	$.fn.activate = function() {
		return this.addClass('active');
	};
	
	// Add an active class
	$.fn.deactivate = function() {
		return this.removeClass('active');
	};
	
	// Add a hidden class
	$.fn.hideMe = function() {
		return this.hide().addClass('hidden');
	};
	
	// Remove hidden class
	$.fn.showMe = function() {
		return this.show().removeClass('hidden');
	};	

	// Replace (at) in mailto email address with @
	$.fn.mailto = function() {
		return this.each(function(){
			var email = $(this).html().replace(/\s*\(.+\)\s*/, "@");
			$(this).before('<a href="mailto:' + email + '" rel="nofollow" title="Email ' + email + '">' + email + '</a>').remove();
		});
	};	
		
})( jQuery );


